source: trunk/FACT++/src/ratecontrol.cc@ 13794

Last change on this file since 13794 was 13756, checked in by tbretz, 13 years ago
Changed the blocking from patch-wise to board-wise.
File size: 20.8 KB
Line 
1#include <valarray>
2
3#include "Dim.h"
4#include "Event.h"
5#include "Shell.h"
6#include "StateMachineDim.h"
7#include "Connection.h"
8#include "Configuration.h"
9#include "Console.h"
10#include "Converter.h"
11#include "DimServiceInfoList.h"
12//#include "PixelMap.h"
13
14#include "tools.h"
15
16#include "LocalControl.h"
17
18#include "HeadersFTM.h"
19
20namespace ba = boost::asio;
21namespace bs = boost::system;
22namespace dummy = ba::placeholders;
23
24using namespace std;
25
26// ------------------------------------------------------------------------
27
28#include "DimDescriptionService.h"
29
30// ------------------------------------------------------------------------
31
32class StateMachineRateControl : public StateMachineDim, public DimInfoHandler
33{
34private:
35 enum states_t
36 {
37 kStateDimNetworkNA = 1,
38 kStateDisconnected,
39 kStateConnecting,
40 kStateConnected,
41
42 kStateSettingGlobalThreshold,
43 kStateGlobalThresholdSet,
44
45 kStateInProgress,
46 };
47
48 bool fTriggerOn;
49
50 vector<bool> fBlock;
51
52 DimServiceInfoList fNetwork;
53
54 pair<Time, int> fStatusDim;
55 pair<Time, int> fStatusFTM;
56 pair<Time, int> fStatusRS;
57
58 DimStampedInfo fDim;
59 DimStampedInfo fFTM;
60 DimStampedInfo fRates;
61 DimStampedInfo fStatic;
62 DimStampedInfo fRateScan;
63
64// DimDescribedService fDimData;
65// DimDescribedService fDimProc;
66
67 float fTargetRate;
68 float fTriggerRate;
69
70 uint16_t fThresholdMin;
71 uint16_t fThresholdReference;
72
73 bool fVerbose;
74 bool fEnabled;
75
76 uint64_t fCounter;
77
78 pair<Time, int> GetNewState(DimStampedInfo &info) const
79 {
80 const bool disconnected = info.getSize()==0;
81
82 // Make sure getTimestamp is called _before_ getTimestampMillisecs
83 const int tsec = info.getTimestamp();
84 const int tms = info.getTimestampMillisecs();
85
86 return make_pair(Time(tsec, tms*1000),
87 disconnected ? -2 : info.getQuality());
88 }
89
90 bool CheckEventSize(size_t has, const char *name, size_t size)
91 {
92 if (has==size)
93 return true;
94
95 if (has==0)
96 return false;
97
98 ostringstream msg;
99 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
100 Fatal(msg);
101 return false;
102 }
103
104 vector<uint16_t> fThresholds;
105
106 void PrintThresholds(const FTM::DimStaticData &sdata)
107 {
108 //if (!fVerbose)
109 // return;
110
111 if (fThresholds.size()==0)
112 return;
113
114 Out() << "Min. DAC=" << fThresholdMin << endl;
115
116 int t=0;
117 for (t=0; t<160; t++)
118 if (sdata.fThreshold[t]!=fThresholds[t])
119 break;
120
121 if (t==160)
122 return;
123
124 for (int j=0; j<10; j++)
125 {
126 for (int k=0; k<4; k++)
127 {
128 for (int i=0; i<4; i++)
129 if (fThresholds[i+k*4+j*16]!=fThresholdMin)
130 Out() << setw(3) << fThresholds[i+k*4+j*16] << " ";
131 else
132 Out() << " - ";
133 Out() << " ";
134 }
135 Out() << endl;
136 }
137 Out() << endl;
138 }
139
140 void Step(int idx, float step)
141 {
142 uint16_t diff = fThresholds[idx]+int16_t(truncf(step));
143 if (diff<fThresholdMin)
144 diff=fThresholdMin;
145
146 if (diff==fThresholds[idx])
147 return;
148
149 if (fVerbose)
150 {
151 Out() << idx/40 << "|" << (idx/4)%10 << "|" << idx%4;
152 Out() << (step>0 ? " += " : " -= ");
153 Out() << step << " (" << diff << ")" << endl;
154 }
155
156 const uint32_t val[2] = { idx, diff };
157 DimClient::sendCommandNB("FTM_CONTROL/SET_THRESHOLD", (void*)val, 8);
158
159 fBlock[idx/4] = true;
160 }
161
162 void ProcessPatches(const FTM::DimTriggerRates &sdata)
163 {
164
165 // Caluclate Median and deviation
166 vector<float> medb(sdata.fBoardRate, sdata.fBoardRate+40);
167 vector<float> medp(sdata.fPatchRate, sdata.fPatchRate+160);
168
169 sort(medb.begin(), medb.end());
170 sort(medp.begin(), medp.end());
171
172 vector<float> devb(40);
173 for (int i=0; i<40; i++)
174 devb[i] = fabs(sdata.fBoardRate[i]-medb[i]);
175
176 vector<float> devp(160);
177 for (int i=0; i<160; i++)
178 devp[i] = fabs(sdata.fPatchRate[i]-medp[i]);
179
180 sort(devb.begin(), devb.end());
181 sort(devp.begin(), devp.end());
182
183 double mb = (medb[19]+medb[20])/2;
184 double mp = (medp[79]+medp[80])/2;
185
186 double db = devb[27];
187 double dp = devp[109];
188
189 // If any is zero there is something wrong
190 if (mb==0 || mp==0 || db==0 || dp==0)
191 return;
192
193 if (fVerbose)
194 {
195 Out() << "Patch: Median=" << mp << " Dev=" << dp << endl;
196 Out() << "Board: Median=" << mb << " Dev=" << db << endl;
197 }
198
199 for (int i=0; i<40; i++)
200 {
201 int maxi = -1;
202
203 const float dif = fabs(sdata.fBoardRate[i]-mb)/db;
204 if (dif>5)
205 {
206 if (fVerbose)
207 Out() << "B" << i << ": " << dif << endl;
208
209 float max = sdata.fPatchRate[i*4];
210 maxi = 0;
211
212 for (int j=1; j<4; j++)
213 if (sdata.fPatchRate[i*4+j]>max)
214 {
215 max = sdata.fPatchRate[i*4+j];
216 maxi = j;
217 }
218 }
219
220 if (fBlock[i])
221 {
222 fBlock[i] = false;
223 continue;
224 }
225
226 for (int j=0; j<4; j++)
227 {
228 // For the noise pixel correct down to median+3*deviation
229 if (maxi==j)
230 {
231 // This is the step which has to be performed to go from
232 // a NSB rate of sdata.fPatchRate[i*4+j]
233
234
235 const float step = (log10(sdata.fPatchRate[i*4+j])-log10(mp+5*dp))/0.039;
236 // * (dif-5)/dif
237 Step(i*4+j, step);
238 continue;
239 }
240
241 // For pixels below the meadian correct also back to median+3*deviation
242 if (sdata.fPatchRate[i*4+j]<mp)
243 {
244 const float step = (log10(sdata.fPatchRate[i*4+j])-log10(mp+3*dp))/0.039;
245 Step(i*4+j, step);
246 continue;
247 }
248
249 const float step = -1.5*(log10(mp+dp)-log10(mp))/0.039;
250 Step(i*4+j, step);
251 }
252 }
253 }
254
255 void ProcessCamera(const FTM::DimTriggerRates &sdata)
256 {
257 if (fCounter++==0)
258 return;
259
260 // Caluclate Median and deviation
261 vector<float> medb(sdata.fBoardRate, sdata.fBoardRate+40);
262
263 sort(medb.begin(), medb.end());
264
265 vector<float> devb(40);
266 for (int i=0; i<40; i++)
267 devb[i] = fabs(sdata.fBoardRate[i]-medb[i]);
268
269 sort(devb.begin(), devb.end());
270
271 double mb = (medb[19]+medb[20])/2;
272 double db = devb[27];
273
274 // If any is zero there is something wrong
275 if (mb==0 || db==0)
276 {
277 Warn("The median or the deviation of all board rates is zero... cannot calibrate.");
278 return;
279 }
280
281 double avg = 0;
282 int num = 0;
283
284 for (int i=0; i<40; i++)
285 {
286 if ( fabs(sdata.fBoardRate[i]-mb)<2.5*db)
287 {
288 avg += sdata.fBoardRate[i];
289 num++;
290 }
291 }
292
293 fTriggerRate = avg/num * 40;
294
295 if (fVerbose)
296 {
297 Out() << "Board: Median=" << mb << " Dev=" << db << endl;
298 Out() << "Camera: " << fTriggerRate << " (" << sdata.fTriggerRate << ", n=" << num << ")" << endl;
299 Out() << "Target: " << fTargetRate << endl;
300 }
301
302 if (sdata.fTriggerRate<fTriggerRate)
303 fTriggerRate = sdata.fTriggerRate;
304
305 // ----------------------
306
307 /*
308 if (avg>0 && avg<fTargetRate)
309 {
310 // I am assuming here (and at other places) the the answer from the FTM when setting
311 // the new threshold always arrives faster than the next rate update.
312 fThresholdMin = fThresholds[0];
313 Out() << "Setting fThresholdMin to " << fThresholds[0] << endl;
314 }
315 */
316
317 if (fTriggerRate>0 && fTriggerRate<fTargetRate)
318 {
319 fThresholds.assign(160, fThresholdMin);
320 return;
321 }
322
323 // This is a step towards a threshold at which the NSB rate is equal the target rate
324 // +1 to avoid getting a step of 0
325 const float step = (log10(fTriggerRate)-log10(fTargetRate))/0.039 + 1;
326
327 const uint16_t diff = fThresholdMin+int16_t(truncf(step));
328 if (diff<=fThresholdMin)
329 return;
330
331 if (fVerbose)
332 {
333 //Out() << idx/40 << "|" << (idx/4)%10 << "|" << idx%4;
334 Out() << fThresholdMin;
335 Out() << (step>0 ? " += " : " -= ");
336 Out() << step << " (" << diff << ")" << endl;
337 }
338
339 const uint32_t val[2] = { -1, diff };
340 DimClient::sendCommandNB("FTM_CONTROL/SET_THRESHOLD", (void*)val, 8);
341
342 fThresholdMin = diff;
343 }
344
345 void infoHandler()
346 {
347 DimInfo *curr = getInfo(); // get current DimInfo address
348 if (!curr)
349 return;
350
351 if (curr==&fFTM)
352 {
353 fStatusFTM = GetNewState(fFTM);
354 return;
355 }
356
357 if (curr==&fDim)
358 {
359 fStatusDim = GetNewState(fDim);
360 fStatusDim.second = curr->getSize()==4 ? curr->getInt() : 0;
361 return;
362 }
363 if (curr==&fRateScan)
364 {
365 fStatusRS = GetNewState(fRateScan);
366 fStatusRS.second = curr->getSize()==4 ? curr->getInt() : 0;
367 return;
368 }
369
370 static vector<uint8_t> counter(160);
371 if (curr==&fStatic)
372 {
373 if (!CheckEventSize(curr->getSize(), "infoHandler[DimStaticData]", sizeof(FTM::DimStaticData)))
374 return;
375
376 const FTM::DimStaticData &sdata = *static_cast<FTM::DimStaticData*>(curr->getData());
377 fTriggerOn = sdata.HasTrigger();
378
379 PrintThresholds(sdata);
380
381 fThresholds.assign(sdata.fThreshold, sdata.fThreshold+160);
382 return;
383 }
384
385 if (curr==&fRates)
386 {
387 if (fThresholds.size()==0)
388 return;
389
390 if (!fTriggerOn && !fEnabled)
391 return;
392
393 if (fStatusRS.second==5)
394 return;
395
396 if (!CheckEventSize(curr->getSize(), "infoHandler[DimTriggerRates]", sizeof(FTM::DimTriggerRates)))
397 return;
398
399 const FTM::DimTriggerRates &sdata = *static_cast<FTM::DimTriggerRates*>(curr->getData());
400
401 if (GetCurrentState()==kStateSettingGlobalThreshold)
402 ProcessCamera(sdata);
403
404 if (GetCurrentState()==kStateInProgress)
405 ProcessPatches(sdata);
406 }
407 }
408
409 int Calibrate()
410 {
411 if (!fTriggerOn)
412 {
413 Info("Trigger not switched on... CALIBRATE command ignored.");
414 return kStateGlobalThresholdSet;
415 }
416
417 const int32_t val[2] = { -1, fThresholdReference };
418 Dim::SendCommand("FTM_CONTROL/SET_THRESHOLD", val);
419
420 fThresholds.assign(160, fThresholdReference);
421
422 fThresholdMin = fThresholdReference;
423 fTriggerRate = -1;
424 fEnabled = true;
425 fCounter = 0;
426
427 ostringstream out;
428 out << "Rate calibration started at a threshold of " << fThresholdReference << " with a target rate of " << fTargetRate << " Hz";
429 Info(out);
430
431 return kStateSettingGlobalThreshold;
432 }
433
434 int StartRC()
435 {
436 fEnabled = true;
437 return GetCurrentState();
438 }
439
440 int StopRC()
441 {
442 fEnabled = false;
443 return GetCurrentState();
444 }
445
446 int SetEnabled(const EventImp &evt)
447 {
448 if (!CheckEventSize(evt.GetSize(), "SetEnabled", 1))
449 return kSM_FatalError;
450
451 fEnabled = evt.GetBool();
452
453 return GetCurrentState();
454 }
455
456 int SetMinThreshold(const EventImp &evt)
457 {
458 if (!CheckEventSize(evt.GetSize(), "SetMinThreshold", 4))
459 return kSM_FatalError;
460
461 // FIXME: Check missing
462
463 fThresholdReference = evt.GetUShort();
464
465 return GetCurrentState();
466 }
467
468 int SetTargetRate(const EventImp &evt)
469 {
470 if (!CheckEventSize(evt.GetSize(), "SetTargetRate", 4))
471 return kSM_FatalError;
472
473 fTargetRate = evt.GetFloat();
474
475 return GetCurrentState();
476 }
477
478 void PrintState(const pair<Time,int> &state, const char *server)
479 {
480 const State rc = fNetwork.GetState(server, state.second);
481
482 Out() << state.first.GetAsStr("%H:%M:%S.%f").substr(0, 12) << " - ";
483 Out() << kBold << server << ": ";
484 Out() << rc.name << "[" << rc.index << "]";
485 Out() << kReset << " - " << kBlue << rc.comment << endl;
486 }
487
488 int Print()
489 {
490 Out() << fStatusDim.first.GetAsStr("%H:%M:%S.%f").substr(0, 12) << " - ";
491 Out() << kBold << "DIM_DNS: ";
492 if (fStatusDim.second==0)
493 Out() << "Offline" << endl;
494 else
495 Out() << "V" << fStatusDim.second/100 << 'r' << fStatusDim.second%100 << endl;
496
497 PrintState(fStatusRS, "RATE_SCAN");
498 PrintState(fStatusFTM, "FTM_CONTROL");
499
500 return GetCurrentState();
501 }
502
503 int SetVerbosity(const EventImp &evt)
504 {
505 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
506 return kSM_FatalError;
507
508 fVerbose = evt.GetBool();
509
510 return GetCurrentState();
511 }
512
513 int Execute()
514 {
515 // Dispatch (execute) at most one handler from the queue. In contrary
516 // to run_one(), it doesn't wait until a handler is available
517 // which can be dispatched, so poll_one() might return with 0
518 // handlers dispatched. The handlers are always dispatched/executed
519 // synchronously, i.e. within the call to poll_one()
520 //poll_one();
521
522 if (fStatusDim.second==0)
523 return kStateDimNetworkNA;
524
525 // All subsystems are not connected
526 if (fStatusFTM.second<FTM::kConnected)
527 return kStateDisconnected;
528
529 if (GetCurrentState()==kStateSettingGlobalThreshold)
530 {
531 if (fTriggerRate<0 || fTriggerRate>fTargetRate)
532 return kStateSettingGlobalThreshold;
533
534 return kStateGlobalThresholdSet;
535 }
536
537 if (GetCurrentState()==kStateGlobalThresholdSet)
538 {
539 if (!fTriggerOn)
540 return kStateGlobalThresholdSet;
541 //return kStateInProgress;
542 }
543
544 // At least one subsystem is not connected
545 // if (fStatusFTM.second>=FTM::kConnected)
546 return fTriggerOn && fEnabled && fStatusRS.second!=5 ? kStateInProgress : kStateConnected;
547 }
548
549public:
550 StateMachineRateControl(ostream &out=cout) : StateMachineDim(out, "RATE_CONTROL"),
551 fTriggerOn(false), fBlock(40),
552 fStatusDim(make_pair(Time(), -2)),
553 fStatusFTM(make_pair(Time(), -2)),
554 fDim("DIS_DNS/VERSION_NUMBER", (void*)NULL, 0, this),
555 fFTM("FTM_CONTROL/STATE", (void*)NULL, 0, this),
556 fRates("FTM_CONTROL/TRIGGER_RATES", (void*)NULL, 0, this),
557 fStatic("FTM_CONTROL/STATIC_DATA", (void*)NULL, 0, this),
558 fRateScan("RATE_SCAN/STATE", (void*)NULL, 0, this)/*,
559 fDimData("RATE_SCAN/DATA", "I:1;F:1;F:1;F:1;F:40;F:160", ""),
560 fDimProc("RATE_SCAN/PROCESS_DATA", "I:1;I:1;I:1",
561 "Rate scan process data"
562 "|min[DAC]:Value at which scan was started"
563 "|max[DAC]:Value at which scan will end"
564 "|step[DAC]:Step size for scan")*/
565 {
566 // ba::io_service::work is a kind of keep_alive for the loop.
567 // It prevents the io_service to go to stopped state, which
568 // would prevent any consecutive calls to run()
569 // or poll() to do nothing. reset() could also revoke to the
570 // previous state but this might introduce some overhead of
571 // deletion and creation of threads and more.
572
573 // State names
574 AddStateName(kStateDimNetworkNA, "DimNetworkNotAvailable",
575 "The Dim DNS is not reachable.");
576
577 AddStateName(kStateDisconnected, "Disconnected",
578 "The Dim DNS is reachable, but the required subsystems are not available.");
579
580 AddStateName(kStateConnected, "Connected",
581 "All needed subsystems are connected to their hardware, no action is performed.");
582
583 AddStateName(kStateSettingGlobalThreshold, "Calibrating", "");
584 AddStateName(kStateGlobalThresholdSet, "GlobalThresholdSet", "");
585
586 AddStateName(kStateInProgress, "InProgress",
587 "Rate scan in progress.");
588
589 AddEvent("CALIBRATE")
590 (bind(&StateMachineRateControl::Calibrate, this))
591 ("");
592
593 AddEvent("START", "")
594 (bind(&StateMachineRateControl::StartRC, this))
595 ("");
596
597 AddEvent("STOP", "")
598 (bind(&StateMachineRateControl::StopRC, this))
599 ("");
600
601 AddEvent("SET_MIN_THRESHOLD", "I:1")
602 (bind(&StateMachineRateControl::SetMinThreshold, this, placeholders::_1))
603 ("");
604
605 AddEvent("SET_TARGET_RATE", "F:1")
606 (bind(&StateMachineRateControl::SetTargetRate, this, placeholders::_1))
607 ("");
608
609 AddEvent("PRINT")
610 (bind(&StateMachineRateControl::Print, this))
611 ("");
612
613 AddEvent("SET_VERBOSE", "B")
614 (bind(&StateMachineRateControl::SetVerbosity, this, placeholders::_1))
615 ("set verbosity state"
616 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
617
618 }
619
620 int EvalOptions(Configuration &conf)
621 {
622 fVerbose = !conf.Get<bool>("quiet");
623
624 fThresholdReference = 300;
625 fTargetRate = 75;
626
627 return -1;
628 }
629};
630
631// ------------------------------------------------------------------------
632
633#include "Main.h"
634
635template<class T>
636int RunShell(Configuration &conf)
637{
638 return Main::execute<T, StateMachineRateControl>(conf);
639}
640
641void SetupConfiguration(Configuration &conf)
642{
643 po::options_description control("Rate control options");
644 control.add_options()
645 ("quiet,q", po_bool(), "Disable printing more informations during rate control.")
646 //("max-wait", var<uint16_t>(150), "The maximum number of seconds to wait to get the anticipated resolution for a point.")
647 // ("resolution", var<double>(0.05) , "The minimum resolution required for a single data point.")
648 ;
649
650 conf.AddOptions(control);
651}
652
653/*
654 Extract usage clause(s) [if any] for SYNOPSIS.
655 Translators: "Usage" and "or" here are patterns (regular expressions) which
656 are used to match the usage synopsis in program output. An example from cp
657 (GNU coreutils) which contains both strings:
658 Usage: cp [OPTION]... [-T] SOURCE DEST
659 or: cp [OPTION]... SOURCE... DIRECTORY
660 or: cp [OPTION]... -t DIRECTORY SOURCE...
661 */
662void PrintUsage()
663{
664 cout <<
665 "The ratecontrol program is a keep the rate reasonable low.\n"
666 "\n"
667 "Usage: ratecontrol [-c type] [OPTIONS]\n"
668 " or: ratecontrol [OPTIONS]\n";
669 cout << endl;
670}
671
672void PrintHelp()
673{
674 Main::PrintHelp<StateMachineRateControl>();
675
676 /* Additional help text which is printed after the configuration
677 options goes here */
678
679 /*
680 cout << "bla bla bla" << endl << endl;
681 cout << endl;
682 cout << "Environment:" << endl;
683 cout << "environment" << endl;
684 cout << endl;
685 cout << "Examples:" << endl;
686 cout << "test exam" << endl;
687 cout << endl;
688 cout << "Files:" << endl;
689 cout << "files" << endl;
690 cout << endl;
691 */
692}
693
694int main(int argc, const char* argv[])
695{
696 Configuration conf(argv[0]);
697 conf.SetPrintUsage(PrintUsage);
698 Main::SetupConfiguration(conf);
699 SetupConfiguration(conf);
700
701 if (!conf.DoParse(argc, argv, PrintHelp))
702 return -1;
703
704 //try
705 {
706 // No console access at all
707 if (!conf.Has("console"))
708 {
709// if (conf.Get<bool>("no-dim"))
710// return RunShell<LocalStream, StateMachine, ConnectionFSC>(conf);
711// else
712 return RunShell<LocalStream>(conf);
713 }
714 // Cosole access w/ and w/o Dim
715/* if (conf.Get<bool>("no-dim"))
716 {
717 if (conf.Get<int>("console")==0)
718 return RunShell<LocalShell, StateMachine, ConnectionFSC>(conf);
719 else
720 return RunShell<LocalConsole, StateMachine, ConnectionFSC>(conf);
721 }
722 else
723*/ {
724 if (conf.Get<int>("console")==0)
725 return RunShell<LocalShell>(conf);
726 else
727 return RunShell<LocalConsole>(conf);
728 }
729 }
730 /*catch (std::exception& e)
731 {
732 cerr << "Exception: " << e.what() << endl;
733 return -1;
734 }*/
735
736 return 0;
737}
Note: See TracBrowser for help on using the repository browser.