root/vtcross/trunk/src/include/vtcross/cbr.h @ 468

Revision 468, 8.3 KB (checked in by bhilburn, 15 years ago)

Fully implemented the CBR as a C++ class, and using it within the CBR_CE
component.

Line 
1/*
2 Copyright 2009 Virginia Polytechnic Institute and State University 
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7 
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15*/
16
17/* This file contains the declaration *and* default implementation of a VTCROSS
18 * case-based reasoner.
19 *
20 * This class can be used either as-is, or with re-implementations of some/all
21 * of the functions.  All functions are declared virtual, and so may be
22 * overridden in the cognitive engine source file as necessary. In addition,
23 * internal class members are declared 'protected', so that they may be
24 * inherited by child implementations.
25 */
26
27
28#ifndef CBR_H
29#define CBR_H
30
31#include <cstdlib>
32#include <cstring>
33#include <cstdio>
34#include <stdint.h>
35#include <string>
36#include <sqlite3.h>
37
38#include "vtcross/common.h"
39#include "vtcross/debug.h"
40#include "vtcross/error.h"
41
42using namespace std;
43
44
45#define DATABASENAME "vtcross_cbr"
46
47
48class CBR
49{
50    public:
51        /* Default constructor and preferred constructor for the CBR class. */
52        CBR();
53        CBR(char *_filename, char *_tablename, char *_cols[], uint32_t _len);
54
55        /* Destructor for the CBR class. Note that this destructor will be
56         * called automatically by any derived classes, and so child classes
57         * should not repeat the freeing actions performed in this function. */
58        virtual ~CBR();
59
60        virtual int32_t OpenDatabase();
61
62        virtual int32_t ExecuteCommand();
63
64        virtual int32_t ExecuteSearchCommand(float *_retvals);
65
66        virtual void Print();
67
68        virtual int32_t Search(char *_names[], int32_t *_ops, float *_vals, \
69                uint32_t _n, float *_retvals);
70
71        virtual int32_t Update(char *_where[], char *_set[], float *_wherevals, \
72                float *_setvals, uint32_t _wherelen, uint32_t _setlen);
73
74        virtual int32_t AddRow(char *_cols[], float *_vals, uint32_t _len);
75
76    protected:
77        char filename[64];
78        char tablename[64];
79        char command[2048];
80        sqlite3 *db;
81        uint32_t numColumns;
82};
83
84
85int32_t
86callback(void *notUsed, int argc, char **argv, char **azColName)
87{
88    int i;
89    for(i=0; i<argc; i++){
90        printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
91    }
92    printf("\n");
93    return 0;
94}
95
96
97// open a database or create a database if it does not exist
98int32_t
99CBR::OpenDatabase()
100{
101    int32_t rc;
102
103    rc = sqlite3_open(filename, &db);
104    if(rc) {
105        WARNING("Can't open database: %s\n", sqlite3_errmsg(db));
106        sqlite3_close(db);
107        exit(1);
108    }
109
110    return rc;
111}
112
113
114// execute command
115int32_t
116CBR::ExecuteCommand()
117{
118    int rc;
119    char *zErrMsg = 0;
120
121    rc = sqlite3_exec(db, command, callback, 0, &zErrMsg);
122    if( rc!=SQLITE_OK){
123        fprintf(stderr, "SQL error: %s: %s\n", zErrMsg, command);
124        sqlite3_free(zErrMsg);
125    }
126
127    return rc;
128}
129
130
131// execute search command
132int32_t
133CBR::ExecuteSearchCommand(float *_retvals)
134{
135    int rc;
136    unsigned int i;
137
138    sqlite3_stmt * pStatement;
139    rc = sqlite3_prepare_v2(db, command, -1, &pStatement, NULL);
140    if (rc == SQLITE_OK){
141        if (sqlite3_step(pStatement) == SQLITE_ROW){
142            for (i=0; i<numColumns; ++i)
143                _retvals[i] = sqlite3_column_double(pStatement, i);
144        } else {
145                    printf("CBR:: No matched results returning default.\n");
146                        rc=31337;
147                }
148    } else {
149                printf("CBR:: Error executing SQL statement. rc = %i\n%s\n",rc,command);
150    }
151
152    sqlite3_finalize(pStatement);
153   
154    return rc;
155}
156
157
158// create database
159CBR::CBR(char * _filename, char * _tablename, char * _cols[], unsigned int _len)
160{
161    // create database
162
163    // copy filename
164    unsigned int i=0;
165    strcpy(filename, _filename);
166
167    // execute create database command
168    // database handle
169    //_cbr->db = NULL;
170    OpenDatabase();
171
172    // create table
173
174    // copy tablename
175    strcpy(tablename, _tablename);
176
177    // number of columns in the table
178    numColumns = _len;
179
180    // generate command
181    strcpy(command, "CREATE TABLE ");
182    strcat(command, tablename);
183    strcat(command, "(");
184    for (i=0; i<numColumns; i++) {
185        strcat(command, _cols[i]);
186        strcat(command, " FLOAT");
187        if (i != numColumns-1) // not last entry
188            strcat(command, ", ");
189    }
190    strcat(command, ");");
191
192    // execute create table command
193    ExecuteCommand();
194}
195
196
197// free space
198CBR::~CBR()
199
200    // generate command, remove a table with its content
201    strcpy(command, "drop table ");
202    strcat(command, tablename);
203
204    // execute delete command
205    ExecuteCommand();
206
207    // clean the database
208    strcpy(command, "vacuum");
209    ExecuteCommand();
210}
211
212
213// print
214void
215CBR::Print()
216{
217    // generate commandi
218    strcpy(command, "select ");
219    strcat(command, tablename);
220    strcat(command, ".* from ");
221    strcat(command, tablename);
222    strcat(command, ";");
223
224    // execute print (select all)  command
225    ExecuteCommand();
226    printf("database %s, table %s:\n", filename, tablename);
227}
228
229//
230// cbr search
231//int cbr_search(cbr _cbr, char *_names[], int * _ops, float *_vals, unsigned int _n, float *_retvals);
232int32_t
233CBR::Search(
234    char *_names[],
235    int * _ops,
236    float *_vals,
237    unsigned int _n,
238    float *_retvals)
239{   
240    int rc;
241        const char *ops_str[] = {"==", "!=", ">", ">=", "<", "<="};
242    // generate command
243    strcpy(command, "select ");
244    strcat(command, tablename);
245    strcat(command, ".* from ");
246    strcat(command, tablename);
247    strcat(command, " where ");
248
249    unsigned int i;
250    char str_buffer[64];
251    printf("number of ops %d:\n", _n);
252    for (i=0; i<_n; i++) {
253        // ensure valid ops value
254        if (_ops[i] < 0 || _ops[i] > 5) {
255            printf("error: cbr_search(), invalid ops id : %d\n", _ops[i]);
256            exit(1);
257        }
258
259        strcat(command, _names[i]);
260        strcat(command, ops_str[_ops[i]]);
261    printf("search command: %s\n", command);
262        sprintf(str_buffer, "%E", _vals[i]);
263        strcat(command, str_buffer);
264
265
266        if (i<_n-1)
267            strcat(command, " AND ");
268        else
269            strcat(command, " order by utility desc;");
270    }
271
272
273    rc = ExecuteSearchCommand(_retvals);
274   
275    return rc;
276}
277
278
279// update a row
280int32_t
281CBR::Update(char *_where[], char*_set[], float *_wherevals, float *_setvals,
282                unsigned int _wherelen, unsigned int _setlen)
283{
284    unsigned int i;
285   
286    // generate command
287    strcpy(command, "UPDATE ");
288    strcat(command, tablename);
289   
290    strcat(command, " SET ");
291    for (i=0; i<_setlen; i++) {
292        strcat(command, _set[i]);
293        strcat(command, " = ");
294        sprintf(command, "%s%f", command, _setvals[i]);
295        strcat(command, "  ");
296        if (i != _setlen-1) // not last entry
297            strcat(command, ", ");
298    }
299    strcat(command, " WHERE ");
300
301    for (i=0; i<_wherelen; i++) {
302        strcat(command, _where[i]);
303        strcat(command, " = ");
304        sprintf(command, "%s%f", command, _wherevals[i]);
305        strcat(command, "  ");
306        if (i != _wherelen-1) // not last entry
307            strcat(command, "AND ");
308    }
309    strcat(command, ";");
310   
311    // execute add command
312    ExecuteCommand();
313
314    return 0;
315}
316
317// cbr add a row
318int32_t
319CBR::AddRow(char *_cols[], float *_vals, unsigned int _len)
320{
321    unsigned int i;
322   
323    // generate command
324    strcpy(command, "insert into ");
325    strcat(command, tablename);
326   
327    strcat(command, " (");
328    for (i=0; i<_len; i++) {
329        strcat(command, _cols[i]);
330        if (i != numColumns-1) // not last entry
331            strcat(command, ", ");
332    }
333    strcat(command, ") ");
334
335    strcat(command, " values(");
336    for (i=0; i<_len; i++) {
337        // ???? how to fill the values if _cbr->numColumns != _len
338        // assume = in the following
339        sprintf(command, "%s%f", command, _vals[i]);
340        if (i != numColumns-1) // not last entry
341            strcat(command, ", ");
342    }
343    strcat(command, ");");
344   
345    // execute add command
346    ExecuteCommand();
347
348    return 0;
349}
350
351#endif
Note: See TracBrowser for help on using the browser.