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

Revision 470, 11.3 KB (checked in by bhilburn, 15 years ago)

Converted the OSSIE CE over to the C++ CBR by creating a child class of
the base CBR. Code is ugly, needs to be cleaned.

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
37#include <sqlite3.h>
38
39#include "vtcross/common.h"
40#include "vtcross/debug.h"
41#include "vtcross/error.h"
42
43using namespace std;
44
45
46#define DATABASENAME "vtcross_cbr"
47
48
49class CBR
50{
51    public:
52        /* Constructors for the CBR class. */
53        CBR(){};
54        CBR(char *_filename, char *_tablename, char *_cols[], uint32_t _len);
55        CBR(char *_filename, char *_tablename, char *_cols[], \
56                char *_primcols[], uint32_t _len, uint32_t  _primlen);
57
58        /* Destructor for the CBR class. Note that this destructor will be
59         * called automatically by any derived classes, and so child classes
60         * should not repeat the freeing actions performed in this function. */
61        virtual ~CBR();
62
63        virtual int32_t OpenDatabase();
64
65        virtual int32_t ExecuteCommand();
66
67        virtual int32_t ExecuteSearchCommand(float *_retvals);
68
69        virtual void Print();
70
71        virtual int32_t Search(char *_names[], int32_t *_ops, float *_vals, \
72                uint32_t _n, float *_retvals);
73        virtual int32_t SearchSum(char *_name, float *_retvals);
74        virtual int32_t SearchRand(char *_names[], int * _ops, float *_vals, unsigned int _n, \
75            float *_retvals);
76
77        virtual int32_t Update(char *_where[], char *_set[], float *_wherevals, \
78                float *_setvals, uint32_t _wherelen, uint32_t _setlen);
79
80        virtual int32_t AddRow(char *_cols[], float *_vals, uint32_t _len);
81
82    protected:
83        char filename[64];
84        char tablename[64];
85        char command[2048];
86        sqlite3 *db;
87        uint32_t numColumns;
88};
89
90
91int32_t
92callback(void *notUsed, int argc, char **argv, char **azColName)
93{
94    int i;
95    for(i=0; i<argc; i++){
96        printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
97    }
98    printf("\n");
99    return 0;
100}
101
102
103// open a database or create a database if it does not exist
104int32_t
105CBR::OpenDatabase()
106{
107    int32_t rc;
108
109    rc = sqlite3_open(filename, &db);
110    if(rc) {
111        WARNING("Can't open database: %s\n", sqlite3_errmsg(db));
112        sqlite3_close(db);
113        exit(1);
114    }
115
116    return rc;
117}
118
119
120// execute command
121int32_t
122CBR::ExecuteCommand()
123{
124    int rc;
125    char *zErrMsg = 0;
126
127    rc = sqlite3_exec(db, command, callback, 0, &zErrMsg);
128    if( rc!=SQLITE_OK){
129        fprintf(stderr, "SQL error: %s: %s\n", zErrMsg, command);
130        sqlite3_free(zErrMsg);
131    }
132
133    return rc;
134}
135
136
137// execute search command
138int32_t
139CBR::ExecuteSearchCommand(float *_retvals)
140{
141    int rc;
142    unsigned int i;
143
144    sqlite3_stmt * pStatement;
145    rc = sqlite3_prepare_v2(db, command, -1, &pStatement, NULL);
146    if (rc == SQLITE_OK){
147        if (sqlite3_step(pStatement) == SQLITE_ROW){
148            for (i=0; i<numColumns; ++i)
149                _retvals[i] = sqlite3_column_double(pStatement, i);
150        } else {
151                    printf("CBR:: No matched results returning default.\n");
152                        rc=31337;
153                }
154    } else {
155                printf("CBR:: Error executing SQL statement. rc = %i\n%s\n",rc,command);
156    }
157
158    sqlite3_finalize(pStatement);
159   
160    return rc;
161}
162
163
164// create database
165CBR::CBR(char * _filename, char * _tablename, char * _cols[], unsigned int _len)
166{
167    // create database
168
169    // copy filename
170    unsigned int i=0;
171    strcpy(filename, _filename);
172
173    // execute create database command
174    // database handle
175    //db = NULL;
176    OpenDatabase();
177
178    // create table
179
180    // copy tablename
181    strcpy(tablename, _tablename);
182
183    // number of columns in the table
184    numColumns = _len;
185
186    // generate command
187    strcpy(command, "CREATE TABLE ");
188    strcat(command, tablename);
189    strcat(command, "(");
190    for (i=0; i<numColumns; i++) {
191        strcat(command, _cols[i]);
192        strcat(command, " FLOAT");
193        if (i != numColumns-1) // not last entry
194            strcat(command, ", ");
195    }
196    strcat(command, ");");
197
198    // execute create table command
199    ExecuteCommand();
200}
201
202// create database
203CBR::CBR(char * _filename, char * _tablename,
204        char * _cols[], char * _primcols[], unsigned int _len,
205        unsigned int _primlen)
206{
207    // create database
208
209    // copy filename
210    unsigned int i=0;
211    strcpy(filename, _filename);
212
213    // execute create database command
214    // database handle
215    //db = NULL;
216    OpenDatabase();
217
218    // create table
219
220    // copy tablename
221    strcpy(tablename, _tablename);
222
223    // number of columns in the table
224    numColumns = _len;
225
226    // generate command
227    strcpy(command, "CREATE TABLE ");
228    strcat(command, tablename);
229    strcat(command, "(");
230    for (i=0; i<numColumns; i++) {
231        strcat(command, _cols[i]);
232        strcat(command, " FLOAT");
233        strcat(command, ", ");
234    }
235   strcat(command, "PRIMARY KEY (");
236    for (i=0; i<_primlen; i++) {
237        strcat(command, _primcols[i]);
238        if (i != _primlen-1) // not last entry
239            strcat(command, ", ");
240    }
241    strcat(command, "));");
242
243    // execute create table command
244    ExecuteCommand();
245}
246
247
248
249// free space
250CBR::~CBR()
251
252    // generate command, remove a table with its content
253    strcpy(command, "drop table ");
254    strcat(command, tablename);
255
256    // execute delete command
257    ExecuteCommand();
258
259    // clean the database
260    strcpy(command, "vacuum");
261    ExecuteCommand();
262}
263
264
265// print
266void
267CBR::Print()
268{
269    // generate commandi
270    strcpy(command, "select ");
271    strcat(command, tablename);
272    strcat(command, ".* from ");
273    strcat(command, tablename);
274    strcat(command, ";");
275
276    // execute print (select all)  command
277    ExecuteCommand();
278    printf("database %s, table %s:\n", filename, tablename);
279}
280
281//
282// cbr search
283//int cbr_search(cbr _cbr, char *_names[], int * _ops, float *_vals, unsigned int _n, float *_retvals);
284int32_t
285CBR::Search(
286    char *_names[],
287    int * _ops,
288    float *_vals,
289    unsigned int _n,
290    float *_retvals)
291{   
292    int rc;
293        const char *ops_str[] = {"==", "!=", ">", ">=", "<", "<="};
294    // generate command
295    strcpy(command, "select ");
296    strcat(command, tablename);
297    strcat(command, ".* from ");
298    strcat(command, tablename);
299    strcat(command, " where ");
300
301    unsigned int i;
302    char str_buffer[64];
303    printf("number of ops %d:\n", _n);
304    for (i=0; i<_n; i++) {
305        // ensure valid ops value
306        if (_ops[i] < 0 || _ops[i] > 5) {
307            printf("error: cbr_search(), invalid ops id : %d\n", _ops[i]);
308            exit(1);
309        }
310
311        strcat(command, _names[i]);
312        strcat(command, ops_str[_ops[i]]);
313    printf("search command: %s\n", command);
314        sprintf(str_buffer, "%E", _vals[i]);
315        strcat(command, str_buffer);
316
317
318        if (i<_n-1)
319            strcat(command, " AND ");
320        else
321            strcat(command, " order by utility desc;");
322    }
323
324
325    rc = ExecuteSearchCommand(_retvals);
326   
327    return rc;
328}
329
330// cbr search for a sum
331int32_t
332CBR::SearchSum(
333    char *_name,
334    float *_retvals)
335{   
336    int rc;
337    // generate command
338    strcpy(command, "select SUM( ");
339    strcat(command, tablename);
340    strcat(command, ".");
341    strcat(command, _name);
342    strcat(command, ") from ");
343    strcat(command, tablename);
344    strcat(command, ";");
345
346    //printf("search command: %s\n", command);
347
348    rc = ExecuteSearchCommand(_retvals);
349    /*printf("search result: ");
350    for (int i=0; i<numColumns; i++)
351        printf("%f, ",_retvals[i]);
352    printf("\n");
353    */
354    return rc;
355}
356
357
358// cbr search
359int32_t
360CBR::SearchRand(
361    char *_names[],
362    int * _ops,
363    float *_vals,
364    unsigned int _n,
365    float *_retvals)
366{   
367        const char *ops_str[] = {"==", "!=", ">", ">=", "<", "<="};
368    int rc;
369    // generate command
370    strcpy(command, "select ");
371    strcat(command, tablename);
372    strcat(command, ".* from ");
373    strcat(command, tablename);
374    strcat(command, " where ");
375
376    unsigned int i;
377    char str_buffer[64];
378    for (i=0; i<_n; i++) {
379        // ensure valid ops value
380        if (_ops[i] < 0 || _ops[i] > 5) {
381            printf("error: cbr_search(), invalid ops id : %d\n", _ops[i]);
382            exit(1);
383        }
384
385        strcat(command, _names[i]);
386        strcat(command, ops_str[_ops[i]]);
387        sprintf(str_buffer, "%E", _vals[i]);
388        strcat(command, str_buffer);
389
390        if (i<_n-1)
391            strcat(command, " AND ");
392        else
393            strcat(command, " order by RAND();");
394    }
395
396    //printf("search command: %s\n", command);
397
398    rc = ExecuteSearchCommand(_retvals);
399   
400    /*printf("search result: ");
401    for (i=0; i<numColumns; i++)
402        printf("%f, ",_retvals[i]);
403    printf("\n");
404*/
405    return rc;
406}
407
408
409
410
411// update a row
412int32_t
413CBR::Update(char *_where[], char*_set[], float *_wherevals, float *_setvals,
414                unsigned int _wherelen, unsigned int _setlen)
415{
416    unsigned int i;
417   
418    // generate command
419    strcpy(command, "UPDATE ");
420    strcat(command, tablename);
421   
422    strcat(command, " SET ");
423    for (i=0; i<_setlen; i++) {
424        strcat(command, _set[i]);
425        strcat(command, " = ");
426        sprintf(command, "%s%f", command, _setvals[i]);
427        strcat(command, "  ");
428        if (i != _setlen-1) // not last entry
429            strcat(command, ", ");
430    }
431    strcat(command, " WHERE ");
432
433    for (i=0; i<_wherelen; i++) {
434        strcat(command, _where[i]);
435        strcat(command, " = ");
436        sprintf(command, "%s%f", command, _wherevals[i]);
437        strcat(command, "  ");
438        if (i != _wherelen-1) // not last entry
439            strcat(command, "AND ");
440    }
441    strcat(command, ";");
442   
443    // execute add command
444    ExecuteCommand();
445
446    return 0;
447}
448
449// cbr add a row
450int32_t
451CBR::AddRow(char *_cols[], float *_vals, unsigned int _len)
452{
453    unsigned int i;
454   
455    // generate command
456    strcpy(command, "insert into ");
457    strcat(command, tablename);
458   
459    strcat(command, " (");
460    for (i=0; i<_len; i++) {
461        strcat(command, _cols[i]);
462        if (i != numColumns-1) // not last entry
463            strcat(command, ", ");
464    }
465    strcat(command, ") ");
466
467    strcat(command, " values(");
468    for (i=0; i<_len; i++) {
469        // ???? how to fill the values if numColumns != _len
470        // assume = in the following
471        sprintf(command, "%s%f", command, _vals[i]);
472        if (i != numColumns-1) // not last entry
473            strcat(command, ", ");
474    }
475    strcat(command, ");");
476   
477    // execute add command
478    ExecuteCommand();
479
480    return 0;
481}
482
483#endif
Note: See TracBrowser for help on using the browser.