root/vtcross/branches/nikhil/CBRcode_development/CBR_CE.cpp @ 558

Revision 558, 17.7 KB (checked in by nikhil, 14 years ago)

Personal CBR_CE codes for futher development

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//inline int signof(int nos) { return (nos==0)?0:(nos<0?-1:1); }
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/*
97        No need or random adaptation since it will get updated
98        using update function call
99        if(returnValues[numberColumns-1] < 0) {
100            returnValues[2] = returnValues[2] - 15;
101            returnValues[3] = returnValues[3] - 2;
102        } else {
103            returnValues[2] = returnValues[2] + 15;
104            returnValues[3] = returnValues[3] + 2;
105        }
106*/
107    } else if(rc == 31337) {
108        LOG("Cognitive Engine:: Not Found.\n");
109        /* No rows in the CBR, pick default parameters */
110        /* Currently this is hard coded and implementation specific! */
111
112        for (int i = 0; i < radioInfo->numParameters; i++) {
113
114            returnValues[i] = currentParameters[i].value + pList[i].step*Slope[i];
115
116
117////////////////////   LIMITER   /////////////////////////////
118            if (returnValues[i] > pList[i].max) {
119                std::cout << "SORRY CANT EXCEED MAX VALUE" << std::endl;
120                returnValues[i] = returnValues[i] - pList[i].step;
121            }
122            if (returnValues[i] < pList[i].min) {
123                std::cout << "SORRY CANT GO BELOW MIN VALUE" << std::endl;
124                returnValues[i] = returnValues[i] + pList[i].step ;             
125            }
126/////////////////////////////////////////////////////////////
127
128        }
129
130        for (int i = 0; i < radioInfo->numUtilities; i++)
131            returnValues[radioInfo->numParameters + i] = uList[i].value;
132
133        for (int i = 0; i < radioInfo->numObservables; i++)
134            returnValues[radioInfo->numParameters + radioInfo->numUtilities + i] = oList[i].value;
135
136    size_t returnValueIndex = 0;
137    for(size_t i = 0; i < radioInfo->numUtilities; i++) {
138        pList[i].value = returnValues[returnValueIndex];
139        returnValueIndex++;
140    }
141    for(size_t i = 0; i < radioInfo->numParameters; i++) {
142        uList[i].value = returnValues[returnValueIndex];
143        returnValueIndex++;
144    }
145    for(size_t i = 0; i < radioInfo->numObservables; i++) {
146        oList[i].value = returnValues[returnValueIndex];
147        returnValueIndex++;
148    }
149    returnValues[returnValueIndex] = 0;
150
151    string allNames[numberColumns];
152    size_t allNameIndex = 0;
153    for(size_t i = 0; i < radioInfo->numParameters; i++) {
154        allNames[allNameIndex] = pList[i].name;
155        allNameIndex++;
156    }
157    for(size_t i = 0; i < radioInfo->numUtilities; i++) {
158        allNames[allNameIndex] = uList[i].name;
159        allNameIndex++;
160    }
161    for(size_t i = 0; i < radioInfo->numObservables; i++) {
162        allNames[allNameIndex] = oList[i].name;
163        allNameIndex++;
164    }
165    allNames[allNameIndex] = "TotalWeight";
166
167    // Add row to CBR.
168    myCBR1->AddRow(allNames, returnValues, returnValueIndex + 1);
169    myCBR2->AddRow(allNames, returnValues, returnValueIndex + 1);       
170        } else {
171        LOG("Cognitive Engine:: Search return an invalid value.\n");
172    }
173
174
175    return pList;
176}
177
178
179void
180CBR_CE::ReceiveFeedback(Observable *observables, Parameter *parameters, Utility *utilities)
181{
182    LOG("Cognitive Engine:: Receiving feedback.\n");
183   
184    uint32_t numberColumns = radioInfo->numParameters + radioInfo->numUtilities + radioInfo->numObservables + 1;
185
186    uint32_t whereLen = radioInfo->numParameters;
187    uint32_t setLen = radioInfo->numUtilities + radioInfo->numObservables + 1;
188
189
190    float whereValue[whereLen];
191    float setValue[setLen];
192    string whereList[whereLen];
193    string setList[setLen];
194
195/*
196    size_t columnObsIndex = 0;
197    for (size_t i = 0; i < radioInfo->numObservables; i++){
198        obsList[columnObsIndex] = observables[i].name;
199        columnObsIndex++;
200    } 
201    obsList[columnObsIndex] = "utility";
202
203    size_t columnIndex = 0;
204    for (size_t i = 0; i < radioInfo->numParameters; i++){
205        nameList[columnIndex] = parameters[i].name;
206        columnIndex++;
207    }   
208    for (size_t i = 0; i < radioInfo->numUtilities; i++){
209        nameList[columnIndex] = uList[i].name;
210        columnIndex++;
211    }   
212
213    size_t obsValueIndex = 0;
214    for(size_t i = 0; i < radioInfo->numObservables; i++) {
215        obsVals[obsValueIndex] = observables[i].value;
216        obsValueIndex++;
217    }
218
219///  Calculate Utility
220   float newUtilityValue = 0;
221
222    for(size_t i = 0; i < radioInfo->numUtilities; i++) {
223        newUtilityValue = newUtilityValue + (uList[i].target - observables[i].value);
224    }
225    obsVals[obsValueIndex] = newUtilityValue;
226
227    size_t returnValueIndex = 0;
228    for(size_t i = 0; i < radioInfo->numParameters; i++) {
229        valList[returnValueIndex] = parameters[i].value;
230        returnValueIndex++;
231    }
232    for(size_t i = 0; i < radioInfo->numUtilities; i++) {
233        valList[returnValueIndex] = uList[i].target;
234        returnValueIndex++;
235    }
236*/
237        float TotalWeight = 0;
238        int Penalty = 10;
239
240    for(size_t i = 0; i < radioInfo->numParameters; i++) {
241        whereList[i] = parameters[i].name;
242        whereValue[i] = parameters[i].value;
243        TotalWeight += parameters[i].value*Pweights[i];
244    }
245
246    size_t returnValueIndex = 0;
247    for(size_t i = 0; i < radioInfo->numUtilities; i++) {
248        setList[returnValueIndex] = utilities[i].name;
249        setValue[returnValueIndex] = utilities[i].value;
250        if ((utilities[i].value > uList[i].target && uList[i].goal == "max") || (utilities[i].value < uList[i].target && uList[i].goal == "min"))
251                TotalWeight += abs(utilities[i].value - uList[i].target)*Uweights[i];
252        else
253                TotalWeight += abs(utilities[i].value - uList[i].target)*Uweights[i]*Penalty;   
254        returnValueIndex++;
255    }
256    for(size_t i = 0; i < radioInfo->numObservables; i++) {
257        setList[returnValueIndex] = observables[i].name;
258        setValue[returnValueIndex] = observables[i].value;
259        returnValueIndex++;
260    }
261        setList[returnValueIndex] = "TotalWeight";
262        setValue[returnValueIndex] = TotalWeight;
263       
264myCBR1->Update(whereList,setList,whereValue,setValue,whereLen,setLen);
265
266// MAIN CODE HERE //
267
268int searchOps[radioInfo->numParameters];
269string searchNames[radioInfo->numParameters];
270float searchVals[radioInfo->numParameters];
271float returnValues[numberColumns];
272
273
274for (int L = 0; L < radioInfo->numParameters ; L++) {
275   searchOps[L] = 0;
276   searchNames[L] = parameters[L].name;
277   searchVals[L] = parameters[L].value;
278}
279
280
281for (int lp = 0; lp < radioInfo->numParameters; lp++ ) {
282
283   searchOps[lp] = (Slope[lp] == -1)?2:4;   
284
285   uint32_t rc = myCBR1->Search(searchNames, searchOps, searchVals,radioInfo->numParameters, returnValues);
286
287    for (int ul = 0; ul < radioInfo->numUtilities; ul++) {
288        int rl = radioInfo->numParameters + ul;
289        if( (1 - returnValues[rl]/utilities[ul].value) > PoC ) {
290            if(Trend[lp][ul] == 0) {
291
292                if ((returnValues[rl] > utilities[ul].value) && Status[lp][ul] >= 0 ) {
293                    Status[lp][ul] += 1;
294                }
295                else if ( ((returnValues[rl]) < utilities[ul].value) && Status[lp][ul] ) {
296                    Status[lp][ul] -= 1;
297                }               
298                else {
299                    Status[lp][ul] = 0;
300                }
301           
302                if (abs(Status[lp][ul]) > 2) {
303                    Trend[lp][ul] = signof(Status[lp][ul]);
304                }
305            }
306            else if ( Trend[lp][ul] == 1 && (returnValues[rl] > utilities[ul].value) && Status[lp][ul] >= 0 ) {
307                    Status[lp][ul] += 1;
308            }
309            else if ( Trend[lp][ul] == -1 && (returnValues[rl] < utilities[ul].value) && Status[lp][ul] <= 0) {
310                    Status[lp][ul] -= 1;
311            }
312            else {
313                    Status[lp][ul] = 0;
314                    Trend[lp][ul] = 0; 
315            }
316
317
318
319        }
320    }
321
322}
323
324// updating slope matrix..
325// AS OF NOW VALID ONLY FOR ONE UTILITY
326    for (int i = 0; i < radioInfo->numParameters; i++) {
327        if ( (uList[0].goal == "min" && Trend[i][0] <= 0) || (uList[0].goal == "max" && Trend[i][0] >= 0) ) {
328            Slope[i] = 1;
329        }
330        else {
331            Slope[i] = -1;     
332        }
333    }
334
335
336
337 /// end of MAIN CODE //
338}
339
340void
341CBR_CE::BuildCognitiveEngine()
342{
343    string filename = "exdb";
344    string tablename1 = "data1";
345    string tablename2 = "data2";
346
347        //// NEW SET OF VARIABLES ///
348
349//      float * Pweights = new float[radioInfo->numParameters];
350        float * Uweights = new float[radioInfo->numUtilities];
351        float * Pweights = new float[radioInfo->numParameters];
352
353///// we have to assume 10 utilities maxxx!!!! VERY important
354
355        float (*Status)[10] = new float[radioInfo->numParameters][10];
356        float (*Trend)[10] = new float[radioInfo->numParameters][10];
357        float PoC = 0.1;
358        int * Slope = new int[radioInfo->numParameters];       
359
360//      InitialSetting();
361
362////////////initializing here since initialsetting giving wierd errors/////
363
364        for (int x = 0; x < radioInfo->numParameters; x++) {
365                std::cout << x << std::endl;
366                Pweights[x] = 1/(pList[x].step);
367                Slope[x] = 1;
368        }
369
370
371
372        for (size_t i = 0; i < radioInfo->numUtilities; i++) {
373                Uweights[i] = 1;
374        }
375
376
377        for (size_t i = 0; i < radioInfo->numParameters; i++) {
378                for (size_t k = 0; k < radioInfo->numUtilities; k++) {
379                        Status[i][k] = 0;
380                        Trend[i][k] = 0;
381                }
382        }
383////////////////////////////////////////////////////////////////////////
384
385
386
387
388    uint32_t numberColumns = radioInfo->numParameters + radioInfo->numUtilities \
389                             + radioInfo->numObservables + 1;
390
391    uint32_t numberParameters = radioInfo->numParameters;
392    uint32_t numberUtilities = radioInfo->numUtilities;
393
394    string cols[numberColumns];
395    string Plist[numberParameters];
396    string Ulist[numberUtilities];
397    float Utarget[numberUtilities];
398    string Ugoal[numberUtilities];
399
400    size_t columnIndex = 0;
401    size_t Pindex = 0;              // new
402    size_t Uindex = 0;              // new
403
404
405    for (size_t i = 0; i < radioInfo->numParameters; i++){
406        cols[columnIndex] = pList[i].name;
407        columnIndex++;
408        Plist[Pindex] = pList[i].name;   // new
409        Pindex++;                        // new
410    }
411    for (size_t i = 0; i < radioInfo->numUtilities; i++){
412        cols[columnIndex] = uList[i].name;
413        columnIndex++;
414        Ulist[Uindex] = uList[i].name;     // new
415        Utarget[Uindex] = uList[i].target; // new
416        Ugoal[Uindex] = uList[i].goal;     // new
417        Uindex++;                          // new
418
419    }     
420    for (size_t i = 0; i < radioInfo->numObservables; i++){   
421        cols[columnIndex] = oList[i].name;
422        columnIndex++;
423    }
424    cols[columnIndex] = "TotalWeight"; 
425
426    myCBR1 = new CBR(filename, tablename1, cols, numberColumns);       
427
428    myCBR2 = new CBR(filename, tablename2, cols, numberColumns);       
429
430
431
432}
433
434
435void
436CBR_CE::PerformUpdatePerformance()
437{
438
439    /* Receive Set of current Parameters */
440    char buffer[256];
441    memset(buffer, 0, 256);
442    ReadMessage(commandSocketFD, buffer);
443    uint32_t numParameters = atoi(buffer);
444
445    Parameter *p = new Parameter[numParameters];
446
447    for(size_t i = 0; i < numParameters; i++) {
448        memset(buffer, 0, 256);
449        ReadMessage(commandSocketFD, buffer);
450        p[i].name = std::string(buffer);
451
452        memset(buffer, 0, 256);
453        ReadMessage(commandSocketFD, buffer);
454        p[i].value = atof(buffer);
455    }
456
457
458    /* Receive Set of Observables */
459    memset(buffer, 0, 256);
460    ReadMessage(commandSocketFD, buffer);
461    uint32_t numObservables = atoi(buffer);
462
463    Observable *o = new Observable[numObservables];
464
465    for(size_t i = 0; i < numObservables; i++) {
466        memset(buffer, 0, 256);
467        ReadMessage(commandSocketFD, buffer);
468        o[i].name = std::string(buffer);
469
470        memset(buffer, 0, 256);
471        ReadMessage(commandSocketFD, buffer);
472        o[i].value = atof(buffer);
473    }
474
475
476    /* Receive Set of Utilities */
477    memset(buffer, 0, 256);
478    ReadMessage(commandSocketFD, buffer);
479    uint32_t numUtilities = atoi(buffer);
480   
481    Utility *u = new Utility[numUtilities];
482
483    for(size_t i = 0; i < numUtilities; i++) {
484        memset(buffer, 0, 256);
485        ReadMessage(commandSocketFD, buffer);
486        u[i].name = std::string(buffer);
487       
488        memset(buffer, 0, 256);
489        ReadMessage(commandSocketFD, buffer);
490        u[i].value = atof(buffer);
491    }
492 
493    ReceiveFeedback(o, p, u);
494
495    delete [] o;
496    delete [] p;
497    delete [] u;
498}
499
500
501void
502CBR_CE::PerformRequestOptimization()
503{
504    /* Receive Set of Observables */
505    LOG("\nCognitive Engine:: Receiving Observables\n");
506
507    char buffer[256];
508    memset(buffer, 0, 256);
509    ReadMessage(commandSocketFD,buffer);
510    uint32_t numObservables = atoi(buffer);
511
512    Observable *o = new Observable[numObservables];
513
514    for(size_t i = 0; i < numObservables; i++) {
515        memset(buffer, 0, 256);
516        ReadMessage(commandSocketFD, buffer);
517        o[i].name = std::string(buffer);
518
519        memset(buffer, 0, 256);
520        ReadMessage(commandSocketFD, buffer);
521        o[i].value = atof(buffer);
522    } 
523
524    /* Receive Set of current Parameters */
525    LOG("Cognitive Engine:: Receiving Current Transmission Parameters\n");
526
527    memset(buffer, 0, 256);
528    ReadMessage(commandSocketFD, buffer);
529    uint32_t numCurrentParameters = atoi(buffer);
530
531    Parameter *cp = new Parameter[numCurrentParameters];
532
533    for(size_t i = 0; i < numCurrentParameters; i++) {
534        memset(buffer, 0, 256);
535        ReadMessage(commandSocketFD, buffer);
536        cp[i].name = std::string(buffer);
537
538        memset(buffer, 0, 256);
539        ReadMessage(commandSocketFD, buffer);
540        cp[i].value = atof(buffer);
541    }
542
543    /* Receive Set of Utilities */
544    LOG("Cognitive Engine:: Receiving Utilities\n");
545
546    memset(buffer, 0, 256);
547    ReadMessage(commandSocketFD, buffer);
548    uint32_t numUtilities = atoi(buffer);
549
550    Utility *u = new Utility[numUtilities];
551
552    for(size_t i = 0; i < numUtilities; i++) {
553        memset(buffer, 0, 256);
554        ReadMessage(commandSocketFD, buffer);
555        u[i].name = std::string(buffer);
556
557        memset(buffer, 0, 256);
558        ReadMessage(commandSocketFD, buffer);
559        u[i].value = atof(buffer);
560    }
561
562
563
564 
565    LOG("Cognitive Engine:: Processing parameters....\n");
566
567    Parameter *solutionSet;
568   
569    solutionSet = GetSolution(o,cp,u);
570
571 
572   
573    LOG("Cognitive Engine:: Sending Optimal Parameters to Application.\n");
574    char numParametersChar[10];
575    char solutionValue[50];
576    sprintf(numParametersChar, "%i", radioInfo->numParameters);
577    SendMessage(commandSocketFD, numParametersChar);
578    for(size_t i = 0; i < radioInfo->numParameters; i++) {
579        SendMessage(commandSocketFD, solutionSet[i].name.c_str());
580        memset(solutionValue, 0, 50);
581        sprintf(solutionValue, "%f", solutionSet[i].value);
582        SendMessage(commandSocketFD, solutionValue);
583    }
584
585    delete [] o;
586    delete [] cp;
587    delete [] u;
588}
589
590void CBR_CE::InitialSetting()
591{
592
593        std::cout << "inside initilsetting method" << std::endl;
594
595        for (int x = 0; x < radioInfo->numParameters; x++) {
596                std::cout << x << std::endl;
597                Pweights[x] = 1/(pList[x].step);
598                Slope[x] = 0;
599        }
600
601
602
603        for (size_t i = 0; i < radioInfo->numUtilities; i++) {
604                Uweights[i] = 1;
605        }
606
607
608        for (size_t i = 0; i < radioInfo->numParameters; i++) {
609                for (size_t k = 0; k < radioInfo->numUtilities; k++) {
610                        Status[i][k] = 0;
611                        Trend[i][k] = 0;
612                }
613        }
614
615}
616
617
618void
619CBR_CE::PerformResetEngineCognitive()
620{
621    Reset();
622}
623
624
625void
626CBR_CE::PerformShutdownEngineCognitive()
627{
628    Shutdown();
629}
630 
Note: See TracBrowser for help on using the browser.