source: trunk/FACT++/src/feedback.cc@ 16991

Last change on this file since 16991 was 16967, checked in by tbretz, 11 years ago
Updated new feedback algorithm.
File size: 59.7 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 "externals/PixelMap.h"
12
13#include "tools.h"
14
15#include "LocalControl.h"
16
17#include "HeadersFAD.h"
18#include "HeadersFSC.h"
19#include "HeadersBIAS.h"
20#include "HeadersFeedback.h"
21
22#include "DimState.h"
23#include "DimDescriptionService.h"
24
25using namespace std;
26
27// ------------------------------------------------------------------------
28
29class StateMachineFeedback : public StateMachineDim
30{
31private:
32 enum control_t
33 {
34 kIdle,
35 kTemp,
36 kFeedback,
37 kFeedbackGlobal,
38 kCurrents,
39 kCurrentsNew,
40 };
41
42 control_t fControlType;
43
44 PixelMap fMap;
45
46 DimVersion fDim;
47 DimDescribedState fDimFAD;
48 DimDescribedState fDimFSC;
49 DimDescribedState fDimBias;
50
51 DimDescribedService fDimReference;
52 DimDescribedService fDimDeviation;
53 DimDescribedService fDimCalibration;
54 DimDescribedService fDimCurrents;
55
56 vector<int64_t> fCurrentsAvg;
57 vector<int64_t> fCurrentsRms;
58
59 vector<float> fCalibration;
60 vector<float> fVoltGapd;
61 vector<float> fBiasVolt;
62
63 vector<vector<float>> fData;
64
65 int64_t fCursorCur;
66 uint64_t fCursorAmpl;
67 uint64_t fCursorTemp;
68
69 Time fBiasLast;
70 Time fStartTime;
71 Time fCalibTime;
72
73 valarray<double> fPV[3]; // Process variable (intgerated/averaged amplitudes)
74 valarray<double> fSP; // Set point (target amplitudes)
75
76 double fKp; // Proportional constant
77 double fKi; // Integral constant
78 double fKd; // Derivative constant
79 double fT; // Time constant (cycle time)
80 double fGain; // Gain (conversion from a DRS voltage deviation into a BIAS voltage change at G-APD reference voltage)
81
82 double fT21;
83
84 double fBiasOffset;
85 double fTempOffset;
86 double fCalibrationOffset;
87 double fAppliedOffset;
88
89 uint16_t fCurrentRequestInterval;
90 uint16_t fNumCalibIgnore;
91 uint16_t fNumCalibRequests;
92
93 bool fOutputEnabled;
94
95 int HandleCameraTemp(const EventImp &evt)
96 {
97 if (fControlType!=kTemp && fControlType!=kCurrents && fControlType!=kCurrentsNew)
98 return GetCurrentState();
99
100 if (evt.GetSize()!=60*sizeof(float))
101 return GetCurrentState();
102
103 const float *ptr = evt.Ptr<float>();
104
105 double avgt = 0;
106 int numt = 0;
107 for (int i=1; i<32; i++)
108 if (ptr[i]!=0)
109 {
110 avgt += ptr[i];
111 numt++;
112 }
113
114 if (numt==0)
115 {
116 Warn("Received sensor temperatures all invalid.");
117 return GetCurrentState();
118 }
119
120 avgt /= numt; // [deg C]
121
122 fTempOffset = (avgt-25)*4./70; // [V]
123
124 fCursorTemp++;
125
126 return fControlType==kCurrentsNew ? HandleCurrentControlNew() : HandleCurrentControl();
127 }
128
129 int HandleCurrentControlNew()
130 {
131 if (GetCurrentState()==Feedback::State::kCalibrating && fBiasOffset>fTempOffset-1.2)
132 {
133 fCursorTemp = 0;
134
135 ostringstream msg;
136 msg << " (applied calibration offset " << fBiasOffset << "V exceeds temperature correction " << fTempOffset << "V - 1.2V.";
137 Warn("Trying to calibrate above G-APD breakdown volatge!");
138 Warn(msg);
139 return GetCurrentState();
140 }
141
142 double avg[2] = { 0, 0 };
143 double min[2] = { 90, 90 };
144 double max[2] = { -90, -90 };
145 int num[2] = { 0, 0 };
146
147 vector<double> med[2];
148 med[0].resize(416);
149 med[1].resize(416);
150
151 //const float *Ravg = fCalibration.data()+BIAS::kNumChannels*2; // Measured resistance
152
153 vector<float> vec(2*BIAS::kNumChannels+2);
154
155 vec[BIAS::kNumChannels*2] = fTempOffset;
156 vec[BIAS::kNumChannels*2+1] = fBiasOffset;
157
158 float *Uoff = vec.data()+BIAS::kNumChannels;
159
160 if (GetCurrentState()==Feedback::State::kCalibrating)
161 for (int i=0; i<BIAS::kNumChannels; i++)
162 Uoff[i] = fBiasOffset;
163 else
164 for (int i=0; i<BIAS::kNumChannels; i++)
165 Uoff[i] = fTempOffset+fBiasOffset;
166
167 if (fControlType==kCurrentsNew)
168 {
169 // Would be a devision by zero. We need informations first.
170 if (fCursorCur==0)
171 return GetCurrentState();
172
173 vector<double> dI;
174 vector<double> R8;
175 vector<double> R9;
176
177 for (int i=0; i<BIAS::kNumChannels; i++)
178 {
179 const PixelMapEntry &hv = fMap.hv(i);
180 if (!hv)
181 continue;
182
183 // Nominal breakdown voltage (includes overvoltage already)
184 double Ubd = fVoltGapd[i];
185
186 // Nominal breakdown voltage excluding overvoltage of 1.1V
187 Ubd -= 1.1;
188
189 // Correct breakdown voltage for temperature dependence
190 Ubd += fTempOffset;
191
192 // Number of G-APDs in this patch
193 const int N = hv.group() ? 5 : 4;
194
195 // Average measured ADC value for this channel
196 const double adc = double(fCurrentsAvg[i])/fCursorCur * (5000/4096.); // [uA]
197
198 // Current through ~100Ohm measurement resistor
199 const double I8 = (adc-dI[i])*100/R8[i];
200
201 // Serial resistors (one 1kOhm at the output of the bias crate, one 1kOhm in the camera)
202 const double R4 = 2000;
203
204 // Serial resistor of the individual G-APDs
205 double R5 = 3900/N;
206
207 // This is assuming that the broken pixels have a 390 Ohm instead of 3900 Ohm serial resistor
208 if (i==66) // Pixel 830(66)
209 R5 = 300; // 2400 = 1/(3/3900 + 1/390)
210 if (i==191 || i==193) // Pixel 583(191) / Pixel 1401(193)
211 R5 = 390/1.4; // 379 = 1/(4/3900 + 1/390)
212
213 // Total resistance of branch with diode
214 const double R = R4+R5;
215
216 // Applied voltage at calibration resistors, according to
217 // biasctrl
218 const double U9 = fBiasVolt[i];
219
220 // Current through calibration resistors
221 // FIXME: Get that from biasctrl!!!
222 const double I9 = U9/R9[i];
223
224 // Current in R4/R5 branch
225 const double Iout = I8>I9 ? I8 - I9 : 0;
226
227 // Voltage drop in R4/R5 branch
228 const double Udrp = R*Iout;
229
230 // Current overvoltage
231 const double Uov = U9-Udrp-Ubd>0 ? U9-Udrp-Ubd : 0;
232
233 // The current through one G-APD is the sum divided by the number of G-APDs
234 // (assuming identical serial resistors)
235 double Iapd = Iout/N;
236
237 // This is assuming that the broken pixels have a 390 Ohm instead of 3900 Ohm serial resistor
238 // In this and the previosu case we neglect the resistance of the G-APDs, but we can make an
239 // assumption: The differential resistance depends more on the NSB than on the PDE,
240 // thus it is at least comparable for all G-APDs in the patch. In addition, although the
241 // G-APD with the 390Ohm serial resistor has the wrong voltage applied, this does not
242 // significantly influences the ohmic resistor or the G-APD because the differential
243 // resistor is large enough that the increase of the overvoltage does not dramatically
244 // increase the current flow as compared to the total current flow.
245 if (i==66)
246 Iapd *= 1.3;
247 if (i==191 || i==193)
248 Iapd *= 1.4;
249
250 // If the G-APD voltage is above the breakdown voltage we have the current through the
251 // G-APD and the over-voltage applied to the G-APD to calculate its differential resistor.
252 if (Iapd>0)
253 {
254 // The differential resistance of the G-APD, i.e. the dependence of the
255 // current above the breakdown voltage, is given by
256 const double Rapd = Uov/Iapd;
257
258 // This allows us to estimate the current Iov at the overvoltage we want to apply
259 const double Iov = (1.1+fBiasOffset)/Rapd;
260
261 // Estimate set point for over-voltage
262 const double Uset = (1.1+fBiasOffset) + Ubd + R*Iov*N;
263
264 // Voltage set point as a difference between breakdown voltage and set point
265 Uoff[i] = Uset - fBiasVolt[i];
266 }
267
268 // Calculate statistics only for channels with a valid calibration
269 if (Uov>0)
270 {
271 const int g = hv.group();
272
273 med[g][num[g]] = Uov;
274 avg[g] += Uov;
275 num[g]++;
276
277 if (Uov<min[g])
278 min[g] = Uov;
279 if (Uov>max[g])
280 max[g] = Uov;
281 }
282 }
283
284 sort(med[0].begin(), med[0].begin()+num[0]);
285 sort(med[1].begin(), med[1].begin()+num[1]);
286
287 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
288 fCursorCur = 0;
289 }
290
291 fDimDeviation.setQuality(fControlType);
292 fDimDeviation.Update(vec);
293
294 // Warning: Here it is assumed that the ramp up and down is done properly
295 // within the time between two new temperatures and that the calibration
296 // is finished within that time.
297 if (GetCurrentState()!=Feedback::State::kCalibrating ||
298 fDimBias.state()!=BIAS::State::kVoltageOff ||
299 fCursorTemp!=1 || !fOutputEnabled)
300 {
301 if (!fOutputEnabled || fDimBias.state()!=BIAS::State::kVoltageOn)
302 return GetCurrentState();
303
304 // Trigger calibration
305 if (GetCurrentState()==Feedback::State::kCalibrating && fCursorTemp==2)
306 {
307 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
308 return GetCurrentState();
309 }
310 }
311
312 ostringstream msg;
313 msg << setprecision(4) << "Sending new absolute offset (" << fAppliedOffset << "V+" << (num[0]+num[1]>0?(avg[0]+avg[1])/(num[0]+num[1]):0) << "V) to biasctrl.";
314 Info(msg);
315
316 if (fControlType==kCurrents && num[0]>0 && num[1]>0)
317 {
318 msg.str("");
319 msg << " Avg0=" << setw(7) << avg[0]/num[0] << " | Avg1=" << setw(7) << avg[1]/num[1];
320 Debug(msg);
321
322 msg.str("");
323 msg << " Med0=" << setw(7) << med[0][num[0]/2] << " | Med1=" << setw(7) << med[1][num[1]/2];
324 Debug(msg);
325
326 msg.str("");
327 msg << " Min0=" << setw(7) << min[0] << " | Min1=" << setw(7) << min[1];
328 Debug(msg);
329
330 msg.str("");
331 msg << " Max0=" << setw(7) << max[0] << " | Max1=" << setw(7) << max[1];
332 Debug(msg);
333 }
334
335 DimClient::sendCommandNB("BIAS_CONTROL/SET_ALL_CHANNELS_OFFSET",
336 vec.data()+BIAS::kNumChannels, BIAS::kNumChannels*sizeof(float));
337
338 return GetCurrentState();
339 }
340
341 int HandleCurrentControl()
342 {
343 const double dUt = fTempOffset; // [V]
344
345 if (GetCurrentState()==Feedback::State::kCalibrating && fBiasOffset>dUt-1.2)
346 {
347 fCursorTemp = 0;
348
349 ostringstream msg;
350 msg << " (applied calibration offset " << fBiasOffset << "V exceeds temperature correction " << fTempOffset << "V - 1.2V.";
351 Warn("Trying to calibrate above G-APD breakdown volatge!");
352 Warn(msg);
353 return GetCurrentState();
354 }
355
356 // FIXME: If calibrating do not wait for the temperature!
357 fAppliedOffset = fBiasOffset;
358 if (GetCurrentState()!=Feedback::State::kCalibrating)
359 fAppliedOffset += dUt;
360
361 vector<float> vec(2*BIAS::kNumChannels+2);
362 for (int i=0; i<BIAS::kNumChannels; i++)
363 vec[i+BIAS::kNumChannels] = fAppliedOffset;
364
365 vec[BIAS::kNumChannels*2] = dUt;
366 vec[BIAS::kNumChannels*2+1] = fBiasOffset;
367
368 double avg[2] = { 0, 0 };
369 double min[2] = { 90, 90 };
370 double max[2] = { -90, -90 };
371 int num[2] = { 0, 0 };
372
373 vector<double> med[2];
374 med[0].resize(416);
375 med[1].resize(416);
376
377 if (fControlType==kCurrents)
378 {
379 if (fCursorCur==0)
380 {
381 //DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
382 return GetCurrentState();
383 }
384
385 // Pixel 583: 5 31 == 191 (5) C2 B3 P3
386 // Pixel 830: 2 2 == 66 (4) C0 B8 P1
387 // Pixel 1401: 6 1 == 193 (5) C2 B4 P0
388
389 // Convert from DAC counts to uA
390 const double conv = 5000./4096;
391
392 // 3900 Ohm/n + 1000 Ohm + 1100 Ohm (with n=4 or n=5)
393 const double R[2] = { 3075, 2870 };
394
395 const float *Iavg = fCalibration.data(); // Offset at U=fCalibrationOffset
396 const float *Ravg = fCalibration.data()+BIAS::kNumChannels*2; // Measured resistance
397
398 // U0 = fCalibrationOffset
399 // dT = fAppliedVoltage
400
401 // Ifeedback = Im[i] - (U[i]-U0)/Ravg[i] - Iavg[i];
402 // dUapplied[i] + dUneu[i] = R[g] * (Im[i] - (dUapplied[i]+dUneu[i]-U0+dT)/Ravg[i] - Iavg[i])
403
404 // The assumption here is that the offset calculated from the temperature
405 // does not significanly change within a single step
406
407 // dU[i] := dUtotal[i] = dUapplied[i] + dUneu[i]
408 // dU[i] / R[g] = Im[i] - (dU[i]+dT-U0)/Ravg[i] - Iavg[i]
409 // dU[i]/R[g] + dU[i]/Ravg[i] = Im[i] + U0/Ravg[i] - dT/Ravg[i] - Iavg[i]
410 // dU[i]*(1/R[g]+1/Ravg[i]) = Im[i] - Iavg[i] + U0/Ravg[i] - dT/Ravg[i]
411 // dU[i] = (Im[i] - Iavg[i] + U0/Ravg[i] - dT/Ravg[i]) / (1/R[g]+1/Ravg[i])
412 // dU[i] = { Im[i] - Iavg[i] + (U0-dT)/Ravg[i] } * r with r := 1 / (1/R[g]+1/Ravg[i])
413
414 const double U0 = fAppliedOffset-fCalibrationOffset;
415
416 for (int i=0; i<BIAS::kNumChannels; i++)
417 {
418 const PixelMapEntry &hv = fMap.hv(i);
419 if (!hv)
420 continue;
421
422 // Average measured current
423 const double Im = double(fCurrentsAvg[i])/fCursorCur * conv; // [uA]
424
425 // Group index (0 or 1) of the of the pixel (4 or 5 pixel patch)
426 const int g = hv.group();
427
428 // Serial resistors in front of the G-APD
429 double Rg = R[g];
430
431 // This is assuming that the broken pixels have a 390 Ohm instead of 3900 Ohm serial resistor
432 if (i==66) // Pixel 830(66)
433 Rg = 2400; // 2400 = (3/3900 + 1/390) + 1000 + 1100
434 if (i==191 || i==193) // Pixel 583(191) / Pixel 1401(193)
435 Rg = 2379; // 2379 = (4/3900 + 1/390) + 1000 + 1100
436
437 const double r = 1./(1./Rg + 1./Ravg[i]); // [Ohm]
438
439 // Offset induced by the voltage above the calibration point
440 const double dI = U0/Ravg[i]; // [V/Ohm]
441
442 // Offset at the calibration point (make sure that the calibration is
443 // valid (Im[i]>Iavg[i]) and we operate above the calibration point)
444 const double I = Im>Iavg[i] ? Im - Iavg[i] : 0; // [A]
445
446 // Make sure that the averaged resistor is valid
447 const double dU = Ravg[i]>10000 ? r*(I*1e-6 - dI) : 0;
448
449 vec[i+BIAS::kNumChannels] += dU;
450
451 // Angelegte Spannung: U0+dU
452 // Gemessener Strom: Im - Iavg
453 // Strom offset: (U0+dU) / Ravg
454 // Fliessender Strom: Im-Iavg - (U0+dU)/Ravg
455 // Korrektur: [ Im-Iavg - (U0+dU)/Ravg ] * Rg
456
457 // Aufgeloest nach dU: dU = ( Im-Iavg - dU/Ravg ) / ( 1/Rg + 1/Ravg )
458 // Equivalent zu: dU = ( I*Ravg - U0 ) / ( Ravg/Rg+1 )
459
460 // Calculate statistics only for channels with a valid calibration
461 if (Iavg[i]>0)
462 {
463 med[g][num[g]] = dU;
464 avg[g] += dU;
465 num[g]++;
466
467 if (dU<min[g])
468 min[g] = dU;
469 if (dU>max[g])
470 max[g] = dU;
471 }
472 }
473
474 sort(med[0].begin(), med[0].begin()+num[0]);
475 sort(med[1].begin(), med[1].begin()+num[1]);
476
477 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
478 fCursorCur = 0;
479 }
480
481 fDimDeviation.setQuality(fControlType);
482 fDimDeviation.Update(vec);
483
484 // Warning: Here it is assumed that the ramp up and down is done properly
485 // within the time between two new temperatures and that the calibration
486 // is finished within that time.
487 if (!(GetCurrentState()==Feedback::State::kCalibrating && fCursorTemp==1 && fOutputEnabled && fDimBias.state()==BIAS::State::kVoltageOff))
488 {
489 if (!fOutputEnabled || fDimBias.state()!=BIAS::State::kVoltageOn)
490 return GetCurrentState();
491
492 // Trigger calibration
493 if (GetCurrentState()==Feedback::State::kCalibrating && fCursorTemp==2)
494 {
495 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
496 return GetCurrentState();
497 }
498 }
499
500 ostringstream msg;
501 msg << setprecision(4) << "Sending new absolute offset (" << fAppliedOffset << "V+" << (num[0]+num[1]>0?(avg[0]+avg[1])/(num[0]+num[1]):0) << "V) to biasctrl.";
502 Info(msg);
503
504 if (fControlType==kCurrents && num[0]>0 && num[1]>0)
505 {
506 msg.str("");
507 msg << " Avg0=" << setw(7) << avg[0]/num[0] << " | Avg1=" << setw(7) << avg[1]/num[1];
508 Debug(msg);
509
510 msg.str("");
511 msg << " Med0=" << setw(7) << med[0][num[0]/2] << " | Med1=" << setw(7) << med[1][num[1]/2];
512 Debug(msg);
513
514 msg.str("");
515 msg << " Min0=" << setw(7) << min[0] << " | Min1=" << setw(7) << min[1];
516 Debug(msg);
517
518 msg.str("");
519 msg << " Max0=" << setw(7) << max[0] << " | Max1=" << setw(7) << max[1];
520 Debug(msg);
521 }
522
523 DimClient::sendCommandNB("BIAS_CONTROL/SET_ALL_CHANNELS_OFFSET",
524 vec.data()+BIAS::kNumChannels, BIAS::kNumChannels*sizeof(float));
525
526 return GetCurrentState();
527 }
528
529 int AverageCurrents(const EventImp &evt)
530 {
531 if (evt.GetSize()!=BIAS::kNumChannels*sizeof(int16_t))
532 return -1;
533
534 if (fDimBias.state()!=BIAS::State::kVoltageOn)
535 return false;
536
537 if (fCursorCur++<0)
538 return true;
539
540 const int16_t *ptr = evt.Ptr<int16_t>();
541
542 for (int i=0; i<BIAS::kNumChannels; i++)
543 {
544 fCurrentsAvg[i] += ptr[i];
545 fCurrentsRms[i] += ptr[i]*ptr[i];
546 }
547
548 return true;
549 }
550
551
552 void HandleCalibration(const EventImp &evt)
553 {
554 const int rc = AverageCurrents(evt);
555 if (rc<0)
556 return;
557
558 if (fCursorCur<fNumCalibRequests)
559 {
560 if (fDimBias.state()==BIAS::State::kVoltageOn)
561 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
562 return;
563 }
564
565 if (rc==0)
566 return;
567
568 fCalibration.resize(BIAS::kNumChannels*3);
569
570 float *avg = fCalibration.data();
571 float *rms = fCalibration.data()+BIAS::kNumChannels;
572 float *res = fCalibration.data()+BIAS::kNumChannels*2;
573
574 const double conv = 5000./4096;
575
576 for (int i=0; i<BIAS::kNumChannels; i++)
577 {
578 const double I = double(fCurrentsAvg[i])/fCursorCur;
579
580 res[i] = (fVoltGapd[i]+fCalibrationOffset)/I / conv * 1e6;
581 avg[i] = conv * I;
582 rms[i] = conv * sqrt(double(fCurrentsRms[i])/fCursorCur-I*I);
583 }
584
585 fCalibTime = Time();
586
587 fDimCalibration.setData(fCalibration);
588 fDimCalibration.Update(fCalibTime);
589
590 fOutputEnabled = false;
591 fControlType = kIdle;
592
593 Info("Calibration successfully done.");
594
595 if (fDimBias.state()==BIAS::State::kVoltageOn)
596 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
597 }
598
599 void HandleFeedback(const EventImp &evt)
600 {
601 if (evt.GetSize()!=1440*sizeof(float))
602 return;
603
604 // -------- Check age of last stored event --------
605
606 const Time tm(evt.GetTime());
607
608 if (Time()-fBiasLast>boost::posix_time::seconds(30))
609 {
610 Warn("Last received event data older than 30s... resetting average calculation.");
611 ResetData();
612 }
613 fBiasLast = tm;
614
615 // -------- Store new event --------
616
617 fData[fCursorAmpl%fData.size()].assign(evt.Ptr<float>(), evt.Ptr<float>()+1440);
618 if (++fCursorAmpl<fData.size())
619 return;
620
621 // -------- Calculate statistics --------
622
623 valarray<double> med(1440);
624
625 for (int ch=0; ch<1440; ch++)
626 {
627 vector<float> arr(fData.size());
628 for (size_t i=0; i<fData.size(); i++)
629 arr[i] = fData[i][ch];
630
631 sort(arr.begin(), arr.end());
632
633 med[ch] = arr[arr.size()/2];
634 }
635
636 /*
637 vector<float> med(1440);
638 vector<float> rms(1440);
639 for (size_t i=0; i<fData.size(); i++)
640 {
641 if (fData[i].size()==0)
642 return;
643
644 for (int j=0; j<1440; j++)
645 {
646 med[j] += fData[i][j];
647 rms[j] += fData[i][j]*fData[i][j];
648 }
649 }
650 */
651
652 vector<double> avg(BIAS::kNumChannels);
653 vector<int> num(BIAS::kNumChannels);
654 for (int i=0; i<1440; i++)
655 {
656 const PixelMapEntry &ch = fMap.hw(i);
657
658 // FIXME: Add a consistency check if the median makes sense...
659 // FIXME: Add a consistency check to remove pixels with bright stars (median?)
660
661 avg[ch.hv()] += med[i];
662 num[ch.hv()]++;
663 }
664
665 for (int i=0; i<BIAS::kNumChannels; i++)
666 {
667 if (num[i])
668 avg[i] /= num[i];
669
670 }
671
672 // -------- Calculate correction --------
673
674 // http://bestune.50megs.com/typeABC.htm
675
676 // CO: Controller output
677 // PV: Process variable
678 // SP: Set point
679 // T: Sampling period (loop update period)
680 // e = SP - PV
681 //
682 // Kp : No units
683 // Ki : per seconds
684 // Kd : seconds
685
686 // CO(k)-CO(k-1) = - Kp[ PV(k) - PV(k-1) ] + Ki * T * (SP(k)-PV(k)) - Kd/T [ PV(k) - 2PV(k-1) + PV(k-2) ]
687
688 if (fCursorAmpl%fData.size()>0)
689 return;
690
691 // FIXME: Take out broken / dead boards.
692
693 const Time tm0 = Time();
694
695 /*const*/ double T21 = fT>0 ? fT : (tm0-fStartTime).total_microseconds()/1000000.;
696 const double T10 = fT21;
697 fT21 = T21;
698
699 fStartTime = tm0;
700
701 ostringstream out;
702 out << "New " << fData.size() << " event received: " << fCursorAmpl << " / " << setprecision(3) << T21 << "s";
703 Info(out);
704
705 if (fPV[0].size()==0)
706 {
707 fPV[0].resize(avg.size());
708 fPV[0] = valarray<double>(avg.data(), avg.size());
709 return;
710 }
711
712 if (fPV[1].size()==0)
713 {
714 fPV[1].resize(avg.size());
715 fPV[1] = valarray<double>(avg.data(), avg.size());
716 return;
717 }
718
719 if (fPV[2].size()==0)
720 {
721 fPV[2].resize(avg.size());
722 fPV[2] = valarray<double>(avg.data(), avg.size());
723 return;
724 }
725
726 fPV[0] = fPV[1];
727 fPV[1] = fPV[2];
728
729 fPV[2].resize(avg.size());
730 fPV[2] = valarray<double>(avg.data(), avg.size());
731
732 if (T10<=0 || T21<=0)
733 return;
734
735 //cout << "Calculating (" << fCursor << ":" << T21 << ")... " << endl;
736
737 // fKi[j] = response[j]*gain;
738 // Kp = 0;
739 // Kd = 0;
740
741 // => Kp = 0.01 * gain = 0.00005
742 // => Ki = 0.8 * gain/20s = 0.00025
743 // => Kd = 0.1 * gain/20s = 0.00003
744
745 /*
746 fKp = 0;
747 fKd = 0;
748 fKi = 0.00003*20;
749 T21 = 1;
750 */
751
752 //valarray<double> correction = - Kp*(PV[2] - PV[1]) + Ki * dT * (SP-PV[2]) - Kd/dT * (PV[2] - 2*PV[1] + PV[0]);
753 //valarray<double> correction =
754 // - Kp * (PV[2] - PV[1])
755 // + dT * Ki * (SP - PV[2])
756 // - Kd / dT * (PV[2] - 2*PV[1] + PV[0]);
757 //
758 // - (Kp+Kd/dT1) * (PV[2] - PV[1])
759 // + dT2 * Ki * (SP - PV[2])
760 // + Kd / dT1 * (PV[1] - PV[0]);
761 //
762 // - Kp * (PV[2] - PV[1])
763 // + Ki * (SP - PV[2])*dT
764 // - Kd * (PV[2] - PV[1])/dT
765 // + Kd * (PV[1] - PV[0])/dT;
766 //
767 //valarray<double> correction =
768 // - Kp*(PV[2] - PV[1]) + Ki * T21 * (SP-PV[2]) - Kd*(PV[2]-PV[1])/T21 - Kd*(PV[0]-PV[1])/T01;
769 const valarray<double> correction = 1./fGain/1000*
770 (
771 - (fKp+fKd/T21)*(fPV[2] - fPV[1])
772 + fKi*T21*(fSP-fPV[2])
773 + fKd/T10*(fPV[1]-fPV[0])
774 );
775
776 /*
777 integral = 0
778 start:
779 integral += (fSP - fPV[2])*dt
780
781 output = Kp*(fSP - fPV[2]) + Ki*integral - Kd*(fPV[2] - fPV[1])/dt
782
783 wait(dt)
784
785 goto start
786 */
787
788 vector<float> vec(2*BIAS::kNumChannels+2);
789 for (int i=0; i<BIAS::kNumChannels; i++)
790 vec[i] = fPV[2][i]-fSP[i];
791
792 for (int i=0; i<BIAS::kNumChannels; i++)
793 vec[i+BIAS::kNumChannels] = avg[i]<5*2.5 ? 0 : correction[i];
794
795 fDimDeviation.setQuality(fControlType);
796 fDimDeviation.Update(vec);
797
798 if (!fOutputEnabled || fDimBias.state()!=BIAS::State::kVoltageOn)
799 return;
800
801 Info("Sending new relative offset to biasctrl.");
802
803 DimClient::sendCommandNB("BIAS_CONTROL/INCREASE_ALL_CHANNELS_VOLTAGE",
804 vec.data()+BIAS::kNumChannels, BIAS::kNumChannels*sizeof(float));
805 }
806
807 void HandleGlobalFeedback(const EventImp &evt)
808 {
809 if (evt.GetSize()!=1440*sizeof(float))
810 return;
811
812 // -------- Store new event --------
813
814 vector<float> arr(evt.Ptr<float>(), evt.Ptr<float>()+1440);
815
816 sort(arr.begin(), arr.end());
817
818 const float med = arr[arr.size()/2];
819
820 fData[fCursorAmpl%fData.size()].resize(1); //assign(&med, &med);
821 fData[fCursorAmpl%fData.size()][0] = med; //assign(&med, &med);
822
823 if (++fCursorAmpl<fData.size())
824 return;
825
826 // -------- Calculate statistics --------
827
828 double avg=0;
829 double rms=0;
830 for (size_t i=0; i<fData.size(); i++)
831 {
832 avg += fData[i][0];
833 rms += fData[i][0]*fData[i][0];
834 }
835
836 avg /= fData.size();
837 rms /= fData.size();
838
839 rms = sqrt(rms-avg*avg);
840
841 // -------- Calculate correction --------
842
843 if (fCursorAmpl%fData.size()!=0)
844 return;
845
846 Out() << "Amplitude: " << avg << " +- " << rms << endl;
847
848 // FIXME: Take out broken / dead boards.
849
850 /*
851 ostringstream out;
852 out << "New " << fData.size() << " event received: " << fCursor << " / " << setprecision(3) << T21 << "s";
853 Info(out);
854 */
855
856 if (fPV[0].size()==0)
857 {
858 fPV[0].resize(1);
859 fPV[0] = valarray<double>(&avg, 1);
860 return;
861 }
862
863 if (fPV[1].size()==0)
864 {
865 fPV[1].resize(1);
866 fPV[1] = valarray<double>(&avg, 1);
867 return;
868 }
869
870 if (fPV[2].size()==0)
871 {
872 fPV[2].resize(1);
873 fPV[2] = valarray<double>(&avg, 1);
874 return;
875 }
876
877 fPV[0] = fPV[1];
878 fPV[1] = fPV[2];
879
880 fPV[2].resize(1);
881 fPV[2] = valarray<double>(&avg, 1);
882
883 // ----- Calculate average currents -----
884
885 vector<float> A(BIAS::kNumChannels);
886 for (int i=0; i<BIAS::kNumChannels; i++)
887 A[i] = double(fCurrentsAvg[i]) / fCursorCur;
888
889 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
890 fCursorCur = 0;
891
892 // -------- Calculate correction --------
893
894 // correction = (fSP[0]-fPV[2])*fKi
895 /*
896 const double T21 = 1; // feedback is 1s
897 const double T10 = 1; // feedback is 20s
898
899 const valarray<double> correction = 1./fGain/1000*
900 (
901 - (fKp+fKd/T21)*(fPV[2] - fPV[1])
902 + fKi*T21*(fSP[0]-fPV[2])
903 + fKd/T10*(fPV[1]-fPV[0])
904 );
905 */
906
907 // pow of 1.6 comes from the non-linearity of the
908 // amplitude vs bias voltage
909 const valarray<double> correction = 1./fGain/1000*
910 (
911 //fKi*(pow(fSP[0], 1./1.6)-pow(fPV[2], 1./1.6))
912 fKi*(fSP[0]-fPV[2])
913 );
914
915 Out() << "Correction: " << correction[0] << "V (" << fSP[0] << ")" << endl;
916
917 const int nch = BIAS::kNumChannels;
918
919 // FIXME: Sanity check!
920
921 vector<float> vec;
922 vec.reserve(2*nch+2);
923 vec.insert(vec.begin(), nch, fPV[2][0]-fSP[0]);
924 vec.insert(vec.begin()+nch, nch, correction[0]);
925 vec.push_back(0);
926 vec.push_back(0);
927
928 fDimDeviation.setQuality(fControlType);
929 fDimDeviation.Update(vec);
930
931 if (!fOutputEnabled || fDimBias.state()!=BIAS::State::kVoltageOn)
932 return;
933
934 Info("Sending new global relative offset to biasctrl.");
935
936 DimClient::sendCommandNB("BIAS_CONTROL/INCREASE_ALL_CHANNELS_VOLTAGE",
937 vec.data()+BIAS::kNumChannels, BIAS::kNumChannels*sizeof(float));
938 }
939
940 void HandleCalibrateCurrents(const EventImp &evt)
941 {
942 if (fBiasVolt.empty() || fCalibration.empty() || evt.GetSize()<416*sizeof(int16_t))
943 return;
944
945 struct dim_data {
946 float I[416];
947 float Iavg;
948 float Irms;
949 float Imed;
950 float Idev;
951 uint32_t N;
952 float Tdiff;
953
954 dim_data() { memset(this, 0, sizeof(dim_data)); }
955 } __attribute__((__packed__));
956
957 const int16_t *I = evt.Ptr<int16_t>();
958 const float *R = fCalibration.data()+BIAS::kNumChannels*2;
959 const float *U = fBiasVolt.data();
960
961 vector<float> med(416);
962 uint16_t cnt = 0;
963
964 double avg = 0;
965 double rms = 0;
966
967 dim_data data;
968 for (int i=0; i<416; i++)
969 {
970 const PixelMapEntry &hv = fMap.hv(i);
971 if (!hv)
972 continue;
973
974 if (R[i]<=0)
975 continue;
976
977 data.I[i] = I[i]*5000./4096 - U[i]/R[i]*1e6;
978 data.I[i] /= hv.group() ? 5 : 4;
979
980 avg += data.I[i];
981 rms += data.I[i]*data.I[i];
982
983 if (i>=320)
984 continue;
985
986 med[cnt++] = data.I[i];
987 }
988
989 if (cnt==0)
990 return;
991
992 avg /= cnt;
993 rms /= cnt;
994
995 data.N = cnt;
996 data.Iavg = avg;
997 data.Irms = sqrt(rms-avg*avg);
998
999 sort(med.data(), med.data()+cnt);
1000
1001 data.Imed = cnt%2 ? (med[cnt/2-1]+med[cnt/2])/2 : med[cnt/2];
1002
1003 for (int i=0; i<cnt; i++)
1004 med[i] = fabs(med[i]-data.Imed);
1005
1006 sort(med.data(), med.data()+cnt);
1007
1008 data.Idev = med[uint32_t(0.682689477208650697*cnt)];
1009
1010 data.Tdiff = evt.GetTime().UnixTime()-fCalibTime.UnixTime();
1011
1012 fDimCurrents.setData(&data, sizeof(dim_data));
1013 fDimCurrents.Update(evt.GetTime());
1014 }
1015
1016 int HandleBiasCurrent(const EventImp &evt)
1017 {
1018 if (fControlType==kTemp && GetCurrentState()==Feedback::State::kCalibrating)
1019 HandleCalibration(evt);
1020
1021 if (fControlType==kFeedbackGlobal || fControlType==kCurrents || fControlType==kCurrentsNew)
1022 AverageCurrents(evt);
1023
1024 /*
1025 if (fControlType==kCurrents && fCursorTemp>0 && fCursorCur>0)
1026 {
1027 // fCursorTemp: 1 2 3 4 5 6 7 8
1028 // fCursor%x: 1 1 1 2 2 2 3 3 // 9 steps in ~15s
1029 //if (fCursorTemp<3 && fCursorCur%(fCursorTemp/3+1)==0)
1030 HandleCurrentControl();
1031 }*/
1032
1033 HandleCalibrateCurrents(evt);
1034
1035 return GetCurrentState();
1036 }
1037
1038 int HandleBiasData(const EventImp &evt)
1039 {
1040 if (fControlType==kFeedback)
1041 HandleFeedback(evt);
1042
1043 if (fControlType==kFeedbackGlobal)
1044 HandleGlobalFeedback(evt);
1045
1046 return GetCurrentState();
1047 }
1048
1049 int HandleBiasNom(const EventImp &evt)
1050 {
1051 if (evt.GetSize()>=416*sizeof(float))
1052 {
1053 fVoltGapd.assign(evt.Ptr<float>(), evt.Ptr<float>()+416);
1054 Info("Nominal bias voltages received.");
1055 }
1056
1057 return GetCurrentState();
1058 }
1059
1060 int HandleBiasVoltage(const EventImp &evt)
1061 {
1062 if (evt.GetSize()>=416*sizeof(float))
1063 fBiasVolt.assign(evt.Ptr<float>(), evt.Ptr<float>()+416);
1064 return GetCurrentState();
1065 }
1066
1067 bool CheckEventSize(size_t has, const char *name, size_t size)
1068 {
1069 if (has==size)
1070 return true;
1071
1072 ostringstream msg;
1073 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
1074 Fatal(msg);
1075 return false;
1076 }
1077
1078 int Print() const
1079 {
1080 Out() << fDim << endl;
1081 Out() << fDimFAD << endl;
1082 Out() << fDimFSC << endl;
1083 Out() << fDimBias << endl;
1084
1085 return GetCurrentState();
1086 }
1087
1088 int PrintCalibration()
1089 {
1090 if (fCalibration.empty())
1091 {
1092 Out() << "No calibration performed so far." << endl;
1093 return GetCurrentState();
1094 }
1095
1096 const float *avg = fCalibration.data();
1097 const float *rms = fCalibration.data()+BIAS::kNumChannels;
1098 const float *res = fCalibration.data()+BIAS::kNumChannels*2;
1099
1100 Out() << "Average current at " << fCalibrationOffset << "V below G-APD operation voltage:\n";
1101
1102 for (int k=0; k<13; k++)
1103 for (int j=0; j<8; j++)
1104 {
1105 Out() << setw(2) << k << "|" << setw(2) << j*4 << "|";
1106 for (int i=0; i<4; i++)
1107 Out() << Tools::Form(" %6.1f+-%4.1f", avg[k*32+j*4+i], rms[k*32+j*4+i]);
1108 Out() << '\n';
1109 }
1110 Out() << '\n';
1111
1112 Out() << "Measured calibration resistor:\n";
1113 for (int k=0; k<13; k++)
1114 for (int j=0; j<4; j++)
1115 {
1116 Out() << setw(2) << k << "|" << setw(2) << j*8 << "|";
1117 for (int i=0; i<8; i++)
1118 Out() << Tools::Form(" %5.0f", res[k*32+j*8+i]);
1119 Out() << '\n';
1120 }
1121
1122 Out() << flush;
1123
1124 return GetCurrentState();
1125 }
1126
1127 void WarnState(bool needfsc, bool needfad)
1128 {
1129 const bool bias = fDimBias.state() >= BIAS::State::kConnecting;
1130 const bool fsc = fDimFSC.state() >= FSC::State::kConnected;
1131 const bool fad = fDimFAD.state() >= FAD::State::kConnected;
1132
1133 if (!bias)
1134 Warn("Bias control not yet ready.");
1135 if (needfsc && !fsc)
1136 Warn("FSC control not yet ready.");
1137 if (needfad && !fad)
1138 Warn("FAD control not yet ready.");
1139 }
1140
1141 int SetConstant(const EventImp &evt, int constant)
1142 {
1143 if (!CheckEventSize(evt.GetSize(), "SetConstant", 8))
1144 return kSM_FatalError;
1145
1146 switch (constant)
1147 {
1148 case 0: fKi = evt.GetDouble(); break;
1149 case 1: fKp = evt.GetDouble(); break;
1150 case 2: fKd = evt.GetDouble(); break;
1151 case 3: fT = evt.GetDouble(); break;
1152 case 4: fGain = evt.GetDouble(); break;
1153 default:
1154 Fatal("SetConstant got an unexpected constant id -- this is a program bug!");
1155 return kSM_FatalError;
1156 }
1157
1158 return GetCurrentState();
1159 }
1160
1161 int EnableOutput(const EventImp &evt)
1162 {
1163 if (!CheckEventSize(evt.GetSize(), "EnableOutput", 1))
1164 return kSM_FatalError;
1165
1166 fOutputEnabled = evt.GetBool();
1167
1168 if (fControlType==kCurrents || fControlType==kCurrentsNew)
1169 if (fCursorTemp>1)
1170 fCursorTemp = 1;
1171
1172 return GetCurrentState();
1173 }
1174
1175 void ResetData(int16_t n=-1)
1176 {
1177 fData.assign(n>0 ? n : fData.size(), vector<float>(0));
1178
1179 fCursorAmpl = 0;
1180 fCursorCur = 0;
1181 fCursorTemp = 0;
1182
1183 fStartTime = Time();
1184
1185 fSP = valarray<double>(0., BIAS::kNumChannels);
1186
1187 vector<float> vec(2*BIAS::kNumChannels+2, fBiasOffset);
1188 vec[2*BIAS::kNumChannels] = 0;
1189 fDimDeviation.setQuality(kIdle);
1190 fDimDeviation.Update(vec);
1191
1192 fPV[0].resize(0);
1193 fPV[1].resize(0);
1194 fPV[2].resize(0);
1195
1196 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
1197 fCurrentsRms.assign(BIAS::kNumChannels, 0);
1198
1199 if (fKp==0 && fKi==0 && fKd==0)
1200 Warn("Control loop parameters are all set to zero.");
1201 }
1202
1203 int StartFeedback(const EventImp &evt)
1204 {
1205 if (!CheckEventSize(evt.GetSize(), "StartFeedback", 2))
1206 return kSM_FatalError;
1207
1208 WarnState(false, true);
1209
1210 fBiasOffset = 0;
1211 ResetData(evt.GetShort());
1212
1213 fControlType = kFeedback;
1214
1215 return GetCurrentState();
1216 }
1217
1218 int StartFeedbackGlobal(const EventImp &evt)
1219 {
1220 if (!CheckEventSize(evt.GetSize(), "StartFeedbackGlobal", 2))
1221 return kSM_FatalError;
1222
1223 WarnState(false, true);
1224
1225 fBiasOffset = 0;
1226 ResetData(evt.GetShort());
1227
1228 fControlType = kFeedbackGlobal;
1229
1230 return GetCurrentState();
1231 }
1232
1233 int StartTempCtrl(const EventImp &evt)
1234 {
1235 if (!CheckEventSize(evt.GetSize(), "StartTempCtrl", 4))
1236 return kSM_FatalError;
1237
1238 WarnState(true, false);
1239
1240 fBiasOffset = evt.GetFloat();
1241 fControlType = kTemp;
1242
1243 ostringstream out;
1244 out << "Starting temperature feedback with an offset of " << fBiasOffset << "V";
1245 Message(out);
1246
1247 if (fDimBias.state()==BIAS::State::kVoltageOn)
1248 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
1249
1250 return GetCurrentState();
1251 }
1252
1253 int StartCurrentCtrl(const EventImp &evt)
1254 {
1255 if (!CheckEventSize(evt.GetSize(), "StartCurrentCtrl", 4))
1256 return kSM_FatalError;
1257
1258 if (fCalibration.empty())
1259 {
1260 Warn("Current control needs a bias crate calibration first... command ignored.");
1261 return GetCurrentState();
1262 }
1263
1264 WarnState(true, false);
1265
1266 fBiasOffset = evt.GetFloat();
1267 fTempOffset = -3;
1268 ResetData(0);
1269 fControlType = kCurrents;
1270
1271 ostringstream out;
1272 out << "Starting current/temp feedback with an offset of " << fBiasOffset << "V";
1273 Message(out);
1274
1275 return GetCurrentState();
1276 }
1277
1278 int StartNewCurrentCtrl(const EventImp &evt)
1279 {
1280 if (!CheckEventSize(evt.GetSize(), "StartNewCurrentCtrl", 4))
1281 return kSM_FatalError;
1282
1283 if (fCalibration.empty())
1284 {
1285 Warn("Current control needs a bias crate calibration first... command ignored.");
1286 return GetCurrentState();
1287 }
1288
1289 WarnState(true, false);
1290
1291 fBiasOffset = evt.GetFloat();
1292 fTempOffset = -3;
1293 ResetData(0);
1294 fControlType = kCurrentsNew;
1295
1296 ostringstream out;
1297 out << "Starting new current/temp feedback with an offset of " << fBiasOffset << "V";
1298 Message(out);
1299
1300 return GetCurrentState();
1301 }
1302
1303 int StopFeedback()
1304 {
1305 fControlType = kIdle;
1306
1307 return GetCurrentState();
1308 }
1309
1310 int StoreReference()
1311 {
1312 if (!fPV[0].size() && !fPV[1].size() && !fPV[2].size())
1313 {
1314 Warn("No values in memory. Take enough events first!");
1315 return GetCurrentState();
1316 }
1317
1318 // FIXME: Check age
1319
1320 if (!fPV[1].size() && !fPV[2].size())
1321 fSP = fPV[0];
1322
1323 if (!fPV[2].size())
1324 fSP = fPV[1];
1325 else
1326 fSP = fPV[2];
1327
1328 vector<float> vec(BIAS::kNumChannels);
1329 for (int i=0; i<BIAS::kNumChannels; i++)
1330 vec[i] = fSP[i];
1331 fDimReference.Update(vec);
1332
1333 return GetCurrentState();
1334 }
1335
1336 int SetReference(const EventImp &evt)
1337 {
1338 if (!CheckEventSize(evt.GetSize(), "SetReference", 4))
1339 return kSM_FatalError;
1340
1341 const float val = evt.GetFloat();
1342 /*
1343 if (!fPV[0].size() && !fPV[1].size() && !fPV[2].size())
1344 {
1345 Warn("No values in memory. Take enough events first!");
1346 return GetCurrentState();
1347 }*/
1348
1349 vector<float> vec(BIAS::kNumChannels);
1350 for (int i=0; i<BIAS::kNumChannels; i++)
1351 vec[i] = fSP[i] = val;
1352 fDimReference.Update(vec);
1353
1354 Out() << "New global reference value: " << val << "mV" << endl;
1355
1356 return GetCurrentState();
1357 }
1358
1359 int CalibrateCurrents()
1360 {
1361// if (!CheckEventSize(evt.GetSize(), "StartTempCtrl", 4))
1362// return kSM_FatalError;
1363
1364 if (fDimBias.state()==BIAS::State::kRamping)
1365 {
1366 Warn("Calibration cannot be started when biasctrl is in state Ramping.");
1367 return GetCurrentState();
1368 }
1369
1370 if (fVoltGapd.empty())
1371 {
1372 Error("No G-APD reference voltages received yet (BIAS_CONTROL/NOMINAL).");
1373 return GetCurrentState();
1374 }
1375
1376 WarnState(true, false);
1377
1378 ostringstream out;
1379 out << "Starting temperature feedback for calibration with an offset of " << fCalibrationOffset << "V";
1380 Message(out);
1381
1382 fBiasOffset = fCalibrationOffset;
1383 fControlType = kTemp;
1384 fCursorCur = -fNumCalibIgnore;
1385 fCursorTemp = 0;
1386 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
1387 fCurrentsRms.assign(BIAS::kNumChannels, 0);
1388 fCalibration.resize(0);
1389 fStartTime = Time();
1390 fOutputEnabled = true;
1391
1392 return Feedback::State::kCalibrating;
1393 }
1394
1395 int SetCurrentRequestInterval(const EventImp &evt)
1396 {
1397 if (!CheckEventSize(evt.GetSize(), "SetCurrentRequestInterval", 2))
1398 return kSM_FatalError;
1399
1400 fCurrentRequestInterval = evt.GetUShort();
1401
1402 Out() << "New current request interval: " << fCurrentRequestInterval << "ms" << endl;
1403
1404 return GetCurrentState();
1405 }
1406
1407 int Execute()
1408 {
1409 // Dispatch (execute) at most one handler from the queue. In contrary
1410 // to run_one(), it doesn't wait until a handler is available
1411 // which can be dispatched, so poll_one() might return with 0
1412 // handlers dispatched. The handlers are always dispatched/executed
1413 // synchronously, i.e. within the call to poll_one()
1414 //poll_one();
1415
1416 if (!fDim.online())
1417 return Feedback::State::kDimNetworkNA;
1418
1419 const bool bias = fDimBias.state() >= BIAS::State::kConnecting;
1420 const bool fad = fDimFAD.state() >= FAD::State::kConnected;
1421 const bool fsc = fDimFSC.state() >= FSC::State::kConnected;
1422
1423 // All subsystems are not connected
1424 if (!bias && !fad && !fsc)
1425 return Feedback::State::kDisconnected;
1426
1427 // At least one subsystem apart from bias is connected
1428 if (bias && !fad && !fsc)
1429 return Feedback::State::kConnecting;
1430
1431/*
1432 // All subsystems are connected
1433 if (GetCurrentStatus()==Feedback::State::kConfiguringStep1)
1434 {
1435 if (fCursor<1)
1436 return Feedback::State::kConfiguringStep1;
1437
1438 if (fCursor==1)
1439 {
1440 fStartTime = Time();
1441 return Feedback::State::kConfiguringStep2;
1442 }
1443 }
1444 if (GetCurrentStatus()==Feedback::State::kConfiguringStep2)
1445 {
1446 if (fCursor==1)
1447 {
1448 if ((Time()-fStartTime).total_microseconds()/1000000.<1.5)
1449 return Feedback::State::kConfiguringStep2;
1450
1451 Dim::SendCommand("BIAS_CONTROL/REQUEST_STATUS");
1452 }
1453 if (fCursor==2)
1454 {
1455
1456 int n=0;
1457 double avg = 0;
1458 for (size_t i=0; i<fCurrents.size(); i++)
1459 if (fCurrents[i]>=0)
1460 {
1461 avg += fCurrents[i];
1462 n++;
1463 }
1464
1465 cout << avg/n << endl;
1466 }
1467 return Feedback::State::kConnected;
1468 }
1469 */
1470
1471 // Needs connection of FAD and BIAS
1472 if (bias && fad)
1473 {
1474 if (fControlType==kFeedback || fControlType==kFeedbackGlobal)
1475 return fOutputEnabled ? Feedback::State::kFeedbackCtrlRunning : Feedback::State::kFeedbackCtrlIdle;
1476 }
1477
1478 // Needs connection of FSC and BIAS
1479 if (bias && fsc)
1480 {
1481 if (fControlType==kTemp)
1482 {
1483 if (GetCurrentState()==Feedback::State::kCalibrating && fCursorCur<fNumCalibRequests)
1484 return GetCurrentState();
1485
1486 return fOutputEnabled ? Feedback::State::kTempCtrlRunning : Feedback::State::kTempCtrlIdle;
1487 }
1488 if (fControlType==kCurrents || fControlType==kCurrentsNew)
1489 {
1490 static Time past;
1491 if (fCurrentRequestInterval>0 && Time()-past>boost::posix_time::milliseconds(fCurrentRequestInterval))
1492 {
1493 if (fDimBias.state()==BIAS::State::kVoltageOn)
1494 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
1495 past = Time();
1496 }
1497
1498 return fOutputEnabled && fCursorTemp>0 ? Feedback::State::kCurrentCtrlRunning : Feedback::State::kCurrentCtrlIdle;
1499 }
1500 }
1501
1502 if (bias && fad && !fsc)
1503 return Feedback::State::kConnectedFAD;
1504
1505 if (bias && fsc && !fad)
1506 return Feedback::State::kConnectedFSC;
1507
1508 return Feedback::State::kConnected;
1509 }
1510
1511public:
1512 StateMachineFeedback(ostream &out=cout) : StateMachineDim(out, "FEEDBACK"),
1513 //---
1514 fDimFAD("FAD_CONTROL"),
1515 fDimFSC("FSC_CONTROL"),
1516 fDimBias("BIAS_CONTROL"),
1517 //---
1518 fDimReference("FEEDBACK/REFERENCE", "F:416",
1519 "Amplitude reference value(s)"
1520 "Vref[mV]:Amplitude reference"),
1521 fDimDeviation("FEEDBACK/DEVIATION", "F:416;F:416;F:1;F:1",
1522 "Control loop information"
1523 "|DeltaAmpl[mV]:Amplitude offset measures"
1524 "|DeltaBias[mV]:Correction value calculated"
1525 "|DeltaTemp[mV]:Correction calculated from temperature"
1526 "|DeltaUser[mV]:Additional offset specified by user"),
1527 fDimCalibration("FEEDBACK/CALIBRATION", "F:416;F:416;F:416",
1528 "Current offsets"
1529 "|Avg[uA]:Average offset"
1530 "|Rms[uA]:Rms of offset"
1531 "|R[Ohm]:Measured calibration resistor"),
1532 fDimCurrents("FEEDBACK/CALIBRATED_CURRENTS", "F:416;F:1;F:1;F:1;F:1;I:1;F:1",
1533 "Calibrated currents"
1534 "|I[uA]:Calibrated currents"
1535 "|I_avg[uA]:Average calibrated current (320 channels)"
1536 "|I_rms[uA]:Rms of calibrated current (320 channels)"
1537 "|I_med[uA]:Median calibrated current (320 channels)"
1538 "|I_dev[uA]:Deviation of calibrated current (320 channels)"
1539 "|N[uint16]:Number of valid values"
1540 "|T_diff[s]:Time difference to calibration"),
1541 fSP(BIAS::kNumChannels),
1542 fKp(0), fKi(0), fKd(0), fT(-1),
1543 fCalibrationOffset(-3),
1544 fCurrentRequestInterval(0),
1545 fNumCalibIgnore(30),
1546 fNumCalibRequests(300),
1547 fOutputEnabled(false)
1548 {
1549 // ba::io_service::work is a kind of keep_alive for the loop.
1550 // It prevents the io_service to go to stopped state, which
1551 // would prevent any consecutive calls to run()
1552 // or poll() to do nothing. reset() could also revoke to the
1553 // previous state but this might introduce some overhead of
1554 // deletion and creation of threads and more.
1555
1556 fDim.Subscribe(*this);
1557 fDimFAD.Subscribe(*this);
1558 fDimFSC.Subscribe(*this);
1559 fDimBias.Subscribe(*this);
1560
1561 Subscribe("BIAS_CONTROL/CURRENT")
1562 (bind(&StateMachineFeedback::HandleBiasCurrent, this, placeholders::_1));
1563 Subscribe("BIAS_CONTROL/VOLTAGE")
1564 (bind(&StateMachineFeedback::HandleBiasVoltage, this, placeholders::_1));
1565 Subscribe("BIAS_CONTROL/FEEDBACK_DATA")
1566 (bind(&StateMachineFeedback::HandleBiasData, this, placeholders::_1));
1567 Subscribe("BIAS_CONTROL/NOMINAL")
1568 (bind(&StateMachineFeedback::HandleBiasNom, this, placeholders::_1));
1569 Subscribe("FSC_CONTROL/TEMPERATURE")
1570 (bind(&StateMachineFeedback::HandleCameraTemp, this, placeholders::_1));
1571
1572 // State names
1573 AddStateName(Feedback::State::kDimNetworkNA, "DimNetworkNotAvailable",
1574 "The Dim DNS is not reachable.");
1575
1576 AddStateName(Feedback::State::kDisconnected, "Disconnected",
1577 "The Dim DNS is reachable, but the required subsystems are not available.");
1578
1579 AddStateName(Feedback::State::kConnecting, "Connecting",
1580 "Only biasctrl is available and connected with its hardware.");
1581
1582 AddStateName(Feedback::State::kConnectedFSC, "ConnectedFSC",
1583 "biasctrl and fscctrl are available and connected with their hardware.");
1584 AddStateName(Feedback::State::kConnectedFAD, "ConnectedFAD",
1585 "biasctrl and fadctrl are available and connected with their hardware.");
1586 AddStateName(Feedback::State::kConnected, "Connected",
1587 "biasctrl, fadctrl and fscctrl are available and connected with their hardware.");
1588
1589 AddStateName(Feedback::State::kFeedbackCtrlIdle, "FeedbackIdle",
1590 "Feedback control activated, but voltage output disabled.");
1591 AddStateName(Feedback::State::kTempCtrlIdle, "TempCtrlIdle",
1592 "Temperature control activated, but voltage output disabled.");
1593 AddStateName(Feedback::State::kCurrentCtrlIdle, "CurrentCtrlIdle",
1594 "Current control activated, but voltage output disabled.");
1595
1596 AddStateName(Feedback::State::kFeedbackCtrlRunning, "FeedbackControl",
1597 "Feedback control activated and voltage output enabled.");
1598 AddStateName(Feedback::State::kTempCtrlRunning, "TempControl",
1599 "Temperature control activated and voltage output enabled.");
1600 AddStateName(Feedback::State::kCurrentCtrlRunning, "CurrentControl",
1601 "Current/Temp control activated and voltage output enabled.");
1602 AddStateName(Feedback::State::kCalibrating, "Calibrating",
1603 "Calibrating current offsets.");
1604
1605 AddEvent("START_FEEDBACK_CONTROL", "S:1", Feedback::State::kConnectedFAD, Feedback::State::kConnected)
1606 (bind(&StateMachineFeedback::StartFeedback, this, placeholders::_1))
1607 ("Start the feedback control loop"
1608 "|Num[short]:Number of events 'medianed' to calculate the correction value");
1609
1610 AddEvent("START_GLOBAL_FEEDBACK", "S:1", Feedback::State::kConnectedFAD, Feedback::State::kConnected)
1611 (bind(&StateMachineFeedback::StartFeedbackGlobal, this, placeholders::_1))
1612 ("Start the global feedback control loop"
1613 "Num[short]:Number of events averaged to calculate the correction value");
1614
1615 AddEvent("START_TEMP_CONTROL", "F:1", Feedback::State::kConnectedFSC, Feedback::State::kConnected)
1616 (bind(&StateMachineFeedback::StartTempCtrl, this, placeholders::_1))
1617 ("Start the temperature control loop"
1618 "|offset[V]:Offset from the nominal temperature corrected value in Volts");
1619
1620 AddEvent("START_CURRENT_CONTROL", "F:1", Feedback::State::kConnectedFSC, Feedback::State::kConnected)
1621 (bind(&StateMachineFeedback::StartCurrentCtrl, this, placeholders::_1))
1622 ("Start the current/temperature control loop"
1623 "|offset[V]:Offset from the nominal current/temperature corrected value in Volts");
1624
1625 // Feedback::State::kTempCtrlIdle, Feedback::State::kFeedbackCtrlIdle, Feedback::State::kTempCtrlRunning, Feedback::State::kFeedbackCtrlRunning
1626 AddEvent("STOP")
1627 (bind(&StateMachineFeedback::StopFeedback, this))
1628 ("Stop any control loop");
1629
1630 AddEvent("ENABLE_OUTPUT", "B:1")//, Feedback::State::kIdle)
1631 (bind(&StateMachineFeedback::EnableOutput, this, placeholders::_1))
1632 ("Enable sending of correction values caluclated by the control loop to the biasctrl");
1633
1634 AddEvent("STORE_REFERENCE")//, Feedback::State::kIdle)
1635 (bind(&StateMachineFeedback::StoreReference, this))
1636 ("Store the last (averaged) value as new reference (for debug purpose only)");
1637
1638 AddEvent("SET_REFERENCE", "F:1")//, Feedback::State::kIdle)
1639 (bind(&StateMachineFeedback::SetReference, this, placeholders::_1))
1640 ("Set a new global reference value (for debug purpose only)");
1641
1642 AddEvent("SET_Ki", "D:1")//, Feedback::State::kIdle)
1643 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 0))
1644 ("Set integral constant Ki");
1645
1646 AddEvent("SET_Kp", "D:1")//, Feedback::State::kIdle)
1647 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 1))
1648 ("Set proportional constant Kp");
1649
1650 AddEvent("SET_Kd", "D:1")//, Feedback::State::kIdle)
1651 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 2))
1652 ("Set derivative constant Kd");
1653
1654 AddEvent("SET_T", "D:1")//, Feedback::State::kIdle)
1655 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 3))
1656 ("Set time-constant. (-1 to use the cycle time, i.e. the time for the last average cycle, instead)");
1657
1658 AddEvent("CALIBRATE_CURRENTS", Feedback::State::kConnectedFSC, Feedback::State::kConnected)//, Feedback::State::kIdle)
1659 (bind(&StateMachineFeedback::CalibrateCurrents, this))
1660 ("");
1661
1662 AddEvent("SET_CURRENT_REQUEST_INTERVAL", Feedback::State::kConnectedFSC, Feedback::State::kConnected)//, Feedback::State::kIdle)
1663 (bind(&StateMachineFeedback::SetCurrentRequestInterval, this, placeholders::_1))
1664 ("|interval[ms]:Interval between two current requests in modes which need that.");
1665
1666 // Verbosity commands
1667// AddEvent("SET_VERBOSE", "B:1")
1668// (bind(&StateMachineMCP::SetVerbosity, this, placeholders::_1))
1669// ("set verbosity state"
1670// "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
1671
1672 AddEvent("PRINT")
1673 (bind(&StateMachineFeedback::Print, this))
1674 ("");
1675
1676 AddEvent("PRINT_CALIBRATION")
1677 (bind(&StateMachineFeedback::PrintCalibration, this))
1678 ("");
1679 }
1680
1681 int EvalOptions(Configuration &conf)
1682 {
1683 if (!fMap.Read(conf.Get<string>("pixel-map-file")))
1684 {
1685 Error("Reading mapping table from "+conf.Get<string>("pixel-map-file")+" failed.");
1686 return 1;
1687 }
1688
1689 fGain = 0.1; // V(Amplitude) / V(Bias)
1690
1691 // 148 -> 248
1692
1693 // 33 : 10s < 2%
1694 // 50 : 5s < 2%
1695 // 66 : 3s < 2%
1696 // 85 : 2s < 2%
1697
1698 fKp = 0;
1699 fKd = 0;
1700 fKi = 0.75;
1701 fT = 1;
1702
1703 // Is that independent of the aboslute real amplitude of
1704 // the light pulser?
1705
1706 ostringstream msg;
1707 msg << "Control loop parameters: ";
1708 msg << "Kp=" << fKp << ", Kd=" << fKd << ", Ki=" << fKi << ", ";
1709 if (fT>0)
1710 msg << fT;
1711 else
1712 msg << "<auto>";
1713 msg << ", Gain(DRS/BIAS)=" << fGain << "V/V";
1714
1715 Message(msg);
1716
1717 fCurrentRequestInterval = conf.Get<uint16_t>("current-request-interval");
1718 fNumCalibIgnore = conf.Get<uint16_t>("num-calib-ignore");
1719 fNumCalibRequests = conf.Get<uint16_t>("num-calib-average");
1720 fCalibrationOffset = conf.Get<float>("calibration-offset");
1721
1722 return -1;
1723 }
1724};
1725
1726// ------------------------------------------------------------------------
1727
1728#include "Main.h"
1729
1730template<class T>
1731int RunShell(Configuration &conf)
1732{
1733 return Main::execute<T, StateMachineFeedback>(conf);
1734}
1735
1736void SetupConfiguration(Configuration &conf)
1737{
1738 po::options_description control("Feedback options");
1739 control.add_options()
1740 ("pixel-map-file", var<string>()->required(), "Pixel mapping file. Used here to get the default reference voltage.")
1741 ("current-request-interval", var<uint16_t>(1000), "Interval between two current requests.")
1742 ("num-calib-ignore", var<uint16_t>(30), "Number of current requests to be ignored before averaging")
1743 ("num-calib-average", var<uint16_t>(300), "Number of current requests to be averaged")
1744 ("calibration-offset", var<float>(-3), "Absolute offset relative to the G-APD operation voltage when calibrating")
1745 ;
1746
1747 conf.AddOptions(control);
1748}
1749
1750/*
1751 Extract usage clause(s) [if any] for SYNOPSIS.
1752 Translators: "Usage" and "or" here are patterns (regular expressions) which
1753 are used to match the usage synopsis in program output. An example from cp
1754 (GNU coreutils) which contains both strings:
1755 Usage: cp [OPTION]... [-T] SOURCE DEST
1756 or: cp [OPTION]... SOURCE... DIRECTORY
1757 or: cp [OPTION]... -t DIRECTORY SOURCE...
1758 */
1759void PrintUsage()
1760{
1761 cout <<
1762 "The feedback control the BIAS voltages based on the calibration signal.\n"
1763 "\n"
1764 "The default is that the program is started without user intercation. "
1765 "All actions are supposed to arrive as DimCommands. Using the -c "
1766 "option, a local shell can be initialized. With h or help a short "
1767 "help message about the usuage can be brought to the screen.\n"
1768 "\n"
1769 "Usage: feedback [-c type] [OPTIONS]\n"
1770 " or: feedback [OPTIONS]\n";
1771 cout << endl;
1772}
1773
1774void PrintHelp()
1775{
1776 Main::PrintHelp<StateMachineFeedback>();
1777
1778 /* Additional help text which is printed after the configuration
1779 options goes here */
1780
1781 /*
1782 cout << "bla bla bla" << endl << endl;
1783 cout << endl;
1784 cout << "Environment:" << endl;
1785 cout << "environment" << endl;
1786 cout << endl;
1787 cout << "Examples:" << endl;
1788 cout << "test exam" << endl;
1789 cout << endl;
1790 cout << "Files:" << endl;
1791 cout << "files" << endl;
1792 cout << endl;
1793 */
1794}
1795
1796int main(int argc, const char* argv[])
1797{
1798 Configuration conf(argv[0]);
1799 conf.SetPrintUsage(PrintUsage);
1800 Main::SetupConfiguration(conf);
1801 SetupConfiguration(conf);
1802
1803 if (!conf.DoParse(argc, argv, PrintHelp))
1804 return 127;
1805
1806 //try
1807 {
1808 // No console access at all
1809 if (!conf.Has("console"))
1810 {
1811// if (conf.Get<bool>("no-dim"))
1812// return RunShell<LocalStream, StateMachine, ConnectionFSC>(conf);
1813// else
1814 return RunShell<LocalStream>(conf);
1815 }
1816 // Cosole access w/ and w/o Dim
1817/* if (conf.Get<bool>("no-dim"))
1818 {
1819 if (conf.Get<int>("console")==0)
1820 return RunShell<LocalShell, StateMachine, ConnectionFSC>(conf);
1821 else
1822 return RunShell<LocalConsole, StateMachine, ConnectionFSC>(conf);
1823 }
1824 else
1825*/ {
1826 if (conf.Get<int>("console")==0)
1827 return RunShell<LocalShell>(conf);
1828 else
1829 return RunShell<LocalConsole>(conf);
1830 }
1831 }
1832 /*catch (std::exception& e)
1833 {
1834 cerr << "Exception: " << e.what() << endl;
1835 return -1;
1836 }*/
1837
1838 return 0;
1839}
Note: See TracBrowser for help on using the repository browser.