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

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