root/vtcross/branches/nikhil/crossmodel2/src/cognitive_engines/CBR_CE/CBR_CE.cpp @ 568

Revision 568, 16.6 KB (checked in by nikhil, 14 years ago)
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 provides a default implementation for a case-based-reasoning based
18 * cognitive engine.
19 */
20
21#include "CBR_CE.h"
22#include <iostream>
23
24
25using namespace std;
26
27// ZERO is consider +1 sign
28inline int signof(int nos) { return ( (nos < 0) ? -1:1 ); }
29
30
31
32
33CBR_CE::CBR_CE(const char* serverName, const char* serverPort, \
34        const int32_t numFields, const bool SML) \
35    : CognitiveEngine(serverName, serverPort, numFields, SML)
36{
37    BuildCognitiveEngine();
38}
39
40
41Parameter*
42CBR_CE::GetSolution(Observable *observables, Parameter *currentParameters, Utility *utilities)
43{
44    LOG("Cognitive Engine:: Generating solution.\n");
45
46    string searchNames[radioInfo->numUtilities];
47
48    for(size_t i = 0; i < radioInfo->numUtilities; i++) {
49        searchNames[i] = uList[i].name;
50    }
51
52    float searchVals[radioInfo->numUtilities];
53
54    for(size_t i = 0; i < radioInfo->numUtilities; i++) {
55        searchVals[i] = uList[i].target;
56    }
57
58    uint32_t numberColumns = radioInfo->numParameters + radioInfo->numUtilities + radioInfo->numObservables + 1;
59   
60    float returnValues[numberColumns];
61   
62    int searchOps[radioInfo->numUtilities];
63    for(size_t i = 0; i < radioInfo->numUtilities; i++) {
64
65        /* If the goal is to maximum, set the search operation to
66         * return values greater than the target.
67         *
68         * If the goal is to minimize, set the search operation to
69         * return values less than the target.
70         *
71         * NOTE: the values '2' and '4' here are from some old preprocesser
72         * definitions, which I will copy here until I can figure out just what
73         * exactly they were for:
74                42      #define EQ 0    // equals
75                43      #define NE 1    // not equals
76                44      #define GT 2    // greater than
77                45      #define GE 3    // greater than or equal to
78                46      #define LT 4    // less than
79                47      #define LE 5    // less than or equal to
80         */
81        if(strcmp(uList[i].goal.c_str(), "max") == 0) {
82            searchOps[i] = 2;
83        } else if(strcmp(uList[i].goal.c_str(), "min") == 0) {
84            searchOps[i] = 4;
85        }
86    }
87
88    /* CBR specific call */
89    uint32_t rc = myCBR1->Search(searchNames, searchOps, searchVals,
90            radioInfo->numUtilities, returnValues);
91
92    if(rc == 0){
93        /* Adapt the returned parameters to meet the objective */
94        LOG("Cognitive Engine:: Found\n");
95       
96        FineTune();
97
98    } else if(rc == 31337) {
99        LOG("Cognitive Engine:: Not Found.\n");
100        /* No rows in the CBR, pick default parameters */
101        /* Currently this is hard coded and implementation specific! */
102
103     int Pt = optList->Ptune;
104 // helps to cycle from on parameter to another..
105
106        for (int i = 0; i < radioInfo->numParameters; i++) {
107            returnValues[i] = currentParameters[i].value;
108        }
109   
110        returnValues[Pt] = currentParameters[Pt].value + pList[Pt].step*(optList->Slope[Pt]);
111                   
112////////////////////   LIMITER   /////////////////////////////
113            if (returnValues[Pt] > pList[Pt].max) {
114                std::cout << "SORRY CANT EXCEED MAX VALUE" << std::endl;
115                returnValues[Pt] = returnValues[Pt] - pList[Pt].step;
116                optList->Ptune += 1;
117            }
118            if (returnValues[Pt] < pList[Pt].min) {
119                std::cout << "SORRY CANT GO BELOW MIN VALUE" << std::endl;
120                returnValues[Pt] = returnValues[Pt] + pList[Pt].step ;
121                optList->Ptune += 1;             
122            }
123
124            if (optList->Ptune > radioInfo->numParameters) {
125                optList->Ptune = 0;             
126            }
127/////////////////////////////////////////////////////////////
128       
129
130        for (int i = 0; i < radioInfo->numUtilities; i++) {
131            returnValues[radioInfo->numParameters + i] = uList[i].value;
132        }
133
134        for (int i = 0; i < radioInfo->numObservables; i++) {
135            returnValues[radioInfo->numParameters + radioInfo->numUtilities + i] = oList[i].value;
136        }
137
138    size_t returnValueIndex = 0;
139    for(size_t i = 0; i < radioInfo->numParameters; i++) {
140        pList[i].value = returnValues[returnValueIndex];
141        returnValueIndex++;
142    }
143    for(size_t i = 0; i < radioInfo->numUtilities; i++) {
144        uList[i].value = returnValues[returnValueIndex];
145        returnValueIndex++;
146    }
147    for(size_t i = 0; i < radioInfo->numObservables; i++) {
148        oList[i].value = returnValues[returnValueIndex];
149        returnValueIndex++;
150    }
151    returnValues[returnValueIndex] = 0;
152
153    string allNames[numberColumns];
154    size_t allNameIndex = 0;
155    for(size_t i = 0; i < radioInfo->numParameters; i++) {
156        allNames[allNameIndex] = pList[i].name;
157        allNameIndex++;
158    }
159    for(size_t i = 0; i < radioInfo->numUtilities; i++) {
160        allNames[allNameIndex] = uList[i].name;
161        allNameIndex++;
162    }
163    for(size_t i = 0; i < radioInfo->numObservables; i++) {
164        allNames[allNameIndex] = oList[i].name;
165        allNameIndex++;
166    }
167    allNames[allNameIndex] = "TotalWeight";
168
169    // Add row to CBR.
170    myCBR1->AddRow(allNames, returnValues, returnValueIndex + 1);
171    myCBR2->AddRow(allNames, returnValues, returnValueIndex + 1);       
172        } else {
173        LOG("Cognitive Engine:: Search return an invalid value.\n");
174    }
175
176    return pList;
177}
178
179
180void
181CBR_CE::ReceiveFeedback(Observable *observables, Parameter *parameters, Utility *utilities)
182{
183    LOG("Cognitive Engine:: Receiving feedback.\n");
184   
185    uint32_t numberColumns = radioInfo->numParameters + radioInfo->numUtilities + radioInfo->numObservables + 1;
186
187    uint32_t whereLen = radioInfo->numParameters;
188    uint32_t setLen = radioInfo->numUtilities + radioInfo->numObservables + 1;
189
190
191    float whereValue[whereLen];
192    float setValue[setLen];
193    string whereList[whereLen];
194    string setList[setLen];
195
196
197// Calculating total weight
198        float TotalWeight = 0;
199        int Penalty = 100;
200
201    for(size_t i = 0; i < radioInfo->numParameters; i++) {
202        whereList[i] = parameters[i].name;
203        whereValue[i] = parameters[i].value;
204        TotalWeight += parameters[i].value*(optList->Pweights[i]);
205    }
206
207    size_t returnValueIndex = 0;
208    for(size_t i = 0; i < radioInfo->numUtilities; i++) {
209        setList[returnValueIndex] = utilities[i].name;
210        setValue[returnValueIndex] = utilities[i].value;
211        if ((utilities[i].value > uList[i].target && uList[i].goal == "max") || (utilities[i].value < uList[i].target && uList[i].goal == "min"))
212                TotalWeight += abs(utilities[i].value - uList[i].target)*(optList->Uweights[i]);
213        else
214                TotalWeight += abs(utilities[i].value - uList[i].target)*(optList->Uweights[i])*Penalty;   
215        returnValueIndex++;
216    }
217    for(size_t i = 0; i < radioInfo->numObservables; i++) {
218        setList[returnValueIndex] = observables[i].name;
219        setValue[returnValueIndex] = observables[i].value;
220        returnValueIndex++;
221    }
222        setList[returnValueIndex] = "TotalWeight";
223        setValue[returnValueIndex] = TotalWeight;
224/////
225       
226myCBR1->Update(whereList,setList,whereValue,setValue,whereLen,setLen);
227
228// MAIN SELF LEARNING CODE HERE //
229
230int searchOps[radioInfo->numParameters];
231string searchNames[radioInfo->numParameters];
232float searchVals[radioInfo->numParameters];
233float returnValues[numberColumns];
234
235
236for (int L = 0; L < radioInfo->numParameters ; L++) {
237   searchOps[L] = 0;
238   searchNames[L] = parameters[L].name;
239   searchVals[L] = parameters[L].value;
240}
241
242
243for (int lp = 0; lp < radioInfo->numParameters; lp++ ) {
244
245   searchOps[lp] = (optList->Slope[lp] == -1)?2:4;   
246
247   uint32_t rc = myCBR1->Search(searchNames, searchOps, searchVals,radioInfo->numParameters, returnValues);
248  if(rc == 0) {
249        std::cout << "case found for learning for parameter : " << lp << std::endl;
250
251///////////
252       
253                std::cout << "CASE STUDY" << std::endl;
254                std::cout << "returnvalue ber " << returnValues[radioInfo->numParameters] << std::endl;
255                std::cout << "BER current value " << utilities[0].value << std::endl;
256               
257       
258
259/////////
260
261    for (int ul = 0; ul < radioInfo->numUtilities; ul++) {
262        int rl = radioInfo->numParameters + ul;
263        if( abs(1 - returnValues[rl]/utilities[ul].value) > optList->PoC ) {
264            if(optList->Trend[lp][ul] == 0.0) {
265
266                if ((returnValues[rl] > utilities[ul].value) && optList->Status[lp][ul] >= 0 ) {
267                    optList->Status[lp][ul] += 1;
268                }
269                else if ( ((returnValues[rl]) < utilities[ul].value) && optList->Status[lp][ul] <= 0) {
270                    optList->Status[lp][ul] -= 1;
271                }               
272                else {
273                    optList->Status[lp][ul] = 0;
274                }
275           
276                if (abs(optList->Status[lp][ul]) > 2) {
277                    optList->Trend[lp][ul] = signof(optList->Status[lp][ul]);
278                }
279            }
280            else if ( optList->Trend[lp][ul] == 1 && (returnValues[rl] > utilities[ul].value) && optList->Status[lp][ul] >= 0 ) {
281                    optList->Status[lp][ul] += 1;
282            }
283            else if ( optList->Trend[lp][ul] == -1 && (returnValues[rl] > utilities[ul].value) && optList->Status[lp][ul] <= 0) {
284                    optList->Status[lp][ul] -= 1;
285            }
286            else {
287                    optList->Status[lp][ul] = 0;
288                    optList->Trend[lp][ul] = 0;
289            }
290
291
292
293        }
294    }
295  }
296  else if (rc == 31337) {   
297         std::cout << "No case found for parameter: " << lp << std::endl;
298  }
299   searchOps[lp] = 0;
300
301
302}
303
304
305// updating slope matrix..
306// AS OF NOW VALID ONLY FOR ONE UTILITY
307    for (int i = 0; i < radioInfo->numParameters; i++) {
308        if ( (uList[0].goal == "min" && optList->Trend[i][0] < 0) || (uList[0].goal == "max" && optList->Trend[i][0] > 0) ) {
309           optList->Slope[i] = -1;
310        }
311        else if ( (uList[0].goal == "min" && optList->Trend[i][0] >= 0) || (uList[0].goal == "max" && optList->Trend[i][0] <= 0) ) { 
312           optList->Slope[i] = 1;       
313        }
314    }
315
316   std::cout << "Ptune " << optList->Ptune << std::endl;
317   std::cout << "Status1 " << optList->Status[0][0] << std::endl;
318   std::cout << "Status2 " << optList->Status[1][0] << std::endl;
319   std::cout << "Slope1 " << optList->Slope[0] << std::endl;
320   std::cout << "Slope2 " << optList->Slope[1] << std::endl;
321   std::cout << "Trend1 " << optList->Trend[0][0] << std::endl;
322   std::cout << "Trend2 " << optList->Trend[1][0] << std::endl;
323
324 /// end of MAIN CODE //
325
326
327}
328
329void
330CBR_CE::BuildCognitiveEngine()
331{
332    string filename = "exdb";
333    string tablename1 = "data1";
334    string tablename2 = "data2";
335
336        //// NEW SET OF VARIABLES ///
337
338        optList->Uweights = new float[radioInfo->numUtilities];
339        optList->Pweights = new float[radioInfo->numParameters];
340        optList->Slope = new int[radioInfo->numParameters];
341
342///// we have to assume 10 utilities maxxx!!!! VERY important
343
344        optList->Status = new float[radioInfo->numParameters][10];
345        optList->Trend = new float[radioInfo->numParameters][10];
346////////////////////////////////////////////////////////////// 
347
348
349////////////initializing Opt_List members here/////
350
351        optList->PoC = 0.01;
352        optList->Ptune = 0; // starting with most tunable parameter.. (widest range .. )
353
354        for (int x = 0; x < radioInfo->numParameters; x++) {
355                optList->Pweights[x] = 1/(pList[x].step);
356                optList->Slope[x] = 1;
357        }
358
359
360
361        for (size_t i = 0; i < radioInfo->numUtilities; i++) {
362                optList->Uweights[i] = 10;
363        }
364
365
366        for (size_t i = 0; i < radioInfo->numParameters; i++) {
367                for (size_t k = 0; k < radioInfo->numUtilities; k++) {
368                        optList->Status[i][k] = 0;
369                        optList->Trend[i][k] = 0;
370                }
371        }
372////////////////////////////////////////////////////////////////////////
373
374
375
376
377    uint32_t numberColumns = radioInfo->numParameters + radioInfo->numUtilities \
378                             + radioInfo->numObservables + 1;
379
380    string cols[numberColumns];
381    size_t columnIndex = 0;
382
383
384    for (size_t i = 0; i < radioInfo->numParameters; i++){
385        cols[columnIndex] = pList[i].name;
386        columnIndex++;
387    }
388    for (size_t i = 0; i < radioInfo->numUtilities; i++){
389        cols[columnIndex] = uList[i].name;
390        columnIndex++;
391    }     
392    for (size_t i = 0; i < radioInfo->numObservables; i++){   
393        cols[columnIndex] = oList[i].name;
394        columnIndex++;
395    }
396    cols[columnIndex] = "TotalWeight"; 
397
398    myCBR1 = new CBR(filename, tablename1, cols, numberColumns);       
399
400    myCBR2 = new CBR(filename, tablename2, cols, numberColumns);       
401
402
403}
404
405
406void
407CBR_CE::PerformUpdatePerformance()
408{
409
410    /* Receive Set of current Parameters */
411    char buffer[256];
412    memset(buffer, 0, 256);
413    ReadMessage(commandSocketFD, buffer);
414    uint32_t numParameters = atoi(buffer);
415
416    Parameter *p = new Parameter[numParameters];
417
418    for(size_t i = 0; i < numParameters; i++) {
419        memset(buffer, 0, 256);
420        ReadMessage(commandSocketFD, buffer);
421        p[i].name = std::string(buffer);
422
423        memset(buffer, 0, 256);
424        ReadMessage(commandSocketFD, buffer);
425        p[i].value = atof(buffer);
426    }
427
428
429    /* Receive Set of Observables */
430    memset(buffer, 0, 256);
431    ReadMessage(commandSocketFD, buffer);
432    uint32_t numObservables = atoi(buffer);
433
434    Observable *o = new Observable[numObservables];
435
436    for(size_t i = 0; i < numObservables; i++) {
437        memset(buffer, 0, 256);
438        ReadMessage(commandSocketFD, buffer);
439        o[i].name = std::string(buffer);
440
441        memset(buffer, 0, 256);
442        ReadMessage(commandSocketFD, buffer);
443        o[i].value = atof(buffer);
444    }
445
446
447    /* Receive Set of Utilities */
448    memset(buffer, 0, 256);
449    ReadMessage(commandSocketFD, buffer);
450    uint32_t numUtilities = atoi(buffer);
451   
452    Utility *u = new Utility[numUtilities];
453
454    for(size_t i = 0; i < numUtilities; i++) {
455        memset(buffer, 0, 256);
456        ReadMessage(commandSocketFD, buffer);
457        u[i].name = std::string(buffer);
458       
459        memset(buffer, 0, 256);
460        ReadMessage(commandSocketFD, buffer);
461        u[i].value = atof(buffer);
462    }
463 
464    ReceiveFeedback(o, p, u);
465
466    delete [] o;
467    delete [] p;
468    delete [] u;
469}
470
471
472void
473CBR_CE::PerformRequestOptimization()
474{
475    /* Receive Set of Observables */
476    LOG("\nCognitive Engine:: Receiving Observables\n");
477
478    char buffer[256];
479    memset(buffer, 0, 256);
480    ReadMessage(commandSocketFD,buffer);
481    uint32_t numObservables = atoi(buffer);
482
483    Observable *o = new Observable[numObservables];
484
485    for(size_t i = 0; i < numObservables; i++) {
486        memset(buffer, 0, 256);
487        ReadMessage(commandSocketFD, buffer);
488        o[i].name = std::string(buffer);
489
490        memset(buffer, 0, 256);
491        ReadMessage(commandSocketFD, buffer);
492        o[i].value = atof(buffer);
493    } 
494
495    /* Receive Set of current Parameters */
496    LOG("Cognitive Engine:: Receiving Current Transmission Parameters\n");
497
498    memset(buffer, 0, 256);
499    ReadMessage(commandSocketFD, buffer);
500    uint32_t numCurrentParameters = atoi(buffer);
501
502    Parameter *cp = new Parameter[numCurrentParameters];
503
504    for(size_t i = 0; i < numCurrentParameters; i++) {
505        memset(buffer, 0, 256);
506        ReadMessage(commandSocketFD, buffer);
507        cp[i].name = std::string(buffer);
508
509        memset(buffer, 0, 256);
510        ReadMessage(commandSocketFD, buffer);
511        cp[i].value = atof(buffer);
512    }
513
514    /* Receive Set of Utilities */
515    LOG("Cognitive Engine:: Receiving Utilities\n");
516
517    memset(buffer, 0, 256);
518    ReadMessage(commandSocketFD, buffer);
519    uint32_t numUtilities = atoi(buffer);
520
521    Utility *u = new Utility[numUtilities];
522
523    for(size_t i = 0; i < numUtilities; i++) {
524        memset(buffer, 0, 256);
525        ReadMessage(commandSocketFD, buffer);
526        u[i].name = std::string(buffer);
527
528        memset(buffer, 0, 256);
529        ReadMessage(commandSocketFD, buffer);
530        u[i].value = atof(buffer);
531    }
532
533
534
535 
536    LOG("Cognitive Engine:: Processing parameters....\n");
537
538    Parameter *solutionSet;
539   
540    solutionSet = GetSolution(o,cp,u);
541
542 
543   
544    LOG("Cognitive Engine:: Sending Optimal Parameters to Application.\n");
545    char numParametersChar[10];
546    char solutionValue[50];
547    sprintf(numParametersChar, "%i", radioInfo->numParameters);
548    SendMessage(commandSocketFD, numParametersChar);
549    for(size_t i = 0; i < radioInfo->numParameters; i++) {
550        SendMessage(commandSocketFD, solutionSet[i].name.c_str());
551        memset(solutionValue, 0, 50);
552        sprintf(solutionValue, "%f", solutionSet[i].value);
553        SendMessage(commandSocketFD, solutionValue);
554    }
555
556    delete [] o;
557    delete [] cp;
558    delete [] u;
559}
560
561
562void
563CBR_CE::PerformResetEngineCognitive()
564{
565    Reset();
566}
567
568
569void
570CBR_CE::PerformShutdownEngineCognitive()
571{
572    Shutdown();
573}
574
575void
576CBR_CE::FineTune()
577{
578
579        std::cout << "UNDER DEVELOPMENT" << std::endl;
580
581}
Note: See TracBrowser for help on using the browser.