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