-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkpgrep.c
1831 lines (1574 loc) · 86 KB
/
kpgrep.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2013, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the Greg Bronevetsky <bronevetsky1@llnl.gov> / <greg@bronevetsky.com>.
//
// LLNL-CODE-642002
// All rights reserved.
//
// This file is part of Sight. For details, see https://e-reports-ext.llnl.gov/pdf/781752.pdf or
// https://github.com/bronevet/sight.
//
// Licensed under the GNU Lesser General Public License (Lesser GPU) Version 2.1,
// February 1999; you may not use this file except in compliance with the License.
// The full licence is included in file LICENCE and you may obtain a copy of the
// License at:
// https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the license.
////////////////////////////////////////////////////////////////////////////////
#define MODULE_LAYOUT_C
#include "../../sight_layout.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <iostream>
#include <iomanip>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include "module_layout.h"
using namespace std;
using namespace sight::common;
namespace sight {
namespace layout {
// Escapes the whitespace in a node's name
string escapeNodeWhitespace(string s)
{
string out;
for(unsigned int i=0; i<s.length(); i++) {
if(s[i]==' ' || s[i]=='\t' || s[i]=='\n' || s[i]=='\r') {
} else
out += s[i];
}
return out;
}
// Record the layout handlers in this file
void* modularAppEnterHandler(properties::iterator props) { return new modularApp(props); }
void modularAppExitHandler(void* obj) { modularApp* ma = static_cast<modularApp*>(obj); delete ma; }
moduleLayoutHandlerInstantiator::moduleLayoutHandlerInstantiator() {
(*layoutEnterHandlers)["modularApp"] = &modularAppEnterHandler;
(*layoutExitHandlers )["modularApp"] = &modularAppExitHandler;
(*layoutEnterHandlers)["modularAppBody"] = &defaultEntryHandler;
(*layoutExitHandlers )["modularAppBody"] = &defaultExitHandler;
(*layoutEnterHandlers)["modularAppStructure"] = &defaultEntryHandler;
(*layoutExitHandlers )["modularAppStructure"] = &defaultExitHandler;
(*layoutEnterHandlers)["moduleTS"] = &moduleTraceStream::enterTraceStream;
(*layoutExitHandlers )["moduleTS"] = &defaultExitHandler;
(*layoutEnterHandlers)["module"] = &modularApp::enterModule;
(*layoutExitHandlers )["module"] = &modularApp::exitModule;
(*layoutEnterHandlers)["moduleMarker"] = &defaultEntryHandler;
(*layoutExitHandlers )["moduleMarker"] = &defaultExitHandler;
(*layoutEnterHandlers)["moduleCtrl"] = &defaultEntryHandler;
(*layoutExitHandlers )["moduleCtrl"] = &defaultExitHandler;
(*layoutEnterHandlers)["moduleEdge"] = &modularApp::addEdge;
(*layoutExitHandlers )["moduleEdge"] = &defaultExitHandler;
(*layoutEnterHandlers)["compModuleTS"] = &compModuleTraceStream::enterTraceStream;
(*layoutExitHandlers )["compModuleTS"] = &defaultExitHandler;
(*layoutEnterHandlers)["processedModuleTS"] = &processedModuleTraceStream::enterTraceStream;
(*layoutExitHandlers )["processedModuleTS"] = &defaultExitHandler;
}
moduleLayoutHandlerInstantiator moduleLayoutHandlerInstance;
// Points to the currently active instance of modularApp. There can be only one.
modularApp* modularApp::activeMA=NULL;
// The path the directory where output files of the graph widget are stored
// Relative to current path
string modularApp::outDir="";
// Relative to root of HTML document
string modularApp::htmlOutDir="";
// Stack of the modules that are currently in scope within this modularApp
list<sight::layout::moduleInfo> modularApp::mStack;
modularApp::modularApp(properties::iterator props) : block(properties::next(props)) {
// Register this modularApp instance (there can be only one)
assert(activeMA == NULL);
activeMA = this;
dbg.enterBlock(this, false, true);
initEnvironment();
appName = properties::get(props, "appName");
appID = properties::getInt(props, "appID");
dbg.ownerAccessing();
dbg << "<div id=\"module_container_"<<appID<<"\"></div>\n";
dbg.userAccessing();
ostringstream origDotFName; origDotFName << outDir << "/orig." << appID << ".dot";
dotFile.open(origDotFName.str().c_str());
dotFile << "digraph G {"<<endl;
dotFile << "\tcompound=true;"<<endl;
}
// Initialize the environment within which generated graphs will operate, including
// the JavaScript files that are included as well as the directories that are available.
void modularApp::initEnvironment() {
static bool initialized=false;
if(initialized) return;
initialized = true;
// Create the directory that holds the module-specific scripts
pair<string, string> paths = dbg.createWidgetDir("module");
outDir = paths.first;
htmlOutDir = paths.second;
//cout << "outDir="<<outDir<<" htmlOutDir="<<htmlOutDir<<endl;
dbg.includeFile("canviz-0.1");
//<!--[if IE]><script type="text/javascript" src="excanvas/excanvas.js"></script><![endif]-->
//dbg.includeWidgetScript("canviz-0.1/prototype/excanvas/excanvas.js", "text/javascript");
dbg.includeWidgetScript("canviz-0.1/prototype/prototype.js", "text/javascript");
dbg.includeWidgetScript("canviz-0.1/path/path.js", "text/javascript");
dbg.includeWidgetScript("canviz-0.1/canviz.css", "text/css");
dbg.includeWidgetScript("canviz-0.1/canviz.js", "text/javascript");
dbg.includeWidgetScript("canviz-0.1/x11colors.js", "text/javascript");
//dbg.includeWidgetScript("canviz-0.1/graphs/graphlist.js", "text/javascript");
//dbg.includeWidgetScript("canviz-0.1/graphs/layoutlist.js", "text/javascript");
dbg.includeFile("module/module.js"); dbg.includeWidgetScript("module/module.js", "text/javascript");
}
modularApp::~modularApp() {
// Unregister this modularApp instance (there can be only one)
assert(activeMA);
activeMA = NULL;
dotFile << "}"<<endl;
dotFile.close();
dbg.exitBlock();
// Lay out the dot graph
ostringstream origDotFName; origDotFName << outDir << "/orig." << appID << ".dot";
ostringstream placedDotFName; placedDotFName << outDir << "/placed." << appID << ".dot";
// Create the explicit DOT file that details the graph's layout
ostringstream cmd; cmd << ROOT_PATH << "/widgets/graphviz/bin/dot "<<origDotFName.str()<<" -Txdot -o"<<placedDotFName.str()<<"&";
//cout << "Command \""<<cmd.str()<<"\"\n";
system(cmd.str().c_str());
dbg.widgetScriptCommand(txt() <<
" var canviz_"<<appID<<";\n" <<
" canviz_"<<appID<<" = new Canviz('module_container_"<<appID<<"');\n" <<
" canviz_"<<appID<<".setScale(1);\n" <<
" canviz_"<<appID<<".load('"<<htmlOutDir<<"/placed." << appID << ".dot');\n");
// Delete all the traceStreams associated with the given trace, which emits their output
for(map<int, traceStream*>::iterator m=moduleTraces.begin(); m!=moduleTraces.end(); m++)
delete m->second;
}
string portName(common::module::ioT type, int index)
{ return txt()<<(type==common::module::input?"input":"output")<<"_"<<index; }
// Given the name of a trace attribute, the string representation of its polynomial fit and a line width
// emits to dotFile HTML where line breaks are inserted at approximately every lineWidth characters.
void printPolyFitStr(ostream& dotFile, std::string traceName, std::string polyFit, unsigned int lineWidth) {
unsigned int i=0;
dotFile << "\t\t<TR><TD><TABLE BORDER=\"0\" CELLBORDER=\"0\">"<<endl;
dotFile << "\t\t\t<TR><TD>:"<<traceName<<"</TD>";
while(i<polyFit.length()) {
// Look for the next line-break
unsigned int nextLB = polyFit.find_first_of("\n", i);
// If the next line is shorter than lineWidth, add it to labelMulLineStr and move on to the next line
if(nextLB-i < lineWidth) {
if(i!=0) dotFile << "\t\t<TR><TD></TD>";
dotFile << "<TD>:"<<polyFit.substr(i, nextLB-i+1)<<"</TD></TR>"<<endl;
i = nextLB+1;
// If the next line is longer than lineWidth, add just lineWidth characters to labelMulLineStr
} else {
// If it is not much longer than lineWidth, don't break it up
if(i>=polyFit.length() - lineWidth) break;
if(i!=0) dotFile << "\t\t<TR><TD></TD>";
dotFile << "<TD>:"<<polyFit.substr(i, lineWidth)<<"</TD></TR>"<<endl;
i += lineWidth;
}
}
if(i<polyFit.length()) {
if(i!=0) dotFile << "\t\t<TR><TD></TD>";
dotFile << "<TD>:"<<polyFit.substr(i, polyFit.length()-i)<<"</TD></TR>"<<endl;
}
dotFile << "</TABLE></TD></TR>"<<endl;
}
// Emits to the dot file the buttons used to select the combination of input property and trace attribute
// that should be shown in the data panel of a given module node.
// numInputs/numOutputs - the number of inputs/outputs of this module node
// ID - the unique ID of this module node
// prefix - We measure both the observations of measurements during the execution of modules and the
// properties of module outputs. Both are included in the trace of the module but the names of measurements
// are prefixed with "measure:" and the names of outputs are prefixed with "output:#:", where the # is the
// index of the output. The prefix argument identifies the types of attributs we'll be making buttons for and
// it should be either "measure" or "output".
// bgColor - The background color of the buttons
int maxButtonID=0; // The maximum ID that has ever been assigned to a button
//void modularApp::showButtons(int numInputs, int numOutputs, int ID, std::string prefix, std::string bgColor) {
// // Buttons for showing the observation trace plots
// //cout << "showButtons("<<numInputs<<", "<<numOutputs<<", #modules["<<ID<<"]->traceAttrNames="<<modules[ID]->traceAttrNames.size()<<endl;
// for(set<string>::iterator t=modules[ID]->traceAttrNames.begin(); t!=modules[ID]->traceAttrNames.end(); t++) {
// // If the current trace attribute does not have the selected prefix, skip it
// if(t->find(prefix) == string::npos) continue;
//
// dotFile << "\t\t\t<TR>";
// //for(int i=0; i<numInputs; i++) {
// for(map<string, list<string> >::iterator ctxtGrouping=modules[ID]->ctxtNames.begin();
// ctxtGrouping!=modules[ID]->ctxtNames.end(); ctxtGrouping++) {
// //if(ctxtNames[ID].find(i)!=ctxtNames[ID].end()) {
// //for(list<string>::iterator c=ctxtNames[ID][i].begin(); c!=ctxtNames[ID][i].end(); c++) {
// for(list<string>::iterator c=ctxtGrouping->second.begin(); c!=ctxtGrouping->second.end(); c++) {
// int buttonID = maxButtonID; maxButtonID++;
// dotFile << "<TD BGCOLOR=\"#"<<bgColor<<"\"><FONT POINT-SIZE=\"14\">"<<buttonID<<":"<<*t<<"</FONT></TD>";
//
// // Register the command to be executed when this button is clicked
// ostringstream cmd;
// cmd << "registerModuleButtonCmd("<<buttonID<<", \""<<
// moduleTraces[ID]->getDisplayJSCmd(traceStream::attrNames(/*txt()<<i<<":"<<*c*/ctxtGrouping->first+":"+*c), traceStream::attrNames(*t))<<
// "\");"<<endl;
////cout << "ts="<<moduleTraces[ID]<<" cmd="<<cmd.str()<<endl;
// dbg.widgetScriptCommand(cmd.str());
// } // ctxt attrs
// /*} else
// dotFile << "<TD></TD>";*/
// } // inputs
// dotFile << "\t\t\t</TR>"<<endl;
// } // trace attrs
//}
// Enter a new module within the current modularApp
// numInputs/numOutputs - the number of inputs/outputs of this module node
// ID - the unique ID of this module node
void modularApp::enterModule(string moduleName, int moduleID, int numInputs, int numOutputs, int count) {
//cout << "modularApp::enterModule("<<moduleName<<") numInputs="<<numInputs<<", #modules["<<moduleID<<"]->ctxtNames="<<modules[moduleID]->ctxtNames.size()<<endl;
// Inform the traceStream associated with this module that it is finished. We need this stream to wrap up
// all of its processing and analysis now, rather than before it is deallocated.
moduleTraces[moduleID]->obsFinished();
// Get the ID of the module that contains this one, if any.
int containerModuleID=-1;
if(mStack.size()>0) containerModuleID = mStack.back().moduleID;
// Start a subgraph for the current module
dotFile << "subgraph cluster"<<moduleID<<" {"<<endl;
//dotFile << "\tstyle=filled;"<<endl;
dotFile << "\tcolor=black;"<<endl;
//dotFile << "\tlabel=\""<<moduleName<<"\";"<<endl;
/*for(int i=0; i<numInputs; i++) {
dotFile << "\t\t"<<portName(node, input, i)<<" [shape=box, label=\"In "<<i<<"\"];\n";//, href=\"javascript:"<<b->first.getLinkJS()<<"\"];\n";
if(i>0) dotFile << "\t\t"<<portName(node, input, i-1)<<" -> "<<portName(node, input, i)<<" [style=invis];"<<endl;
}
for(int o=0; o<numOutputs; o++)
dotFile << "\t\t"<<portName(node, output, o)<<" [shape=box, label=\"Out "<<o<<"\"];\n";//, href=\"javascript:"<<b->first.getLinkJS()<<"\"];\n";
if(numInputs>0) {
dotFile << "\t{rank=\"source\"";
for(int i=0; i<numInputs; i++) dotFile << " "<<portName(node, input, i)<<"";
dotFile << "}"<<endl;
}
if(numOutputs>0) {
dotFile << "\t{rank=\"sink\"";
for(int o=0; o<numOutputs; o++) dotFile << " "<<portName(node, output, o)<<"";
dotFile << "}"<<endl;
}*/
// In the construction below we wish to allow users to interact with the trace information displayed in the main ID
// box by clicking on the names of context attributes. graphviz/Canviz allow us to create a single onclick method for
// the entire node but not separate ones for each TD. As such, Canviz has been extended to treat this special case
// (javascript handlers + HTML nodes) specially, where each piece of text in such a node must be formated as
// "ID:text" where ID is the ID that uniquely identifies the piece of text and text is the actual text that should
// be displayed. ID must not contain ":" but text may. Then, the javascript handlers of the node can assume the existence
// of a special ID variable that uniquely identifies the particular piece of text that got clicked. If an ID of a given
// piece of text is empty, then no link is placed around it. If some piece of text is mis-formatted (if missing the ":",
// Canviz provides an alert).
int databoxWidth = 300;
int databoxHeight = 200;
//cout << "module "<<moduleName<<", numInputs="<<numInputs<<", #modules[moduleID]->ctxtNames="<<modules[moduleID]->ctxtNames.size()<<endl;
//dotFile << "\t\""<<portNamePrefix(moduleName)<<"\" [shape=none, fill=lightgrey, label=<<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\">"<<endl;
// Input ports and body
dotFile << "\tnode"<<moduleID<<" [shape=none, fill=lightgrey, href=\"#\", onclick=\"return ClickOnModuleNode('node"<<moduleID<<"', this, ID);\", label=";
dotFile << "<<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\">"<<endl;
// Records whether the entry and ports have been emitted
bool entryEmitted=false;
bool exitEmitted=false;
//cout << "moduleName="<<moduleName<<", numInputs="<<numInputs<<", #modules["<<moduleID<<"]->ctxtNames="<<modules[moduleID]->ctxtNames.size()<<endl;
if(numInputs>0) {
if(modules[moduleID]->ctxtNames.size()>0) {
dotFile << "\t\t<TR><TD PORT=\"ENTRY\"><TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\">"<<endl;
entryEmitted = true;
dotFile << "\t\t\t<TR>";
int maxCtxt=0; // The maximum number of context names across all the inputs
for(map<string, list<string> >::iterator c=modules[moduleID]->ctxtNames.begin();
c!=modules[moduleID]->ctxtNames.end(); c++) {
string moduleClass, ctxtGrouping, ctxtSubGrouping, attrName;
decodeCtxtName(c->first, moduleClass, ctxtGrouping, ctxtSubGrouping, attrName);
dotFile << "<TD PORT=\""<<ctxtGrouping<<"_"<<ctxtSubGrouping<<"\" "<<
// Horizontal context "COLSPAN=\""<<c->second.size()<<"\""<<
">"<<
"<FONT POINT-SIZE=\"20\">:"<<ctxtGrouping<<" "<<ctxtSubGrouping<<" "<<attrName<<"</FONT>"<<
"</TD>";
maxCtxt = (maxCtxt > c->second.size()? maxCtxt: c->second.size());
}
dotFile << "</TR>"<<endl;
// The names of the context attributes for each output
/* Horizontal context
dotFile << "\t\t\t<TR>";
for(map<string, list<string> >::iterator ctxtGrouping=modules[moduleID]->ctxtNames.begin();
ctxtGrouping!=modules[moduleID]->ctxtNames.end(); ctxtGrouping++) {
for(list<string>::iterator c=ctxtGrouping->second.begin(); c!=ctxtGrouping->second.end(); c++) {
dotFile << "<TD BGCOLOR=\"#000066\"><FONT COLOR=\"#ffffff\" POINT-SIZE=\"18\">:"<<*c<<"</FONT></TD>";
}
}
dotFile << "\t\t\t</TR>"<<endl;*/
// Vertical context
/* --- Not showing this anymore since it looks ugly ---
// Place the first context name of each input, then the 2nd, etc.
map<string, pair<list<string>::iterator, list<string>::iterator> > i; // Points to the i^th context name for each input
// Initializes i to contain the starting iterators of each input's context names list
for(map<string, list<string> >::iterator c=modules[moduleID]->ctxtNames.begin(); c!=modules[moduleID]->ctxtNames.end(); c++)
i[c->first] = make_pair(c->second.begin(), c->second.end());
for(int cIdx=0; cIdx<maxCtxt; cIdx++) {
dotFile << "<TR>";
map<string, pair<list<string>::iterator, list<string>::iterator> > newI;
for(map<string, pair<list<string>::iterator, list<string>::iterator> >::iterator j=i.begin(); j!=i.end(); j++) {
// Place boxes for the current context of each input
dotFile << "<TD>";
// If we have not yet run out of contexts for the current input
if(j->second.first != j->second.second) dotFile << ":" << *(j->second.first);
dotFile << "</TD>";
// Advance the iterator for the current input
//j->second.first++;
list<string>::iterator next = j->second.first;
if(j->second.first != j->second.second) next++;
newI[j->first] = make_pair(next, j->second.second);
}
i = newI;
dotFile << "</TR>"<<endl;
}*/
// Buttons for showing the observation trace plots
//showButtons(numInputs, numOutputs, moduleID, "measure", "B0CDFF");
//showButtons(numInputs, numOutputs, moduleID, "output", "F78181");
dotFile << "</TABLE></TD></TR>"<<endl;
}
}
{
// Node Info
// Collect the names of all the context and trace attributes
list<string> contextAttrs;
for(map<string, list<string> >::iterator c=modules[moduleID]->ctxtNames.begin(); c!=modules[moduleID]->ctxtNames.end(); c++) {
for(list<string>::iterator d=c->second.begin(); d!=c->second.end(); d++)
contextAttrs.push_back(c->first+":"+*d);
}
list<string> traceAttrs;
for(set<string>::iterator t=modules[moduleID]->traceAttrNames.begin(); t!=modules[moduleID]->traceAttrNames.end(); t++)
traceAttrs.push_back(*t);
// Register the command to be executed when this button is clicked
ostringstream cmd;
cmd << "registerModuleButtonCmd("<<maxButtonID<<", \""<<
moduleTraces[moduleID]->getDisplayJSCmd(contextAttrs, traceAttrs, "", trace::scatter3d, true, false, true)<<
"\");"<<endl;
dbg.widgetScriptCommand(cmd.str());
dotFile << "\t\t<TR><TD";
if(!entryEmitted) dotFile << " PORT=\"ENTRY\"";
//if(numInputs + numOutputs > 0) dotFile << " COLSPAN=\""<<(numInputs>numOutputs? numInputs: numOutputs)<<"\"";
dotFile << "><FONT POINT-SIZE=\"26\">"<<(maxButtonID++)<<":"<<moduleName<<"</FONT></TD></TR>"<<endl;
}
if(numInputs>0) {
/* // If we observed values during the execution of this module group
if(modules[moduleID]->traceAttrNames.size()>0) {
// Polynomial fit of the observations
vector<string> polynomials = modules[moduleID]->polyFit();
assert(polynomials.size() == modules[moduleID]->traceAttrNames.size());
int i=0;
for(set<std::string>::iterator t=modules[moduleID]->traceAttrNames.begin(); t!=modules[moduleID]->traceAttrNames.end(); t++, i++) {
// If we were able to train a model for the current trace attribute, emit it
if(polynomials[i] != "") printPolyFitStr(dotFile, *t, polynomials[i], 80);
}
//dotFile << "\t\t<TR><TD>:"<<modules[moduleID]->traceAttrNames[i]<< ": "<<wrapStr(polynomials[i], 50)<<"</TD></TR>"<<endl;
}*/
//cout << "polyFits[moduleID]="<<polyFits[moduleID]<<", polyFits[moduleID]->numFits()="<<polyFits[moduleID]->numFits()<<endl;
if(polyFits[moduleID] && polyFits[moduleID]->numFits()>0)
dotFile << "\t\t"<<polyFits[moduleID]->getFitText()<<""<<endl;
//cout << "#modules[moduleID]->traceAttrNames="<<modules[moduleID]->traceAttrNames.size()<<endl;
if(modules[moduleID]->traceAttrNames.size()>0) {
//for(int i=0; i<modules[moduleID]->traceAttrNames.size(); i++) {
dotFile << "\t\t<TR><TD PORT=\"EXIT\"><TABLE><TR><TD BGCOLOR=\"#FF00FF\" COLOR=\"#FF00FF\" WIDTH=\""<<databoxWidth<<"\" HEIGHT=\""<<databoxHeight<<"\"></TD></TR></TABLE></TD></TR>"<<endl;
exitEmitted = true;
}
}
if(!exitEmitted)
dotFile << "\t\t<TR><TD PORT=\"EXIT\"></TD></TR>"<<endl;
dotFile << "</TABLE>>";
dotFile << "];" << endl;
// Output ports
dotFile << "\tnode"<<moduleID<<"_Out [shape=none, fill=lightgrey, href=\"#\", onclick=\"return ClickOnModuleNode('node"<<moduleID<<"', this, ID);\", label=";
if(numOutputs==0)
dotFile << "\"\"";
else {
dotFile << "<<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\">"<<endl;
//dotFile << "\t<TR><TD PORT=\"ENTRY\" HEIGHT=\"0\">:</TD></TR>"<<endl;
dotFile << "\t<TR>"<<endl;
for(int o=0; o<numOutputs; o++)
dotFile << "\t\t<TD WIDTH=\""<<databoxWidth<<"\" PORT=\""<<portName(output, o)<<"\"><FONT POINT-SIZE=\"14\">:Out "<<o<<"</FONT></TD>"<<endl;
dotFile << "\t</TR>"<<endl;
//dotFile << "\t<TR><TD PORT=\"EXIT\" HEIGHT=\"0\">:</TD></TR>"<<endl;
dotFile << "</TABLE>>";
}
dotFile << "];" <<endl;
// Add a high-weight invisible edge between the input and the output nodes to vertically align them
dotFile << "\tnode"<<moduleID<<":EXIT:s "
" -> "<<
"node"<<moduleID<<"_Out "<<
"[weight=100, style=invis];\n";
// If this module is contained inside another, add invisible edges between the input portion of container module and
// this one and the output portion of this module and the container to vertically align them
if(containerModuleID>=0) {
dotFile << "\tnode"<<containerModuleID<<":EXIT:s -> node"<<moduleID<<":ENTRY:n [weight=150, style=invis];"<<endl;
//dotFile << "\tnode"<<moduleID<<"_Out:EXIT:s -> node"<<containerModuleID<<"_Out:ENTRY:n [weight=300];"<<endl;
dotFile << "\tnode"<<moduleID<<"_Out -> node"<<containerModuleID<<"_Out [weight=150, style=invis];"<<endl;
//dotFile << "\tnode"<<containerModuleID<<" -> node"<<moduleID<<" [ltail=cluster"<<containerModuleID<<", lhead=cluster"<<moduleID<<", weight=5];"<<endl;
//dotFile << "\tnode"<<moduleID<<"_Out -> node"<<containerModuleID<<"_Out [ltail=cluster"<<moduleID<<", lhead=cluster"<<containerModuleID<<", weight=5];"<<endl;
}
dotFile << "{rank=source;node"<<moduleID<<";}"<<endl;
dotFile << "{rank=sink;node"<<moduleID<<"_Out;}"<<endl;
// Add a moduleInfo object that records this module to the modularApp's stack
mStack.push_back(sight::layout::moduleInfo(moduleName, moduleID, numInputs, numOutputs, count));
//cout << "modularApp::enterModule() done\n";
}
// Static version of enterModule() that pulls the from/to anchor IDs from the properties iterator and calls
// enterModule() in the currently active modularApp
void* modularApp::enterModule(properties::iterator props) {
int moduleID = properties::getInt(props, "moduleID");
// Get this module's moduleTraceStream
assert(modularApp::getInstance()->moduleTraces.find(moduleID) != modularApp::getInstance()->moduleTraces.end());
moduleTraceStream* ts = dynamic_cast<moduleTraceStream*>(modularApp::getInstance()->moduleTraces[moduleID]);
assert(ts);
assert(modularApp::activeMA);
modularApp::activeMA->enterModule(ts->name,
moduleID,
ts->numInputs,
ts->numOutputs,
properties::getInt(props, "count"));
return NULL;
}
// Exit a module within the current modularApp
void modularApp::exitModule() {
// Grab the information about the module we're exiting from this modularApp's mStack and pop it off
assert(mStack.size()>0);
sight::layout::moduleInfo m = mStack.back();
mStack.pop_back();
//cout << "modularApp::exitModule("<<m.moduleName<<")"<<endl;
// Close the current module's sub-graph
dotFile << "}" << endl;
}
// Static version of exitModule() that calls exitModule() in the currently active modularApp
void modularApp::exitModule(void* obj) {
assert(modularApp::activeMA);
modularApp::activeMA->exitModule();
}
// Register the given module object (keeps data on the raw observations) and polyFitObserver object
void modularApp::registerModule(int moduleID, sight::layout::module* m, polyFitObserver* pf) {
assert(modularApp::activeMA);
modularApp::activeMA->modules[moduleID] = m;
modularApp::activeMA->polyFits[moduleID] = pf;
}
// Add a directed edge from one port to another
void modularApp::addEdge(int fromCID, common::module::ioT fromT, int fromP,
int toCID, common::module::ioT toT, int toP,
double prob) {
dotFile << "\tnode"<<fromCID<<"_Out:"<<portName(fromT, fromP)<<":s"<<
" -> "<<
"node"<<toCID <<":"<<portName(toT, toP )<<":n "<<
"[penwidth="<<(1+prob*3)<<"];\n";
}
// Static version of the call that pulls the from/to anchor IDs from the properties iterator and calls addUndirEdge() in the currently active graph
void* modularApp::addEdge(properties::iterator props) {
assert(activeMA);
activeMA->addEdge(properties::getInt(props, "fromCID"), (ioT)properties::getInt(props, "fromT"), properties::getInt(props, "fromP"),
properties::getInt(props, "toCID"), (ioT)properties::getInt(props, "toT"), properties::getInt(props, "toP"),
properties::getFloat(props, "prob"));
return NULL;
}
/******************
***** module *****
******************/
module::module(int moduleID) : moduleID(moduleID)
{
/*polyfitCtxt=NULL;
polyfitObs=NULL;*/
numObs=0;
/*numAllocObs=0;
numAllocTraceAttrs=0;
numNumericCtxt=-1;*/
}
module::~module() {
/*if(numObs>0) {
gsl_matrix_free(polyfitCtxt);
gsl_matrix_free(polyfitObs);
}*/
}
//// Iterates over all combinations of keys in numericCtxt upto maxDegree in size and computes the products of
//// their values. Adds each such product to the given row of polyfitCtxt at different columns.
//void addPolyTerms(const map<string, double>& numericCtxt, int termCnt, int maxDegree,
// int row, int& col, double product, gsl_matrix *polyfitCtxt) {
// // If product contains maxDegree terms, add it to the given column of polyfitObs and increment the column counter
// if(termCnt==maxDegree) {
// gsl_matrix_set(polyfitCtxt, row, col, product);
// col++;
// } else {
// // Iterate through all the possible choices of the next factor in the current polynomial term
// for(map<string, double>::const_iterator c=numericCtxt.begin(); c!=numericCtxt.end(); c++) {
// addPolyTerms(numericCtxt, termCnt+1, maxDegree, row, col, product * c->second, polyfitCtxt);
// }
// }
//}
//
//// Iterates over all combinations of keys in numericCtxt upto maxDegree in size. Given ctxtNames, which maintains the list
//// of names for each attribute and selTerms, which identifies the attribute combinations that should be selected, matches
//// the selections to the names and inserts the matched pairs to selCtxt.
//// termCnt - counts the number of terms that have been added to the current polynomial product
//// maxDegree - the maximum such terms that can go into a single product
//// idx - The current count of the terms from the overall space of terms. May not be 0 at the root recursive calls since
//// we may iterate over multiple choices of maxDegree
//// subName - the name string that has been computed so far for the current prefix of terms in the polynomial product
//void selTerms2Names(const list<string>& ctxtNames, const set<int>& selTerms,
// list<pair<int, string> >& selCtxt,
// int termCnt, int maxDegree, int& idx, map<string, int>& subNames) {
// // If product contains maxDegree terms, add it to the given column of polyfitObs and increment the column counter
// if(termCnt==maxDegree) {
// // If the current product index exists in selTerms
// if(selTerms.find(idx) != selTerms.end()) {
// // Match it to its name and add it to selCtx.
// //selCtxt.push_back(make_pair(idx, subName));
// ostringstream name;
// for(map<string, int>::iterator n=subNames.begin(); n!=subNames.end(); n++) {
// assert(n->second>0);
// if(n!=subNames.begin()) name << "*";
// name << n->first;
// if(n->second>1) name << "^"<<n->second;
// }
// selCtxt.push_back(make_pair(idx, name.str()));
// }
// idx++;
// } else {
// // Iterate through all the possible choices of the next factor in the current polynomial term
// for(list<string>::const_iterator c=ctxtNames.begin(); c!=ctxtNames.end(); c++) {
// if(subNames.find(*c) == subNames.end()) subNames[*c] = 1;
// else subNames[*c]++;
//
// selTerms2Names(ctxtNames, selTerms, selCtxt, termCnt+1, maxDegree, idx, subNames/*subName+(termCnt>0?"*":"")+*c*/);
//
// subNames[*c]--;
// if(subNames[*c]==0) subNames.erase(*c);
// }
// }
//}
//
//
//// Do a multi-variate polynomial fit of the data observed for the given moduleID and return for each trace attribute
//// a string that describes the function that best fits its values
//std::vector<std::string> module::polyFit()
//{
// vector<string> polynomials;
//
// // Do nothing if we had no observations with numeric context attributes
// if(numObs==0) return polynomials;
//
// // Fit a polynomial to the observed data
// int maxDegree = 2;
// long numTerms = polyfitCtxt->size2;
// // Covariance matrix
// gsl_matrix *polyfitCov = gsl_matrix_alloc(numTerms, numTerms);
//
// //for(int i=0; i<polyfitObs.size(); i++) {
// int i=0;
// for(set<std::string>::iterator t=traceAttrNames.begin(); t!=traceAttrNames.end(); t++, i++) {
// //cout << i << ": attr "<<*t<<endl;
//
// gsl_vector* polyfitCoeff = gsl_vector_alloc(numTerms);
// gsl_multifit_linear_workspace *polyfitWS = gsl_multifit_linear_alloc(numObs, numTerms);
// double chisq;
// gsl_matrix_view ctxtView = gsl_matrix_submatrix (polyfitCtxt, 0, 0, numObs, numTerms);
// //gsl_matrix_view ctxtView = gsl_matrix_submatrix (polyfitObs[i], 0, 0, numObs, numTerms);
// //gsl_vector_view obsView = gsl_vector_subvector(polyfitObs[i], 0, numObs);
// //gsl_vector_view obsView = gsl_matrix_subcolumn(polyfitObs[i], i, 0, numObs);
// gsl_vector_view obsView1 = gsl_matrix_column(polyfitObs, i);
// gsl_vector_view obsView = gsl_vector_subvector(&(obsView1.vector), 0, numObs);
//
// /*for(int j=0; j<numObs; j++) {
// for(int k=0; k<numTerms; k++)
// cout << " "<<gsl_matrix_get(&(ctxtView.matrix),j,k);
// cout << " => "<<gsl_vector_get(&(obsView.vector), j)<<endl;
// }*/
//
//
// // If we have enough observations to fit a model
// if(numTerms <= numObs) {
// // Use a linear solver to fit the coefficients of the polynomial
// // ******
// gsl_multifit_linear(&(ctxtView.matrix), &(obsView.vector), polyfitCoeff, polyfitCov, &chisq, polyfitWS);
// // ******
//
// /*cout << "polyfitCoeff=";
// for(int t=0; t<numTerms; t++) cout << gsl_vector_get(polyfitCoeff, t)<<" ";
// cout << endl;*/
//
// // Identify the pair of coefficients in the sorted order with the largest relative difference between them
// map<double, int> sortedCoeff;
// map<int, double> sortedCoeffInv;
// for(int t=0; t<numTerms; t++) {
// sortedCoeff[fabs(gsl_vector_get(polyfitCoeff, t))] = t;
// sortedCoeffInv[t] = fabs(gsl_vector_get(polyfitCoeff, t));
// }
// map<double, int>::reverse_iterator splitIter = sortedCoeff.rend();
// double largestCoeff = sortedCoeff.rbegin()->first;
//
// // Iterate sortedCoeff from the largest to smallest coefficient, looking for the largest gap between adjacent coefficients
// double maxDiff = 0;
// map<double, int>::reverse_iterator c=sortedCoeff.rbegin();
// map<double, int>::reverse_iterator next = c; next++;
// while(next!=sortedCoeff.rend() && next->first!=0) {
// //cout << c->first<<" / "<<next->first<<endl;
// double diff = c->first / next->first;
// if(diff>maxDiff) {
// maxDiff = diff;
// splitIter = next;
// }
// c++;
// next = c; next++;
// }
//
// // Create a set of just the indexes of the large coefficients, which are the coefficients larger than the largest
// // coefficient drop and are not irrelevantly small compared to the largest coefficient
// set<int> coeffIdxes;
// //cout << "sortedCoeff: ";
// for(map<double, int>::reverse_iterator c=sortedCoeff.rbegin(); c!=splitIter && c->first>=largestCoeff*1e-3; c++) {
// //cout << c->second<<"/"<<c->first<<" ";
// coeffIdxes.insert(c->second);
// }
// //cout << endl;
//
// list<pair<int, string> > selCtxt;
//
// // Add the constant term, if it is in coeffIdxes
// if(coeffIdxes.find(0) != coeffIdxes.end()) selCtxt.push_back(make_pair(0,""));
//
// int idx=1;
// for(int degree=1; degree<=maxDegree; degree++) {
// map<string, int> subNames;
// selTerms2Names(numericCtxtNames, coeffIdxes, selCtxt, 0, degree, idx, subNames/*""*/);
// }
//
// // Sort the selected names according to the size of their coefficients
// map<double, pair<int, string> > selCtxtSorted;
// for(list<pair<int, string> >::iterator c=selCtxt.begin(); c!=selCtxt.end(); c++)
// selCtxtSorted[sortedCoeffInv[c->first]] = *c;
//
// //cout << "selCtxtSorted="<<selCtxtSorted.size()<<" #selCtxt="<<selCtxt.size()<<endl;
//
// // Serialize the polynomial fit terms in the order from largest to smallest coefficient
// ostringstream polyStr;
// for(map<double, pair<int, string> >::reverse_iterator c=selCtxtSorted.rbegin(); c!=selCtxtSorted.rend(); c++) {
// if(c!=selCtxtSorted.rbegin()) polyStr << " + ";
// polyStr << setiosflags(ios::scientific) << setprecision(2) <<
// gsl_vector_get(polyfitCoeff, c->second.first) <<
// (c->second.second==""?"":"*") <<
// c->second.second;
// }
// polynomials.push_back(polyStr.str());
// // If we didn't get enough observations to train a model
// } else
// polynomials.push_back("");
//
// //gsl_vector_free(polyfitObs[i]);
// gsl_vector_free(polyfitCoeff);
// }
//
// gsl_matrix_free(polyfitCov);
//
// return polynomials;
//}
// Interface implemented by objects that listen for observations a traceStream reads. Such objects
// call traceStream::registerObserver() to inform a given traceStream that it should observations.
void module::observe(int traceID,
const map<string, string>& ctxt,
const map<string, string>& obs,
const map<string, anchor>& obsAnchor) {
/*cout << "module::observe("<<traceID<<") moduleID="<<moduleID<<" #ctxt="<<ctxt.size()<<" #obs="<<obs.size()<<endl;
cout << " ctxt=";
for(map<string, string>::const_iterator c=ctxt.begin(); c!=ctxt.end(); c++) { cout << c->first << "=>"<<c->second<<" "; }
cout << endl;
cout << " obs=";
for(map<string, string>::const_iterator o=obs.begin(); o!=obs.end(); o++) { cout << o->first << "=>"<<o->second<<" "; }
cout << endl;*/
// Record the names of the trace attributes and verify that all observations have the same ones
set<string> curTraceAttrNames;
for(map<string, string>::const_iterator o=obs.begin(); o!=obs.end(); o++)
curTraceAttrNames.insert(o->first);
if(numObs == 0) traceAttrNames = curTraceAttrNames;
else if(traceAttrNames != curTraceAttrNames)
{
cerr << "ERROR: Inconsistent trace attributes in different observations for the same module node "<<moduleID<<"!"<<endl;
cerr << "Before observed "<<traceAttrNames.size()<<" trace attributes: [";
for(set<string>::iterator t=traceAttrNames.begin(); t!=traceAttrNames.end(); t++) {
if(t!=traceAttrNames.begin()) cerr << ", ";
cerr << *t;
}
cerr << "]."<<endl;
cerr <<"This observation has "<<curTraceAttrNames.size()<<": [";
for(set<string>::iterator t=curTraceAttrNames.begin(); t!=curTraceAttrNames.end(); t++) {
if(t!=curTraceAttrNames.begin()) cerr << ", ";
cerr << *t;
}
cerr << "]."<<endl;
assert(0);
}
// Record the context attribute groupings and the names of the attributes within each one
map<string, list<string> > curCtxtNames;
for(map<string, string>::const_iterator c=ctxt.begin(); c!=ctxt.end(); c++) {
string moduleClass, ctxtGrouping, ctxtSubGrouping, attrName;
decodeCtxtName(c->first, moduleClass, ctxtGrouping, ctxtSubGrouping, attrName);
curCtxtNames[moduleClass+":"+ctxtGrouping+":"+ctxtSubGrouping].push_back(attrName);
}
if(numObs==0) ctxtNames = curCtxtNames;
else if(ctxtNames != curCtxtNames) {
cerr << "ERROR: Inconsistent context attributes in different observations for the same module node "<<moduleID<<"!"<<endl;
cerr << "Before observed "<<ctxtNames.size()<<" context attributes: "<<endl;
for(map<string, list<string> >::iterator c=ctxtNames.begin(); c!=ctxtNames.end(); c++) {
cerr << " "<<c->first<<" : ";
for(list<string>::iterator i=c->second.begin(); i!=c->second.end(); i++) {
if(i!=c->second.begin()) cerr << ", ";
cerr << *i;
}
cerr << endl;
}
cerr <<"This observation has "<<curCtxtNames.size()<<":"<<endl;
for(map<string, list<string> >::iterator c=curCtxtNames.begin(); c!=curCtxtNames.end(); c++) {
cerr << " "<<c->first<<" : ";
for(list<string>::iterator i=c->second.begin(); i!=c->second.end(); i++) {
if(i!=c->second.begin()) cerr << ", ";
cerr << *i;
}
cerr << endl;
}
assert(false);
}
numObs++;
//cout << "#curTraceAttrNames="<<curTraceAttrNames.size()<<", curCtxtNames="<<curCtxtNames.size()<<", numObs="<<numObs<<endl;
/* // Maps the names of numeric contexts to their floating point values
map<string, double> numericCtxt;
list<string> curNumericCtxtNames;
for(map<string, string>::const_iterator c=ctxt.begin(); c!=ctxt.end(); c++) {
attrValue val(c->second, attrValue::unknownT);
// If this value is numeric
if(val.getType()==attrValue::intT || val.getType()==attrValue::floatT) {
numericCtxt[c->first] = val.getAsFloat();
curNumericCtxtNames.push_back(c->first);
}
}
if(numObs==0) numericCtxtNames = curNumericCtxtNames;
else if(numericCtxtNames != curNumericCtxtNames)
{ cerr << "ERROR: Inconsistent numeric context attributes in different observations for the same module node "<<moduleID<<"! Before observed "<<numericCtxtNames.size()<<" numeric context attributed but this observation has "<<curNumericCtxtNames.size()<<"."<<endl; assert(false); }
//cout << " #numericCtxt="<<numericCtxt.size()<<endl;
// Only bother computing the polynomial fit if any of the context attributes are numeric
if(numericCtxt.size()>0) {
// Read out the names of the observation's trace attributes
for(map<string, string>::const_iterator o=obs.begin(); o!=obs.end(); o++) {
traceAttrNames.insert(o->first);
// If this is the first time we've encountered this trace attribute, map it to a fresh column number
if(traceAttrName2Col.find(o->first) == traceAttrName2Col.end()) {
assert(traceAttrName2Count.size() == traceAttrName2Col.size());
int newCol = traceAttrName2Col.size();
traceAttrName2Col[o->first] = newCol;
// We have not yet recorded any observations for this trace attribute (we will later in this function)
traceAttrName2Count.push_back(0);
}
}
int maxDegree = 2;
// The total number of polynomial terms to maxDegree:
long numTerms = (numericCtxt.size()==1 ? maxDegree+1:
// #numericCtxt^0 + #numericCtxt^1 + #numericCtxt^2 + ... + #numericCtxt^maxDegree = #numericCtxt^(maxDegree+1) - 1
pow(numericCtxt.size(), maxDegree+1));
//cout << "module::observe() moduleID="<<moduleID<<", #numericCtxt="<<numericCtxt.size()<<", #polyfitCtxt="<<polyfitCtxt.size()<<", found="<<(polyfitCtxt.find(moduleID) != polyfitCtxt.end())<<", numTerms="<<numTerms<<endl;
// If this is the first observation we have from the given traceStream, allocate the
// polynomial fit datastructures
if(numObs==0) {
polyfitCtxt = gsl_matrix_alloc(1000, numTerms);
//for(map<string, string>::const_iterator o=obs.begin(); o!=obs.end(); o++) {
// polyfitObs.push_back(gsl_vector_alloc(1000));
//}
polyfitObs = gsl_matrix_alloc(1000, traceAttrName2Col.size());
numObs = 0;
numAllocObs = 1000;
numAllocTraceAttrs = traceAttrName2Col.size();
//cout << " Allocated "<<numAllocObs<<" rows, "<<numAllocTraceAttrs<<" columns"<<endl;
}
//cout << " #polyfitCtxt="<<polyfitCtxt.size()<<", found="<<(polyfitCtxt.find(moduleID) != polyfitCtxt.end())<<", numObs="<<numObs<<", numAllocObs="<<numAllocObs<<endl;
//cout << "traceAttrName2Col.size()="<<traceAttrName2Col.size()<<" numAllocTraceAttrs="<<numAllocTraceAttrs<<endl;
// If we're out of space in polyfitCtxt and polyfitObs to store another observation or store more columns, grow them
if(numObs == numAllocObs-1 ||
traceAttrName2Col.size() > numAllocTraceAttrs) {
// If we're out of space for rows, double it
int newNumAllocObs = numAllocObs;
if(numObs == numAllocObs-1) newNumAllocObs *= 2;
// If we need new columns, adjust accordingly
int newNumAllocTraceAttrs = numAllocTraceAttrs;
if(traceAttrName2Col.size() > numAllocTraceAttrs)
newNumAllocTraceAttrs = traceAttrName2Col.size();
// Expand polyfitCtxt
gsl_matrix* newCtxt = gsl_matrix_alloc(newNumAllocObs, numTerms);
gsl_matrix_view newCtxtView = gsl_matrix_submatrix (newCtxt, 0, 0, numAllocObs, numTerms);
gsl_matrix_memcpy (&(newCtxtView.matrix), polyfitCtxt);
gsl_matrix_free(polyfitCtxt);
polyfitCtxt = newCtxt;
// Expand polyfitObs
gsl_matrix* newObs = gsl_matrix_alloc(newNumAllocObs, newNumAllocTraceAttrs);
gsl_matrix_view newObsView = gsl_matrix_submatrix (newObs, 0, 0, numAllocObs, numAllocTraceAttrs);
gsl_matrix_memcpy (&(newObsView.matrix), polyfitObs);
gsl_matrix_free(polyfitObs);
polyfitObs = newObs;
// Update our allocated space records
numAllocObs = newNumAllocObs;
numAllocTraceAttrs = newNumAllocTraceAttrs;
//cout << " Reallocated "<<numAllocObs<<" rows, "<<numAllocTraceAttrs<<" columns, numObs="<<numObs<<endl;
}
// Add this observation to polyfitObs
int obsIdx=0;
// Records whether this observation corresponds to a new context row
bool newContext = false;
//cout << " Adding Observations:"<<endl;
for(map<string, string>::const_iterator o=obs.begin(); o!=obs.end(); o++, obsIdx++) {
// Skip any non-numeric observed values
attrValue val(o->second, attrValue::unknownT);
if(val.getType() != attrValue::intT && val.getType() != attrValue::floatT) continue;
double v = val.getAsFloat();
int traceAttrCol = traceAttrName2Col[o->first];
/ *cout << " "<<o->first<<" traceAttrCol="<<traceAttrCol<<
", numAllocTraceAttrs="<<numAllocTraceAttrs<<
", traceAttrName2Count[traceAttrCol]="<<traceAttrName2Count[traceAttrCol]<<
", numObs="<<numObs<<endl;* /
assert(traceAttrCol < numAllocTraceAttrs);
gsl_matrix_set(polyfitObs, traceAttrName2Count[traceAttrCol], traceAttrCol, v);
// Increment the number of values written into the current column
traceAttrName2Count[traceAttrCol]++;
// If this observation has started a new row in the observations matrix
if(traceAttrName2Count[traceAttrCol] > numObs) {
assert(traceAttrName2Count[traceAttrCol] == numObs+1);
// Update numObs to correspond to the maximum number of values written to any column
numObs = traceAttrName2Count[traceAttrCol];
// Record that this is a new context, which should be written into polyfitCtxt
newContext = true;
}
}
// Add the context of the observation to polyfitCtxt
// The first entry corresponds to the degree-0 constant term
gsl_matrix_set(polyfitCtxt, numObs, 0, 1);
// Add all the polynomial terms of degrees upto and including maxDegree
int col=1;
for(int degree=1; degree<=maxDegree; degree++)
addPolyTerms(numericCtxt, 0, degree, numObs, col, 1, polyfitCtxt);
}
*/
// Forward the observation to observers of this object
emitObservation(traceID, ctxt, obs, obsAnchor/*, observers*/);
}
/*************************
***** polyFitFilter *****
*************************/
// The total number of polyFitFilter instances that have been created so far.
// Used to set unique names to files output by polyFitFilters.
int polyFitFilter::maxFileNum=0;
// Records whether the working directory for this class has been initialized
bool polyFitFilter::workDirInitialized=false;
// The directory that is used for storing intermediate files
std::string polyFitFilter::workDir="";
polyFitFilter::polyFitFilter() {
numObservations = 0;
fileNum = maxFileNum++;
// Initialize the directories this polyFitFilter will use for its temporary storage
if(!workDirInitialized) {
// Create the directory that holds the workDirInitialized-specific data
std::pair<std::string, std::string> dirs = dbg.createWidgetDir("polyFitFilter");
workDir = dirs.first;
}
workDirInitialized = true;