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

Last change on this file since 20069 was 19437, checked in by tbretz, 6 years ago
Added a new calibration scheme ('3') which only starts a current calibration if previously no calibration was done.
File size: 32.4 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 "PixelMap.h"
11
12#include "tools.h"
13
14#include "LocalControl.h"
15
16#include "HeadersFTM.h"
17#include "HeadersLid.h"
18#include "HeadersDrive.h"
19#include "HeadersRateScan.h"
20#include "HeadersRateControl.h"
21
22namespace ba = boost::asio;
23namespace bs = boost::system;
24namespace dummy = ba::placeholders;
25
26using namespace std;
27
28// ------------------------------------------------------------------------
29
30#include "DimDescriptionService.h"
31#include "DimState.h"
32
33// ------------------------------------------------------------------------
34
35class StateMachineRateControl : public StateMachineDim//, public DimInfoHandler
36{
37private:
38 struct config
39 {
40 uint16_t fCalibrationType;
41 uint16_t fTargetRate;
42 uint16_t fMinThreshold;
43 uint16_t fAverageTime;
44 uint16_t fRequiredEvents;
45 };
46
47 map<string, config> fRunTypes;
48
49 PixelMap fMap;
50
51 bool fPhysTriggerEnabled;
52 bool fTriggerOn;
53
54 vector<bool> fBlock;
55
56 DimVersion fDim;
57 DimDescribedState fDimFTM;
58 DimDescribedState fDimRS;
59 DimDescribedState fDimLid;
60 DimDescribedState fDimDrive;
61
62 DimDescribedService fDimThreshold;
63
64 float fTargetRate;
65 float fTriggerRate;
66
67 uint16_t fThresholdMin;
68 uint16_t fThresholdReference;
69
70 uint16_t fAverageTime;
71 uint16_t fRequiredEvents;
72
73 list<pair<Time,float>> fCurrentsMed;
74 list<pair<Time,float>> fCurrentsDev;
75 list<pair<Time,vector<float>>> fCurrentsVec;
76
77 bool fVerbose;
78 bool fCalibrateByCurrent;
79
80 uint64_t fCounter;
81
82 Time fCalibrationTimeStart;
83
84 bool CheckEventSize(const EventImp &evt, size_t size)
85 {
86 if (size_t(evt.GetSize())==size)
87 return true;
88
89 if (evt.GetSize()==0)
90 return false;
91
92 ostringstream msg;
93 msg << evt.GetName() << " - Received event has " << evt.GetSize() << " bytes, but expected " << size << ".";
94 Fatal(msg);
95 return false;
96 }
97
98 vector<uint32_t> fThresholds;
99
100 void PrintThresholds(const FTM::DimStaticData &sdata)
101 {
102 if (!fVerbose)
103 return;
104
105 if (fThresholds.empty())
106 return;
107
108 if (GetCurrentState()<=RateControl::State::kConnected)
109 return;
110
111 Out() << "Min. DAC=" << fThresholdMin << endl;
112
113 for (int j=0; j<10; j++)
114 {
115 for (int k=0; k<4; k++)
116 {
117 for (int i=0; i<4; i++)
118 {
119 const int p = i + k*4 + j*16;
120
121 if (fThresholds[p]!=fThresholdMin)
122 Out() << setw(3) << fThresholds[p];
123 else
124 Out() << " - ";
125
126 if (fThresholds[p]!=sdata.fThreshold[p])
127 Out() << "!";
128 else
129 Out() << " ";
130 }
131
132 Out() << " ";
133 }
134 Out() << endl;
135 }
136 Out() << endl;
137 }
138
139 // RETURN VALUE
140 bool Step(int idx, float step)
141 {
142 uint32_t diff = fThresholds[idx]+int16_t(truncf(step));
143 if (diff<fThresholdMin)
144 diff=fThresholdMin;
145 if (diff>0xffff)
146 diff = 0xffff;
147
148 if (diff==fThresholds[idx])
149 return false;
150
151 if (fVerbose)
152 {
153 Out() << "Apply: Patch " << setw(3) << idx << " [" << idx/40 << "|" << (idx/4)%10 << "|" << idx%4 << "]";
154 Out() << (step>0 ? " += " : " -= ");
155 Out() << fabs(step) << " (old=" << fThresholds[idx] << ", new=" << diff << ")" << endl;
156 }
157
158 fThresholds[idx] = diff;
159 fBlock[idx/4] = true;
160
161 return true;
162 }
163
164 void ProcessPatches(const FTM::DimTriggerRates &sdata)
165 {
166
167 // Caluclate Median and deviation
168 vector<float> medb(sdata.fBoardRate, sdata.fBoardRate+40);
169 vector<float> medp(sdata.fPatchRate, sdata.fPatchRate+160);
170
171 sort(medb.begin(), medb.end());
172 sort(medp.begin(), medp.end());
173
174 vector<float> devb(40);
175 for (int i=0; i<40; i++)
176 devb[i] = fabs(sdata.fBoardRate[i]-medb[i]);
177
178 vector<float> devp(160);
179 for (int i=0; i<160; i++)
180 devp[i] = fabs(sdata.fPatchRate[i]-medp[i]);
181
182 sort(devb.begin(), devb.end());
183 sort(devp.begin(), devp.end());
184
185 const double mb = (medb[19]+medb[20])/2;
186 const double mp = (medp[79]+medp[80])/2;
187
188 const double db = devb[27];
189 const double dp = devp[109];
190
191 // If any is zero there is something wrong
192 if (mb==0 || mp==0 || db==0 || dp==0)
193 return;
194
195 if (fVerbose)
196 Out() << Tools::Form("Boards: Med=%3.1f +- %3.1f Hz Patches: Med=%3.1f +- %3.1f Hz", mb, db, mp, dp) << endl;
197
198 bool changed = false;
199
200 for (int i=0; i<40; i++)
201 {
202 if (fBlock[i])
203 {
204 fBlock[i] = false;
205 continue;
206 }
207
208 int maxi = -1;
209
210 const float dif = fabs(sdata.fBoardRate[i]-mb)/db;
211 if (dif>3)
212 {
213 if (fVerbose)
214 Out() << "Board " << setw(3) << i << ": " << dif << " dev away from med" << endl;
215
216 float max = sdata.fPatchRate[i*4];
217 maxi = 0;
218
219 for (int j=1; j<4; j++)
220 if (sdata.fPatchRate[i*4+j]>max)
221 {
222 max = sdata.fPatchRate[i*4+j];
223 maxi = j;
224 }
225 }
226
227 for (int j=0; j<4; j++)
228 {
229 // For the noise pixel correct down to median+3*deviation
230 if (maxi==j)
231 {
232 // This is the step which has to be performed to go from
233 // a NSB rate of sdata.fPatchRate[i*4+j]
234
235
236 const float step = (log10(sdata.fPatchRate[i*4+j])-log10(mp+3.5*dp))/0.039;
237 // * (dif-5)/dif
238 changed |= Step(i*4+j, step);
239 continue;
240 }
241
242 // For pixels below the median correct also back to median+3*deviation
243 if (sdata.fPatchRate[i*4+j]<mp)
244 {
245 const float step = (log10(sdata.fPatchRate[i*4+j])-log10(mp+3.5*dp))/0.039;
246 changed |= Step(i*4+j, step);
247 continue;
248 }
249
250 const float step = -1.5*(log10(mp+dp)-log10(mp))/0.039;
251 changed |= Step(i*4+j, step);
252 }
253 }
254
255 if (changed)
256 Dim::SendCommandNB("FTM_CONTROL/SET_SELECTED_THRESHOLDS", fThresholds);
257 }
258
259 int ProcessCamera(const FTM::DimTriggerRates &sdata)
260 {
261 if (fCounter++==0)
262 return GetCurrentState();
263
264 // Caluclate Median and deviation
265 vector<float> medb(sdata.fBoardRate, sdata.fBoardRate+40);
266
267 sort(medb.begin(), medb.end());
268
269 vector<float> devb(40);
270 for (int i=0; i<40; i++)
271 devb[i] = fabs(sdata.fBoardRate[i]-medb[i]);
272
273 sort(devb.begin(), devb.end());
274
275 double mb = (medb[19]+medb[20])/2;
276 double db = devb[27];
277
278 // If any is zero there is something wrong
279 if (mb==0 || db==0)
280 {
281 Warn("The median or the deviation of all board rates is zero... cannot calibrate.");
282 return GetCurrentState();
283 }
284
285 double avg = 0;
286 int num = 0;
287
288 for (int i=0; i<40; i++)
289 {
290 if ( fabs(sdata.fBoardRate[i]-mb)<2.5*db)
291 {
292 avg += sdata.fBoardRate[i];
293 num++;
294 }
295 }
296
297 fTriggerRate = avg/num * 40;
298
299 if (fVerbose)
300 {
301 Out() << "Board: Median=" << mb << " Dev=" << db << endl;
302 Out() << "Camera: " << fTriggerRate << " (" << sdata.fTriggerRate << ", n=" << num << ")" << endl;
303 Out() << "Target: " << fTargetRate << endl;
304 }
305
306 if (sdata.fTriggerRate<fTriggerRate)
307 fTriggerRate = sdata.fTriggerRate;
308
309 // ----------------------
310
311 /*
312 if (avg>0 && avg<fTargetRate)
313 {
314 // I am assuming here (and at other places) the the answer from the FTM when setting
315 // the new threshold always arrives faster than the next rate update.
316 fThresholdMin = fThresholds[0];
317 Out() << "Setting fThresholdMin to " << fThresholds[0] << endl;
318 }
319 */
320
321 if (fTriggerRate>0 && fTriggerRate<fTargetRate)
322 {
323 fThresholds.assign(160, fThresholdMin);
324
325 const RateControl::DimThreshold data = { fThresholdMin, fCalibrationTimeStart.Mjd(), Time().Mjd() };
326 fDimThreshold.setQuality(0);
327 fDimThreshold.Update(data);
328
329 ostringstream out;
330 out << setprecision(3);
331 out << "Measured rate " << fTriggerRate << "Hz below target rate " << fTargetRate << "... minimum threshold set to " << fThresholdMin;
332 Info(out);
333
334 fTriggerOn = false;
335 fPhysTriggerEnabled = false;
336 return RateControl::State::kGlobalThresholdSet;
337 }
338
339 // This is a step towards a threshold at which the NSB rate is equal the target rate
340 // +1 to avoid getting a step of 0
341 const float step = (log10(fTriggerRate)-log10(fTargetRate))/0.039 + 1;
342
343 const uint16_t diff = fThresholdMin+int16_t(truncf(step));
344 if (diff<=fThresholdMin)
345 {
346 const RateControl::DimThreshold data = { fThresholdMin, fCalibrationTimeStart.Mjd(), Time().Mjd() };
347 fDimThreshold.setQuality(1);
348 fDimThreshold.Update(data);
349
350 ostringstream out;
351 out << setprecision(3);
352 out << "Next step would be 0... minimum threshold set to " << fThresholdMin;
353 Info(out);
354
355 fTriggerOn = false;
356 fPhysTriggerEnabled = false;
357 return RateControl::State::kGlobalThresholdSet;
358 }
359
360 if (fVerbose)
361 {
362 //Out() << idx/40 << "|" << (idx/4)%10 << "|" << idx%4;
363 Out() << fThresholdMin;
364 Out() << (step>0 ? " += " : " -= ");
365 Out() << step << " (" << diff << ")" << endl;
366 }
367
368 const uint32_t val[2] = { uint32_t(-1), diff };
369 Dim::SendCommandNB("FTM_CONTROL/SET_THRESHOLD", val);
370
371 fThresholdMin = diff;
372
373 return GetCurrentState();
374 }
375
376 int HandleStaticData(const EventImp &evt)
377 {
378 if (!CheckEventSize(evt, sizeof(FTM::DimStaticData)))
379 return GetCurrentState();
380
381 const FTM::DimStaticData &sdata = *static_cast<const FTM::DimStaticData*>(evt.GetData());
382 fPhysTriggerEnabled = sdata.HasTrigger();
383 fTriggerOn = (evt.GetQoS()&FTM::kFtmStates)==FTM::kFtmRunning;
384
385 Out() << "\n" << evt.GetTime() << ": " << (bool)fTriggerOn << " " << (bool)fPhysTriggerEnabled << endl;
386 PrintThresholds(sdata);
387
388 if (GetCurrentState()==RateControl::State::kSettingGlobalThreshold && fCalibrateByCurrent)
389 {
390 if (fThresholds.empty())
391 return RateControl::State::kSettingGlobalThreshold;
392
393 if (!std::equal(sdata.fThreshold, sdata.fThreshold+160, fThresholds.begin()))
394 return RateControl::State::kSettingGlobalThreshold;
395
396 return RateControl::State::kGlobalThresholdSet;
397 }
398
399 fThresholds.assign(sdata.fThreshold, sdata.fThreshold+160);
400
401 return GetCurrentState();
402 }
403
404 int HandleTriggerRates(const EventImp &evt)
405 {
406 fTriggerOn = (evt.GetQoS()&FTM::kFtmStates)==FTM::kFtmRunning;
407
408 if (fThresholds.empty())
409 return GetCurrentState();
410
411 if (GetCurrentState()<=RateControl::State::kConnected ||
412 GetCurrentState()==RateControl::State::kGlobalThresholdSet)
413 return GetCurrentState();
414
415 if (!CheckEventSize(evt, sizeof(FTM::DimTriggerRates)))
416 return GetCurrentState();
417
418 const FTM::DimTriggerRates &sdata = *static_cast<const FTM::DimTriggerRates*>(evt.GetData());
419
420 if (GetCurrentState()==RateControl::State::kSettingGlobalThreshold && !fCalibrateByCurrent)
421 return ProcessCamera(sdata);
422
423 if (GetCurrentState()==RateControl::State::kInProgress)
424 ProcessPatches(sdata);
425
426 return GetCurrentState();
427 }
428
429 int HandleCalibratedCurrents(const EventImp &evt)
430 {
431 // Check if received event is valid
432 if (!CheckEventSize(evt, (2*416+8)*4))
433 return GetCurrentState();
434
435 // Record only currents when the drive is tracking to avoid
436 // bias from the movement
437 if (fDimDrive.state()<Drive::State::kTracking || fDimLid.state()==Lid::State::kClosed)
438 return GetCurrentState();
439
440 // Get time and median current (FIXME: check N?)
441 const Time &time = evt.GetTime();
442 const float med = evt.Get<float>(416*4+4+4);
443 const float dev = evt.Get<float>(416*4+4+4+4);
444 const float *cur = evt.Ptr<float>();
445
446 // Keep all median currents of the past 10 seconds
447 fCurrentsMed.emplace_back(time, med);
448 fCurrentsDev.emplace_back(time, dev);
449 fCurrentsVec.emplace_back(time, vector<float>(cur, cur+320));
450 while (!fCurrentsMed.empty())
451 {
452 if (time-fCurrentsMed.front().first<boost::posix_time::seconds(fAverageTime))
453 break;
454
455 fCurrentsMed.pop_front();
456 fCurrentsDev.pop_front();
457 fCurrentsVec.pop_front();
458 }
459
460 // If we are not doing a calibration no further action necessary
461 if (!fCalibrateByCurrent)
462 return GetCurrentState();
463
464 // We are not setting thresholds at all
465 if (GetCurrentState()!=RateControl::State::kSettingGlobalThreshold)
466 return GetCurrentState();
467
468 // Target thresholds have been assigned already
469 if (!fThresholds.empty())
470 return GetCurrentState();
471
472 // We want at least 8 values for averaging
473 if (fCurrentsMed.size()<fRequiredEvents)
474 return GetCurrentState();
475
476 // Calculate avera and rms of median
477 double avg = 0;
478 double rms = 0;
479 for (auto it=fCurrentsMed.begin(); it!=fCurrentsMed.end(); it++)
480 {
481 avg += it->second;
482 rms += it->second*it->second;
483 }
484 avg /= fCurrentsMed.size();
485 rms /= fCurrentsMed.size();
486 rms -= avg*avg;
487 rms = rms<0 ? 0 : sqrt(rms);
488
489 double avg_dev = 0;
490 for (auto it=fCurrentsDev.begin(); it!=fCurrentsDev.end(); it++)
491 avg_dev += it->second;
492 avg_dev /= fCurrentsMed.size();
493
494 // One could recalculate the median of all pixels including the
495 // correction for the three crazy pixels, but that is three out
496 // of 320. The effect on the median should be negligible anyhow.
497 vector<double> vec(160);
498 for (auto it=fCurrentsVec.begin(); it!=fCurrentsVec.end(); it++)
499 for (int i=0; i<320; i++)
500 {
501 const PixelMapEntry &hv = fMap.hv(i);
502 if (hv)
503 vec[hv.hw()/9] += it->second[i]*hv.count();
504 }
505
506 //fThresholdMin = max(uint16_t(36.0833*pow(avg, 0.638393)+184.037), fThresholdReference);
507 //fThresholdMin = max(uint16_t(42.4*pow(avg, 0.642)+182), fThresholdReference);
508 //fThresholdMin = max(uint16_t(41.6*pow(avg+1, 0.642)+175), fThresholdReference);
509 //fThresholdMin = max(uint16_t(42.3*pow(avg, 0.655)+190), fThresholdReference);
510 //fThresholdMin = max(uint16_t(46.6*pow(avg, 0.627)+187), fThresholdReference);
511 fThresholdMin = max(uint16_t(156.3*pow(avg, 0.3925)+1), fThresholdReference);
512 //fThresholdMin = max(uint16_t(41.6*pow(avg, 0.642)+175), fThresholdReference);
513 fThresholds.assign(160, fThresholdMin);
514
515 int counter = 1;
516
517 double avg2 = 0;
518 for (int i=0; i<160; i++)
519 {
520 vec[i] /= fCurrentsVec.size()*9;
521
522 avg2 += vec[i];
523
524 if (vec[i]>avg+3.5*avg_dev)
525 {
526 fThresholds[i] = max(uint16_t(40.5*pow(vec[i], 0.642)+164), fThresholdMin);
527
528 counter++;
529 }
530 }
531 avg2 /= 160;
532
533
534 Dim::SendCommandNB("FTM_CONTROL/SET_ALL_THRESHOLDS", fThresholds);
535
536
537 const RateControl::DimThreshold data = { fThresholdMin, fCalibrationTimeStart.Mjd(), Time().Mjd() };
538 fDimThreshold.setQuality(2);
539 fDimThreshold.Update(data);
540
541 //Info("Sent a total of "+to_string(counter)+" commands for threshold setting");
542
543 ostringstream out;
544 out << setprecision(3);
545 out << "Measured average current " << avg << "uA +- " << rms << "uA [N=" << fCurrentsMed.size() << "]... minimum threshold set to " << fThresholdMin;
546 Info(out);
547 Info("Set "+to_string(counter)+" individual thresholds.");
548
549 fTriggerOn = false;
550 fPhysTriggerEnabled = false;
551
552 return RateControl::State::kSettingGlobalThreshold;
553 }
554
555 int Calibrate()
556 {
557 const int32_t val[2] = { -1, fThresholdReference };
558 Dim::SendCommandNB("FTM_CONTROL/SET_THRESHOLD", val);
559
560 fThresholds.assign(160, fThresholdReference);
561
562 fThresholdMin = fThresholdReference;
563 fTriggerRate = -1;
564 fCounter = 0;
565 fBlock.assign(160, false);
566
567 fCalibrateByCurrent = false;
568 fCalibrationTimeStart = Time();
569
570 ostringstream out;
571 out << "Rate calibration started at a threshold of " << fThresholdReference << " with a target rate of " << fTargetRate << " Hz";
572 Info(out);
573
574 return RateControl::State::kSettingGlobalThreshold;
575 }
576
577 int CalibrateByCurrent()
578 {
579 fCounter = 0;
580 fCalibrateByCurrent = true;
581 fCalibrationTimeStart = Time();
582 fBlock.assign(160, false);
583
584 fThresholds.clear();
585
586 ostringstream out;
587 out << "Rate calibration by current with min. threshold of " << fThresholdReference << ".";
588 Info(out);
589
590 return RateControl::State::kSettingGlobalThreshold;
591 }
592
593 int CalibrateRun(const EventImp &evt)
594 {
595 const string name = evt.GetText();
596
597 auto it = fRunTypes.find(name);
598 if (it==fRunTypes.end())
599 {
600 Info("CalibrateRun - Run-type '"+name+"' not found... trying 'default'.");
601
602 it = fRunTypes.find("default");
603 if (it==fRunTypes.end())
604 {
605 Error("CalibrateRun - Run-type 'default' not found.");
606 return GetCurrentState();
607 }
608 }
609
610 const config &conf = it->second;
611
612 if (conf.fCalibrationType!=0)
613 {
614
615 if (!fPhysTriggerEnabled)
616 {
617 Info("Calibration requested, but physics trigger not enabled... CALIBRATE command ignored.");
618
619 fTriggerOn = false;
620 fPhysTriggerEnabled = false;
621 return RateControl::State::kGlobalThresholdSet;
622 }
623
624 if (fDimLid.state()==Lid::State::kClosed)
625 {
626 Info("Calibration requested, but lid closed... setting all thresholds to "+to_string(conf.fMinThreshold)+".");
627
628 const int32_t val[2] = { -1, conf.fMinThreshold };
629 Dim::SendCommandNB("FTM_CONTROL/SET_THRESHOLD", val);
630
631 fThresholds.assign(160, conf.fMinThreshold);
632
633 const double mjd = Time().Mjd();
634
635 const RateControl::DimThreshold data = { conf.fMinThreshold, mjd, mjd };
636 fDimThreshold.setQuality(3);
637 fDimThreshold.Update(data);
638
639 fCalibrateByCurrent = true;
640 fTriggerOn = false;
641 fPhysTriggerEnabled = false;
642 return RateControl::State::kSettingGlobalThreshold;
643 }
644
645 if (fDimDrive.state()<Drive::State::kMoving)
646 Warn("Calibration requested, but drive not even moving...");
647 }
648
649 switch (conf.fCalibrationType)
650 {
651 case 0:
652 Info("No calibration requested.");
653 fTriggerOn = false;
654 fPhysTriggerEnabled = false;
655 return RateControl::State::kGlobalThresholdSet;
656 break;
657
658 case 1:
659 fThresholdReference = conf.fMinThreshold;
660 fTargetRate = conf.fTargetRate;
661 return Calibrate();
662
663 case 2:
664 fThresholdReference = conf.fMinThreshold;
665 fAverageTime = conf.fAverageTime;
666 fRequiredEvents = conf.fRequiredEvents;
667 return CalibrateByCurrent();
668
669 case 3: // This is a fast mode which keeps the system running if already running
670 if (GetCurrentState()==RateControl::State::kInProgress)
671 {
672 Info("Keeping previous calibration.");
673 return GetCurrentState();
674 }
675
676 // If not yet running
677 fThresholdReference = conf.fMinThreshold;
678 fAverageTime = conf.fAverageTime;
679 fRequiredEvents = conf.fRequiredEvents;
680 return CalibrateByCurrent();
681 }
682
683 Error("CalibrateRun - Calibration type "+to_string(conf.fCalibrationType)+" unknown.");
684 return GetCurrentState();
685 }
686
687 int StopRC()
688 {
689 Info("Stop received.");
690 return RateControl::State::kConnected;
691 }
692
693 int SetMinThreshold(const EventImp &evt)
694 {
695 if (!CheckEventSize(evt, 4))
696 return kSM_FatalError;
697
698 // FIXME: Check missing
699
700 fThresholdReference = evt.GetUShort();
701
702 return GetCurrentState();
703 }
704
705 int SetTargetRate(const EventImp &evt)
706 {
707 if (!CheckEventSize(evt, 4))
708 return kSM_FatalError;
709
710 fTargetRate = evt.GetFloat();
711
712 return GetCurrentState();
713 }
714
715 int Print() const
716 {
717 Out() << fDim << endl;
718 Out() << fDimFTM << endl;
719 Out() << fDimRS << endl;
720 Out() << fDimLid << endl;
721 Out() << fDimDrive << endl;
722
723 return GetCurrentState();
724 }
725
726 int SetVerbosity(const EventImp &evt)
727 {
728 if (!CheckEventSize(evt, 1))
729 return kSM_FatalError;
730
731 fVerbose = evt.GetBool();
732
733 return GetCurrentState();
734 }
735
736 int Execute()
737 {
738 if (!fDim.online())
739 return RateControl::State::kDimNetworkNA;
740
741 // All subsystems are not connected
742 if (fDimFTM.state()<FTM::State::kConnected || fDimDrive.state()<Drive::State::kConnected)
743 return RateControl::State::kDisconnected;
744
745 // Do not allow any action while a ratescan is configured or in progress
746 if (fDimRS.state()>=RateScan::State::kConfiguring)
747 return RateControl::State::kConnected;
748
749 switch (GetCurrentState())
750 {
751 case RateControl::State::kSettingGlobalThreshold:
752 return RateControl::State::kSettingGlobalThreshold;
753
754 case RateControl::State::kGlobalThresholdSet:
755
756 // Wait for the trigger to get switched on before starting control loop
757 if (fTriggerOn && fPhysTriggerEnabled)
758 return RateControl::State::kInProgress;
759
760 return RateControl::State::kGlobalThresholdSet;
761
762 case RateControl::State::kInProgress:
763
764 // Go back to connected when the trigger has been switched off
765 if (!fTriggerOn || !fPhysTriggerEnabled)
766 return RateControl::State::kConnected;
767
768 return RateControl::State::kInProgress;
769 }
770
771 return RateControl::State::kConnected;
772 }
773
774public:
775 StateMachineRateControl(ostream &out=cout) : StateMachineDim(out, "RATE_CONTROL"),
776 fPhysTriggerEnabled(false), fTriggerOn(false), fBlock(40),
777 fDimFTM("FTM_CONTROL"),
778 fDimRS("RATE_SCAN"),
779 fDimLid("LID_CONTROL"),
780 fDimDrive("DRIVE_CONTROL"),
781 fDimThreshold("RATE_CONTROL/THRESHOLD", "S:1;D:1;D:1",
782 "Resulting threshold after calibration"
783 "|threshold[dac]:Resulting threshold from calibration"
784 "|begin[mjd]:Start time of calibration"
785 "|end[mjd]:End time of calibration")
786 {
787 // ba::io_service::work is a kind of keep_alive for the loop.
788 // It prevents the io_service to go to stopped state, which
789 // would prevent any consecutive calls to run()
790 // or poll() to do nothing. reset() could also revoke to the
791 // previous state but this might introduce some overhead of
792 // deletion and creation of threads and more.
793
794 fDim.Subscribe(*this);
795 fDimFTM.Subscribe(*this);
796 fDimRS.Subscribe(*this);
797 fDimLid.Subscribe(*this);
798 fDimDrive.Subscribe(*this);
799
800 Subscribe("FTM_CONTROL/TRIGGER_RATES")
801 (bind(&StateMachineRateControl::HandleTriggerRates, this, placeholders::_1));
802 Subscribe("FTM_CONTROL/STATIC_DATA")
803 (bind(&StateMachineRateControl::HandleStaticData, this, placeholders::_1));
804 Subscribe("FEEDBACK/CALIBRATED_CURRENTS")
805 (bind(&StateMachineRateControl::HandleCalibratedCurrents, this, placeholders::_1));
806
807 // State names
808 AddStateName(RateControl::State::kDimNetworkNA, "DimNetworkNotAvailable",
809 "The Dim DNS is not reachable.");
810
811 AddStateName(RateControl::State::kDisconnected, "Disconnected",
812 "The Dim DNS is reachable, but the required subsystems are not available.");
813
814 AddStateName(RateControl::State::kConnected, "Connected",
815 "All needed subsystems are connected to their hardware, no action is performed.");
816
817 AddStateName(RateControl::State::kSettingGlobalThreshold, "Calibrating",
818 "A global minimum threshold is currently determined.");
819
820 AddStateName(RateControl::State::kGlobalThresholdSet, "GlobalThresholdSet",
821 "A global threshold has ben set, waiting for the trigger to be switched on.");
822
823 AddStateName(RateControl::State::kInProgress, "InProgress",
824 "Rate control in progress.");
825
826 AddEvent("CALIBRATE")
827 (bind(&StateMachineRateControl::Calibrate, this))
828 ("Start a search for a reasonable minimum global threshold");
829
830 AddEvent("CALIBRATE_BY_CURRENT")
831 (bind(&StateMachineRateControl::CalibrateByCurrent, this))
832 ("Set the global threshold from the median current");
833
834 AddEvent("CALIBRATE_RUN", "C")
835 (bind(&StateMachineRateControl::CalibrateRun, this, placeholders::_1))
836 ("Start a threshold calibration as defined in the setup for this run-type, state change to InProgress is delayed until trigger enabled");
837
838 AddEvent("STOP", RateControl::State::kSettingGlobalThreshold, RateControl::State::kGlobalThresholdSet, RateControl::State::kInProgress)
839 (bind(&StateMachineRateControl::StopRC, this))
840 ("Stop a calibration or ratescan in progress");
841
842 AddEvent("SET_MIN_THRESHOLD", "I:1")
843 (bind(&StateMachineRateControl::SetMinThreshold, this, placeholders::_1))
844 ("Set a minimum threshold at which th rate control starts calibrating");
845
846 AddEvent("SET_TARGET_RATE", "F:1")
847 (bind(&StateMachineRateControl::SetTargetRate, this, placeholders::_1))
848 ("Set a target trigger rate for the calibration");
849
850 AddEvent("PRINT")
851 (bind(&StateMachineRateControl::Print, this))
852 ("Print current status");
853
854 AddEvent("SET_VERBOSE", "B")
855 (bind(&StateMachineRateControl::SetVerbosity, this, placeholders::_1))
856 ("set verbosity state"
857 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
858
859 }
860
861 bool GetConfig(Configuration &conf, const string &name, const string &sub, uint16_t &rc)
862 {
863 if (conf.HasDef(name, sub))
864 {
865 rc = conf.GetDef<uint16_t>(name, sub);
866 return true;
867 }
868
869 Error("Neither "+name+"default nor "+name+sub+" found.");
870 return false;
871 }
872
873 int EvalOptions(Configuration &conf)
874 {
875 fVerbose = !conf.Get<bool>("quiet");
876
877 if (!fMap.Read(conf.GetPrefixedString("pixel-map-file")))
878 {
879 Error("Reading mapping table from "+conf.Get<string>("pixel-map-file")+" failed.");
880 return 1;
881 }
882
883 fThresholdReference = 300;
884 fThresholdMin = 300;
885 fTargetRate = 75;
886
887 fAverageTime = 10;
888 fRequiredEvents = 8;
889
890 // ---------- Setup run types ---------
891 const vector<string> types = conf.Vec<string>("run-type");
892 if (types.empty())
893 Warn("No run-types defined.");
894 else
895 Message("Defining run-types");
896
897 for (auto it=types.begin(); it!=types.end(); it++)
898 {
899 Message(" -> "+ *it);
900
901 if (fRunTypes.count(*it)>0)
902 {
903 Error("Run-type "+*it+" defined twice.");
904 return 1;
905 }
906
907 config &c = fRunTypes[*it];
908 if (!GetConfig(conf, "calibration-type.", *it, c.fCalibrationType) ||
909 !GetConfig(conf, "target-rate.", *it, c.fTargetRate) ||
910 !GetConfig(conf, "min-threshold.", *it, c.fMinThreshold) ||
911 !GetConfig(conf, "average-time.", *it, c.fAverageTime) ||
912 !GetConfig(conf, "required-events.", *it, c.fRequiredEvents))
913 return 2;
914 }
915
916 return -1;
917 }
918};
919
920// ------------------------------------------------------------------------
921
922#include "Main.h"
923
924template<class T>
925int RunShell(Configuration &conf)
926{
927 return Main::execute<T, StateMachineRateControl>(conf);
928}
929
930void SetupConfiguration(Configuration &conf)
931{
932 po::options_description control("Rate control options");
933 control.add_options()
934 ("quiet,q", po_bool(), "Disable printing more informations during rate control.")
935 ("pixel-map-file", var<string>()->required(), "Pixel mapping file. Used here to get the default reference voltage.")
936 //("max-wait", var<uint16_t>(150), "The maximum number of seconds to wait to get the anticipated resolution for a point.")
937 // ("resolution", var<double>(0.05) , "The minimum resolution required for a single data point.")
938 ;
939
940 conf.AddOptions(control);
941
942 po::options_description runtype("Run type configuration");
943 runtype.add_options()
944 ("run-type", vars<string>(), "Name of run-types (replace the * in the following configuration by the case-sensitive names defined here)")
945 ("calibration-type.*", var<uint16_t>(), "Calibration type (0: none, 1: by rate, 2: by current)")
946 ("target-rate.*", var<uint16_t>(), "Target rate for calibration by rate")
947 ("min-threshold.*", var<uint16_t>(), "Minimum threshold which can be applied in a calibration")
948 ("average-time.*", var<uint16_t>(), "Time in seconds to average the currents for a calibration by current.")
949 ("required-events.*", var<uint16_t>(), "Number of required current events to start a calibration by current.");
950 ;
951
952 conf.AddOptions(runtype);
953}
954
955/*
956 Extract usage clause(s) [if any] for SYNOPSIS.
957 Translators: "Usage" and "or" here are patterns (regular expressions) which
958 are used to match the usage synopsis in program output. An example from cp
959 (GNU coreutils) which contains both strings:
960 Usage: cp [OPTION]... [-T] SOURCE DEST
961 or: cp [OPTION]... SOURCE... DIRECTORY
962 or: cp [OPTION]... -t DIRECTORY SOURCE...
963 */
964void PrintUsage()
965{
966 cout <<
967 "The ratecontrol program is a keep the rate reasonable low.\n"
968 "\n"
969 "Usage: ratecontrol [-c type] [OPTIONS]\n"
970 " or: ratecontrol [OPTIONS]\n";
971 cout << endl;
972}
973
974void PrintHelp()
975{
976 Main::PrintHelp<StateMachineRateControl>();
977
978 /* Additional help text which is printed after the configuration
979 options goes here */
980
981 /*
982 cout << "bla bla bla" << endl << endl;
983 cout << endl;
984 cout << "Environment:" << endl;
985 cout << "environment" << endl;
986 cout << endl;
987 cout << "Examples:" << endl;
988 cout << "test exam" << endl;
989 cout << endl;
990 cout << "Files:" << endl;
991 cout << "files" << endl;
992 cout << endl;
993 */
994}
995
996int main(int argc, const char* argv[])
997{
998 Configuration conf(argv[0]);
999 conf.SetPrintUsage(PrintUsage);
1000 Main::SetupConfiguration(conf);
1001 SetupConfiguration(conf);
1002
1003 if (!conf.DoParse(argc, argv, PrintHelp))
1004 return 127;
1005
1006 if (!conf.Has("console"))
1007 return RunShell<LocalStream>(conf);
1008
1009 if (conf.Get<int>("console")==0)
1010 return RunShell<LocalShell>(conf);
1011 else
1012 return RunShell<LocalConsole>(conf);
1013
1014 return 0;
1015}
Note: See TracBrowser for help on using the repository browser.