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

Revision 563, 16.7 KB (checked in by nikhil, 14 years ago)

final codes

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 = 10;
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                        std::cout << "TREND GETTING UPDATED" << std::endl;
279                }
280            }
281            else if ( optList->Trend[lp][ul] == 1 && (returnValues[rl] > utilities[ul].value) && optList->Status[lp][ul] >= 0 ) {
282                    optList->Status[lp][ul] += 1;
283            }
284            else if ( optList->Trend[lp][ul] == -1 && (returnValues[rl] > utilities[ul].value) && optList->Status[lp][ul] <= 0) {
285                    optList->Status[lp][ul] -= 1;
286            }
287            else {
288                    optList->Status[lp][ul] = 0;
289                    optList->Trend[lp][ul] = 0;
290            }
291
292
293
294        }
295    }
296  }
297  else if (rc == 31337) {   
298         std::cout << "No case found for parameter: " << lp << std::endl;
299  }
300   searchOps[lp] = 0;
301
302
303}
304
305
306// updating slope matrix..
307// AS OF NOW VALID ONLY FOR ONE UTILITY
308    for (int i = 0; i < radioInfo->numParameters; i++) {
309        if ( (uList[0].goal == "min" && optList->Trend[i][0] < 0) || (uList[0].goal == "max" && optList->Trend[i][0] > 0) ) {
310           optList->Slope[i] = -1;
311        }
312        else if ( (uList[0].goal == "min" && optList->Trend[i][0] >= 0) || (uList[0].goal == "max" && optList->Trend[i][0] <= 0) ) { 
313           optList->Slope[i] = 1;       
314        }
315    }
316
317   std::cout << "Ptune " << optList->Ptune << std::endl;
318   std::cout << "Status1 " << optList->Status[0][0] << std::endl;
319   std::cout << "Status2 " << optList->Status[1][0] << std::endl;
320   std::cout << "Slope1 " << optList->Slope[0] << std::endl;
321   std::cout << "Slope2 " << optList->Slope[1] << std::endl;
322   std::cout << "Trend1 " << optList->Trend[0][0] << std::endl;
323   std::cout << "Trend2 " << optList->Trend[1][0] << std::endl;
324
325 /// end of MAIN CODE //
326
327
328}
329
330void
331CBR_CE::BuildCognitiveEngine()
332{
333    string filename = "exdb";
334    string tablename1 = "data1";
335    string tablename2 = "data2";
336
337        //// NEW SET OF VARIABLES ///
338
339        optList->Uweights = new float[radioInfo->numUtilities];
340        optList->Pweights = new float[radioInfo->numParameters];
341        optList->Slope = new int[radioInfo->numParameters];
342
343///// we have to assume 10 utilities maxxx!!!! VERY important
344
345        optList->Status = new float[radioInfo->numParameters][10];
346        optList->Trend = new float[radioInfo->numParameters][10];
347////////////////////////////////////////////////////////////// 
348
349
350////////////initializing Opt_List members here/////
351
352        optList->PoC = 0.01;
353        optList->Ptune = 0; // starting with most tunable parameter.. (widest range .. )
354
355        for (int x = 0; x < radioInfo->numParameters; x++) {
356                std::cout << x << std::endl;
357                optList->Pweights[x] = 1/(pList[x].step);
358                optList->Slope[x] = 1;
359        }
360
361
362
363        for (size_t i = 0; i < radioInfo->numUtilities; i++) {
364                optList->Uweights[i] = 1;
365        }
366
367
368        for (size_t i = 0; i < radioInfo->numParameters; i++) {
369                for (size_t k = 0; k < radioInfo->numUtilities; k++) {
370                        optList->Status[i][k] = 0;
371                        optList->Trend[i][k] = 0;
372                }
373        }
374////////////////////////////////////////////////////////////////////////
375
376
377
378
379    uint32_t numberColumns = radioInfo->numParameters + radioInfo->numUtilities \
380                             + radioInfo->numObservables + 1;
381
382    string cols[numberColumns];
383    size_t columnIndex = 0;
384
385
386    for (size_t i = 0; i < radioInfo->numParameters; i++){
387        cols[columnIndex] = pList[i].name;
388        columnIndex++;
389    }
390    for (size_t i = 0; i < radioInfo->numUtilities; i++){
391        cols[columnIndex] = uList[i].name;
392        columnIndex++;
393    }     
394    for (size_t i = 0; i < radioInfo->numObservables; i++){   
395        cols[columnIndex] = oList[i].name;
396        columnIndex++;
397    }
398    cols[columnIndex] = "TotalWeight"; 
399
400    myCBR1 = new CBR(filename, tablename1, cols, numberColumns);       
401
402    myCBR2 = new CBR(filename, tablename2, cols, numberColumns);       
403
404
405}
406
407
408void
409CBR_CE::PerformUpdatePerformance()
410{
411
412    /* Receive Set of current Parameters */
413    char buffer[256];
414    memset(buffer, 0, 256);
415    ReadMessage(commandSocketFD, buffer);
416    uint32_t numParameters = atoi(buffer);
417
418    Parameter *p = new Parameter[numParameters];
419
420    for(size_t i = 0; i < numParameters; i++) {
421        memset(buffer, 0, 256);
422        ReadMessage(commandSocketFD, buffer);
423        p[i].name = std::string(buffer);
424
425        memset(buffer, 0, 256);
426        ReadMessage(commandSocketFD, buffer);
427        p[i].value = atof(buffer);
428    }
429
430
431    /* Receive Set of Observables */
432    memset(buffer, 0, 256);
433    ReadMessage(commandSocketFD, buffer);
434    uint32_t numObservables = atoi(buffer);
435
436    Observable *o = new Observable[numObservables];
437
438    for(size_t i = 0; i < numObservables; i++) {
439        memset(buffer, 0, 256);
440        ReadMessage(commandSocketFD, buffer);
441        o[i].name = std::string(buffer);
442
443        memset(buffer, 0, 256);
444        ReadMessage(commandSocketFD, buffer);
445        o[i].value = atof(buffer);
446    }
447
448
449    /* Receive Set of Utilities */
450    memset(buffer, 0, 256);
451    ReadMessage(commandSocketFD, buffer);
452    uint32_t numUtilities = atoi(buffer);
453   
454    Utility *u = new Utility[numUtilities];
455
456    for(size_t i = 0; i < numUtilities; i++) {
457        memset(buffer, 0, 256);
458        ReadMessage(commandSocketFD, buffer);
459        u[i].name = std::string(buffer);
460       
461        memset(buffer, 0, 256);
462        ReadMessage(commandSocketFD, buffer);
463        u[i].value = atof(buffer);
464    }
465 
466    ReceiveFeedback(o, p, u);
467
468    delete [] o;
469    delete [] p;
470    delete [] u;
471}
472
473
474void
475CBR_CE::PerformRequestOptimization()
476{
477    /* Receive Set of Observables */
478    LOG("\nCognitive Engine:: Receiving Observables\n");
479
480    char buffer[256];
481    memset(buffer, 0, 256);
482    ReadMessage(commandSocketFD,buffer);
483    uint32_t numObservables = atoi(buffer);
484
485    Observable *o = new Observable[numObservables];
486
487    for(size_t i = 0; i < numObservables; i++) {
488        memset(buffer, 0, 256);
489        ReadMessage(commandSocketFD, buffer);
490        o[i].name = std::string(buffer);
491
492        memset(buffer, 0, 256);
493        ReadMessage(commandSocketFD, buffer);
494        o[i].value = atof(buffer);
495    } 
496
497    /* Receive Set of current Parameters */
498    LOG("Cognitive Engine:: Receiving Current Transmission Parameters\n");
499
500    memset(buffer, 0, 256);
501    ReadMessage(commandSocketFD, buffer);
502    uint32_t numCurrentParameters = atoi(buffer);
503
504    Parameter *cp = new Parameter[numCurrentParameters];
505
506    for(size_t i = 0; i < numCurrentParameters; i++) {
507        memset(buffer, 0, 256);
508        ReadMessage(commandSocketFD, buffer);
509        cp[i].name = std::string(buffer);
510
511        memset(buffer, 0, 256);
512        ReadMessage(commandSocketFD, buffer);
513        cp[i].value = atof(buffer);
514    }
515
516    /* Receive Set of Utilities */
517    LOG("Cognitive Engine:: Receiving Utilities\n");
518
519    memset(buffer, 0, 256);
520    ReadMessage(commandSocketFD, buffer);
521    uint32_t numUtilities = atoi(buffer);
522
523    Utility *u = new Utility[numUtilities];
524
525    for(size_t i = 0; i < numUtilities; i++) {
526        memset(buffer, 0, 256);
527        ReadMessage(commandSocketFD, buffer);
528        u[i].name = std::string(buffer);
529
530        memset(buffer, 0, 256);
531        ReadMessage(commandSocketFD, buffer);
532        u[i].value = atof(buffer);
533    }
534
535
536
537 
538    LOG("Cognitive Engine:: Processing parameters....\n");
539
540    Parameter *solutionSet;
541   
542    solutionSet = GetSolution(o,cp,u);
543
544 
545   
546    LOG("Cognitive Engine:: Sending Optimal Parameters to Application.\n");
547    char numParametersChar[10];
548    char solutionValue[50];
549    sprintf(numParametersChar, "%i", radioInfo->numParameters);
550    SendMessage(commandSocketFD, numParametersChar);
551    for(size_t i = 0; i < radioInfo->numParameters; i++) {
552        SendMessage(commandSocketFD, solutionSet[i].name.c_str());
553        memset(solutionValue, 0, 50);
554        sprintf(solutionValue, "%f", solutionSet[i].value);
555        SendMessage(commandSocketFD, solutionValue);
556    }
557
558    delete [] o;
559    delete [] cp;
560    delete [] u;
561}
562
563
564void
565CBR_CE::PerformResetEngineCognitive()
566{
567    Reset();
568}
569
570
571void
572CBR_CE::PerformShutdownEngineCognitive()
573{
574    Shutdown();
575}
576
577void
578CBR_CE::FineTune()
579{
580
581        std::cout << "UNDER DEVELOPMENT" << std::endl;
582
583}
Note: See TracBrowser for help on using the browser.