-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcrate_cbal.c
1483 lines (1234 loc) · 57.9 KB
/
crate_cbal.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <math.h>
#include "include/dacNumber.h"
#include "include/xl_regs.h"
#include "penn_daq.h"
#include "fec_util.h"
#include "mtc_util.h"
#include "crate_cbal.h"
#include "net_util.h"
//#include "pouch.h"
//#include "json.h"
uint32_t *pmt_buf;
int crate_cbal(char * buffer)
{
if (sbc_is_connected == 0){
printsend("SBC not connected.\n");
return -1;
}
int crate = 2;
uint32_t slot_mask = 0x2000;
uint32_t theDACs[50];
uint32_t theDAC_Values[50];
int num_dacs = 0;
uint32_t chan_mask = 0xFFFFFFFF;
int update_db = 0;
int final_test = 0;
char ft_ids[16][50];
int i;
char *words,*words2;
words = strtok(buffer, " ");
while (words != NULL){
if (words[0] == '-'){
if (words[1] == 'c'){
words2 = strtok(NULL, " ");
crate = atoi(words2);
}else if (words[1] == 's'){
words2 = strtok(NULL, " ");
slot_mask = strtoul(words2,(char**)NULL,16);
}else if (words[1] == 'd'){
update_db = 1;
}else if (words[1] == '#'){
final_test = 1;
for (i=0;i<16;i++){
if ((0x1<<i) & slot_mask){
words2 = strtok(NULL, " ");
sprintf(ft_ids[i],"%s",words2);
}
}
}else if (words[1] == 'l'){
words2 = strtok(NULL, " ");
chan_mask = strtoul(words2,(char**)NULL,16);
}else if (words[1] == 'h'){
printsend("Usage: crate_cbal -c"
" [crate_num] -s [slot_mask (hex)] -l [chan_mask] -d (update debug db)\n");
return 0;
}
}
words = strtok(NULL, " ");
}
if (!update_db)
printsend("Not writing balance values to DB.\n");
else
;
int j,it,im,is;
int error_flags[32];
for (i=0;i<32;i++){
error_flags[i] = 0;
}
//constants
const short Max_channels = 32;
const short Max_iterations = 40;
// test value to set timing dacs to during test
// roughly corresponds to 1.5 us GTV, 0.8-1.2us reset/sample.
// also set VLI, RMP to values that are defaults
// these setup values are also stored in DB-Skey 2.
const short vsitestval = 0;
const short isetmtestval = 85;
const short rmp1testval = 100;
const short vlitestval = 120;
const short rmp2testval = 155;
const short vmaxtestval = 203;
const short tacreftestval = 72;
uint32_t BalancedChs = 0x0; // which channels have been balanced;
uint32_t activeChannels = chan_mask;
uint32_t orig_activeChannels;
//create pedestal structures
struct pedestal x1[MAXCHAN], x2[MAXCHAN], tmp[MAXCHAN];
struct pedestal x1l[MAXCHAN], x2l[MAXCHAN], tmpl[MAXCHAN];
//three locations to store channel info
struct pedestal *x1_ch, *x2_ch, *tmp_ch, *x1l_ch, *x2l_ch, *tmpl_ch;
//pointer to dac values for each channel
short *x1_bal, *x2_bal, *tmp_bal, *bestguess_bal;
short ax1_bal[MAXCHAN], ax2_bal[MAXCHAN], atmp_bal[MAXCHAN],
abestguess_bal[MAXCHAN];
float *f1, *f2; // the actual function
float af1[MAXCHAN], af2[MAXCHAN];
//keep individual channel info here.
struct channelParams *ChParams;
struct channelParams ChParam[32];
//keep track of how often we loop through.
short iterations = 0, returnValue = 0;
//max acceptable diff btw qhl and qhs in same
float acceptableDiff = 10;
//other stuff
float fmean1, fmean2;
const float numcells = 16;
int vbal_temp[2][32*16];
hware_vals_t theHWconf[FECSLOTS];
//packet stuff
uint32_t select_reg;
uint32_t result;
XL3_Packet packet;
uint32_t *p;
p = (uint32_t *) packet.payload;
// END variables --------------
printsend("-------------------------------\n");
printsend("Balancing channels now.\nHigh gain balance first.\n");
//initialization
x1_ch = &x1[0];
x2_ch = &x2[0];
tmp_ch = &tmp[0];
x1l_ch = &x1l[0];
x2l_ch = &x2l[0];
tmpl_ch = &tmpl[0];
x1_bal = &ax1_bal[0];
x2_bal = &ax2_bal[0];
tmp_bal = &atmp_bal[0];
bestguess_bal = &abestguess_bal[0];
f1 = &af1[0];
f2 = &af2[0];
ChParams = &ChParam[0];
//setup pulser for soft GT mode by setting frequency to zero
setup_pedestals(0.0,50,125,0);
unset_gt_crate_mask(MASKALL);
unset_ped_crate_mask(MASKALL); // unmask all crates
set_gt_crate_mask(0x1<<crate);
set_ped_crate_mask(0x1<<crate); // add our crate to mask
//set_gt_crate_mask(MASKALL);
//set_ped_crate_mask(MASKALL); // add our crate to mask
set_gt_crate_mask(MSK_TUB);
set_ped_crate_mask(MSK_TUB); // add TUB to mask
// malloc some stuff
pmt_buf = (uint32_t *) malloc( TWOTWENTY*sizeof(u_long));
//END initialization --------
//loop over slots
for (is=0;is<16;is++){
if ((0x1<<is) & slot_mask){
select_reg = FEC_SEL*is;
xl3_rw(GENERAL_CSR_R + select_reg + WRITE_REG,0xF,&result,crate); // clear fec
printsend( "--------------------------------\n");
printsend( "Balancing Crate %hu, Slot %hu. \n",crate,is);
//////////////////////////
// INITIALIZE VARIABLES //
//////////////////////////
//initialize structs -- pedestal struct initialized in getPedestal.
iterations = 0;
BalancedChs = 0x0;
for (i=0;i<32;i++){
ChParam[i].test_status = 0x0; // zero means test not passed
ChParam[i].hiBalanced = 0; // set to false
ChParam[i].loBalanced = 0; // set to false
ChParam[i].highGainBalance = 0; // reset
ChParam[i].lowGainBalance = 0; // reset
}
for (i=0;i<32;i++){
f1[i] = f2[i] = 0;
// I will assume that a large setting of dac balance conditions
// gives the balance a positive slope. Therefore the x2 series
// will have Qhl > Qhs and f = qhl - qhs > 0, and the x1 series
// will have Qhl < Qhs and therefore f < 0.
*(x1_bal + i) = 0x32; // low initial setting
*(x2_bal + i) = 0xBE; // high initial setting
}
// init other stuff
orig_activeChannels = activeChannels;
// timing setup for test.
// set VSI, VLI to a long time during test.
// see variable section above for details.
if (DEBUG){
printsend(SNTR_TOOLS_DIALOG_DIVIDER);
printsend("Setting up timing for test.\n");
}
for (i=0;i<8;i++){
theDACs[num_dacs] = d_rmp[i];
theDAC_Values[num_dacs] = rmp2testval;
num_dacs++;
theDACs[num_dacs] = d_rmpup[i];
theDAC_Values[num_dacs] = rmp1testval;
num_dacs++;
theDACs[num_dacs] = d_vsi[i];
theDAC_Values[num_dacs] = vsitestval;
num_dacs++;
theDACs[num_dacs] = d_vli[i];
theDAC_Values[num_dacs] = vlitestval;
num_dacs++;
}
// now CMOS timing for GTValid
for (i = 0; i < 2; i++) {
theDACs[num_dacs] = d_isetm[i];
theDAC_Values[num_dacs] = isetmtestval;
num_dacs++;
}
theDACs[num_dacs] = d_tacref;
theDAC_Values[num_dacs] = tacreftestval;
num_dacs++;
theDACs[num_dacs] = d_vmax;
theDAC_Values[num_dacs] = vmaxtestval;
num_dacs++;
if (multiloadsDac(num_dacs,theDACs,theDAC_Values,crate,select_reg) != 0){
printsend("Error loading Dacs. Aborting.\n");
free(pmt_buf);
return REG_ERROR;
}
num_dacs = 0;
////////////////////////////
// CALCULATE ZERO BALANCE //
////////////////////////////
// done setting up the timing.
// first need to calculate initial conditions
if (DEBUG) {
printsend(SNTR_TOOLS_DIALOG_DIVIDER);
printsend("Starting testing run.\n");
}
// get data for balance at zero
for (i = 0; i <= 31; i++) {
// only do active channels
if ((activeChannels & (0x1L << i)) != 0) {
theDACs[num_dacs] = d_vbal_hgain[i];
theDAC_Values[num_dacs] = x1_bal[i];
num_dacs++;
}
}
if (multiloadsDac(num_dacs,theDACs,theDAC_Values,crate,select_reg) != 0){
printsend("Error loading Dacs. Aborting.\n");
free(pmt_buf);
return REG_ERROR;
}
num_dacs = 0;
// x1 will be the low data point.
// grab pedestal data with these settings.
if (getPedestal(x1_ch, ChParams, crate, select_reg) != 0) {
printsend(PED_ERROR_MESSAGE);
//SNO_printerr(5, INIT_FAC, err_str);
free(pmt_buf);
return PED_ERROR;
}
///////////////////////////
// CALCULATE MAX BALANCE //
///////////////////////////
// get data for balance at 0xff
for (i = 0; i <= 31; i++) {
// only do active channels
if ((activeChannels & (0x1L << i)) != 0) {
theDACs[num_dacs] = d_vbal_hgain[i];
theDAC_Values[num_dacs] = x2_bal[i];
num_dacs++;
}
}
if (multiloadsDac(num_dacs,theDACs,theDAC_Values,crate,select_reg) != 0){
printsend("Error loading Dacs. Aborting.\n");
free(pmt_buf);
return REG_ERROR;
}
num_dacs = 0;
// x2 will be the high data point.
if (getPedestal(x2_ch, ChParams, crate,select_reg) != 0) {
printsend(PED_ERROR_MESSAGE);
//SNO_printerr(5, INIT_FAC, err_str);
free(pmt_buf);
return PED_ERROR;
}
// end initial conditions.
/////////////////////////
// LOOP UNTIL BALANCED //
/////////////////////////
// loop until the balance is set.
do {
// some checking to make sure we don't do this forever.
if (iterations++ > (Max_iterations)) {
if (DEBUG) {
printsend("Too many iterations, "
"aborting with some channels unbalanced.\n");
//SNO_printerr(5, INIT_FAC, err_str);
printsend("Making best guess for unbalanced channels.\n");
//SNO_printerr(5, INIT_FAC, err_str);
}
// get best guess from those channels that remain unbalanced
for (it = 0; it < 32; it++) {
// if this channel is unbalanced
if (ChParam[it].hiBalanced == 0) {
// then we take the best guess and use that.
ChParam[it].highGainBalance = bestguess_bal[it];
}
}
break;
}
// loop over channels
for (j = 0; j <= 31; j++) {
// if this channel is active and was not declared balanced before
if (((activeChannels & (0x1L << j)) != 0) &&
(ChParam[j].hiBalanced == 0)) {
// then calculate the two data points, high and low.
// average data over all cells to reduce effects of badly
// matched cells -RGV
fmean1= 0;
fmean2= 0;
for (im = 0; im < 16; im++) {
fmean1 += x1_ch[j].thiscell[im].qhlbar
- x1_ch[j].thiscell[im].qhsbar;
fmean2 += x2_ch[j].thiscell[im].qhlbar
- x2_ch[j].thiscell[im].qhsbar;
}
f1[j] = fmean1 / numcells;
f2[j] = fmean2 / numcells;
if (DEBUG) {
printsend( "Iteration %d, Ch(%2i): f1 = %+7.1f, x1 = %3i, f2 = %+7.1f,"
" x2 = %3i\n", iterations, j, f1[j], x1_bal[j], f2[j], x2_bal[j]);
//SNO_printerr(5, INIT_FAC, err_str);
}
// check to assure we straddle root, i.e. channel is balanceable
// i.e. they both have the same sign on first run
if (((f1[j] * f2[j]) > 0.0) && (iterations == 1)) {
if (DEBUG) {
printsend("Error: Ch(%2i) does not appear"
" balanceable.\n", j);
//SNO_printerr(5, INIT_FAC, err_str);
}
// turn off this one and go on.
activeChannels &= ~(0x1UL << j);
returnValue += 100;
// if returnvalue is gt. 100, we know some channels were
// unbalanceable
}
if (fabs(f2[j]) < acceptableDiff) { // we found bal w/ f2[j]
BalancedChs |= 0x1L << j; // turn on bit since balanced.
ChParam[j].hiBalanced = 1;
ChParam[j].highGainBalance = x2_bal[j];
// turn this off to speed up retrieving data.
activeChannels &= ~(0x1UL << j);
// this will not enable the pedestal on this channel.
}
else if (fabs(f1[j]) < acceptableDiff) { // we found bal w/ f1[j]
BalancedChs |= 0x1L << j; // turn on bit since it's balanced.
ChParam[j].hiBalanced = 1;
ChParam[j].highGainBalance = x1_bal[j];
activeChannels &= ~(0x1UL << j); // turn off to speed up
// this will not enable the pedestal on this channel.
}
else { // we haven't found balance.
// data point between the two locations -- false
// position method. this is new dac value. false
// position, x_guess = x1 + dx* f(x1) / (f(x1) - f(x2))
tmp_bal[j] = x1_bal[j] + (x2_bal[j] - x1_bal[j])
* (f1[j] / (f1[j] - f2[j]));
// keep track of best guess
if (fabs(f1[j]) < fabs(f2[j]))
// then make best guess for which one we should take
bestguess_bal[j] = x1_bal[j];
else
bestguess_bal[j] = x2_bal[j];
if (tmp_bal[j] == x2_bal[j]) { // i.e., we are stuck in a rut
// short kick = (short) (rand() % 35) + 15;
short kick = (short) (rand() % 35) + 150;
tmp_bal[j] = (tmp_bal[j] >= 45) ?
(tmp_bal[j] - kick) : (tmp_bal[j] + kick);
if (DEBUG) {
printsend( "Ch(%2i) in local trap. "
"Nudging by %2i\n", j, kick);
//SNO_printerr(5, INIT_FAC, err_str);
}
}
// this algorithm can "run away" to infinity so make sure
// we stay in bounds
if (tmp_bal[j] > 255)
tmp_bal[j] = 255;
else if (tmp_bal[j] < 0)
tmp_bal[j] = 0;
theDACs[num_dacs] = d_vbal_hgain[j];
theDAC_Values[num_dacs] = tmp_bal[j];
num_dacs++;
// now process rest of this loop before running
// pedestal once to get all the rest of the
// information.
}
} // end loop over active channels
} // end loop over channels
if (multiloadsDac(num_dacs,theDACs,theDAC_Values,crate,select_reg) != 0){
printsend("Error loading Dacs. Aborting.\n");
free(pmt_buf);
return REG_ERROR;
}
num_dacs = 0;
// do a pedestal run with new balance unless all chs are balanced,
// i.e. none are active
if (activeChannels != 0x0) {
if (DEBUG) {
printsend( "Next step, iteration %i.\n", iterations);
//SNO_printerr(7, INIT_FAC, err_str);
}
if (getPedestal(tmp_ch, ChParams, crate,select_reg) != 0) {
printsend(PED_ERROR_MESSAGE);
//SNO_printerr(5, INIT_FAC, err_str);
free(pmt_buf);
return PED_ERROR;
}
for (j = 0; j <= 31; j++) {
if ((activeChannels & (0x1L << j)) != 0) {
// secant method -- always keep last two points.
x1_ch[j] = x2_ch[j];
x1_bal[j] = x2_bal[j];
x2_ch[j] = tmp_ch[j];
x2_bal[j] = tmp_bal[j];
// now we're ready go on to next channel.....
}
}
}
} while (BalancedChs != orig_activeChannels); // loop utl the bal'd chs
// equal the active channels.
// let people know what's going on
if (DEBUG) {
printsend("End of high gain balancing.\n");
//SNO_printerr(7, INIT_FAC, err_str);
printsend(SNTR_TOOLS_DIALOG_DIVIDER);
//SNO_printerr(7, INIT_FAC, err_str);
printsend("Starting low gain balance run.\n");
//SNO_printerr(7, INIT_FAC, err_str);
}
// reset this
activeChannels = orig_activeChannels;
// now do low gain loop. basic copy of above, with slight exception
// that there is an additional step (toggle LGI_SEL bit) to set the
// second balance point. Even slower. yikes.
// need additional info here
// rezero these guys
for (i = 0; i <= 31; i++) {
f1[i] = f2[i] = 0;
// I will assume that a large setting of dac balance conditions
// gives the balance a positive slope. Therefore the x2 series
// will have Qhl > Qhs and f = qhl - qhs > 0, and the x1 series
// will have Qhl < Qhs and therefore f < 0.
//Hacked by cK. Original settings were 0 and FF
*(x1_bal + i) = 0x32; // low initial setting
*(x2_bal + i) = 0xBE; // high initial setting
}
// get data for balance at zero
for (i = 0; i <= 31; i++) {
// only do active channels
if ((activeChannels & (0x1L << i)) != 0) {
theDACs[num_dacs] = d_vbal_lgain[i];
theDAC_Values[num_dacs] = x1_bal[i];
num_dacs++;
}
}
if (multiloadsDac(num_dacs,theDACs,theDAC_Values,crate,select_reg) != 0){
printsend("Error loading Dacs. Aborting.\n");
free(pmt_buf);
return REG_ERROR;
}
num_dacs = 0;
// x1,x1l will be the low data point.
// grab pedestal data with these settings.
if (getPedestal(x1_ch, ChParams, crate,select_reg) != 0) {
printsend(PED_ERROR_MESSAGE);
//SNO_printerr(5, INIT_FAC, err_str);
free(pmt_buf);
return PED_ERROR;
}
// now switch LGI sel bit
xl3_rw(CMOS_LGISEL_R + select_reg + WRITE_REG,0x1,&result,crate);
// now get low gain long integrate
if (getPedestal(x1l_ch, ChParams, crate,select_reg) != 0) {
printsend(PED_ERROR_MESSAGE);
//SNO_printerr(5, INIT_FAC, err_str);
free(pmt_buf);
return PED_ERROR;
}
// now switch LGI sel bit back
xl3_rw(CMOS_LGISEL_R + select_reg + WRITE_REG,0x0,&result,crate);
// get data for balance at 0xff
for (i = 0; i <= 31; i++) {
// only do active channels
if ((activeChannels & (0x1L << i)) != 0) {
theDACs[num_dacs] = d_vbal_lgain[i];
theDAC_Values[num_dacs] = x2_bal[i];
num_dacs++;
}
}
if (multiloadsDac(num_dacs,theDACs,theDAC_Values,crate,select_reg) != 0){
printsend("Error loading Dacs. Aborting.\n");
free(pmt_buf);
return REG_ERROR;
}
num_dacs = 0;
// x2 will be the high data point.
if (getPedestal(x2_ch, ChParams, crate,select_reg) != 0) {
printsend(PED_ERROR_MESSAGE);
//SNO_printerr(5, INIT_FAC, err_str);
free(pmt_buf);
return PED_ERROR;
}
// now switch LGI sel bit
xl3_rw(CMOS_LGISEL_R + select_reg + WRITE_REG,0x1,&result,crate);
// now get low gain long integrate
if (getPedestal(x2l_ch, ChParams, crate,select_reg) != 0) {
printsend(PED_ERROR_MESSAGE);
//SNO_printerr(5, INIT_FAC, err_str);
free(pmt_buf);
return PED_ERROR;
}
// now switch LGI sel bit back
xl3_rw(CMOS_LGISEL_R + select_reg + WRITE_REG,0x0,&result,crate);
// end initial conditions.
iterations = 0; // reset this
BalancedChs = 0x0;
///////////////////////////////////////
// LOOP AGAIN UNTIL BALANCED FOR LGI //
///////////////////////////////////////
// loop until the balance is set.
do {
// some checking to make sure we don't do this forever.
if (iterations++ > (Max_iterations)) {
if (DEBUG) {
printsend("Too many iterations -- aborting with some"
" channels unbalanced.\n");
//SNO_printerr(7, INIT_FAC, err_str);
printsend("Making best guess for unbalanced channels.\n");
//SNO_printerr(7, INIT_FAC, err_str);
}
// get best guess from those channels that remain unbalanced
for (it = 0; it < 32; it++) {
if (ChParam[it].loBalanced == 0) { // if this ch is unbalanced
// then we take the best guess and use that.
ChParam[it].lowGainBalance = bestguess_bal[it];
}
}
break;
}
// loop over channels
for (j = 0; j <= 31; j++) {
// if this channel is active and was not declared balanced before
if (((activeChannels & (0x1L << j)) != 0) &&
(ChParam[j].loBalanced == 0)) {
// then calculate the two data points, high and low.
//average data over all cells to reduce effects of badly
// matched cells -RGV
fmean1= 0;
fmean2= 0;
for (im = 0; im < 16; im++) {
fmean1 += (x1_ch[j].thiscell[im].qlxbar
- x1l_ch[j].thiscell[im].qlxbar);
fmean2 += (x2_ch[j].thiscell[im].qlxbar
- x2l_ch[j].thiscell[im].qlxbar);
}
f1[j] = fmean1 / numcells;
f2[j] = fmean2 / numcells;
if (DEBUG) {
printsend( "Ch(%2i): f1 = %+7.1f, x1 = %3i, f2 = %+7.1f"
", x2 = %3i\n", j, f1[j], x1_bal[j], f2[j], x2_bal[j]);
//SNO_printerr(7, INIT_FAC, err_str);
}
// check to assure we straddle root, i.e. channel is balanceable
if (((f1[j] * f2[j]) > 0.0) && (iterations == 1)) {
//they both have the same sign on first run
if (DEBUG) {
printsend( "Error: Ch(%2i) does not appear"
" balanceable.\n", j);
//SNO_printerr(7, INIT_FAC, err_str);
}
activeChannels &= ~(0x1UL << j); // turn off this one and go on.
returnValue += 100; // if returnvalue is gt. 100, we know some
// channels were unbalanceable
}
if (fabs(f2[j]) < acceptableDiff) { // we found bal using f2[j]
BalancedChs |= 0x1L << j; // turn on bit as it's balc'd.
ChParam[j].loBalanced = 1;
ChParam[j].lowGainBalance = x2_bal[j];
// turn this off to speed up retrieving data.
activeChannels &= ~(0x1UL << j);
// this will not enable the pedestal on this channel.
}
else if (fabs(f1[j]) < acceptableDiff) { // we found balance using f1[j]
BalancedChs |= 0x1L << j; // turn on this bit since it's balanced.
ChParam[j].loBalanced = 1;
ChParam[j].lowGainBalance = x1_bal[j];
activeChannels &= ~(0x1UL << j); // turn this off to speed up retrieving data.
// this will not enable the pedestal on this channel.
}
else { // we haven't found balance.
// data point between the two locations -- false
// position method. this is new dac value. false
// position, x_guess = x1 + dx* f(x1) / (f(x1) - f(x2))
// see numerical recipes.
tmp_bal[j] = x1_bal[j] +
(x2_bal[j] - x1_bal[j]) * (f1[j] / (f1[j] - f2[j]));
if (tmp_bal[j] == x2_bal[j]) { // i.e., we are stuck in a rut
// short kick = (short) (rand() % 35) + 15;
short kick = (short) (rand() % 35) + 150;
tmp_bal[j] = (tmp_bal[j] >= 45)
? (tmp_bal[j] - kick) : (tmp_bal[j] + kick);
if (DEBUG) {
printsend( "Ch(%2i) in local trap. Nudging by %2i\n",
j, kick);
//SNO_printerr(7, INIT_FAC, err_str);
}
}
// keep track of best guess
// then make best guess for which one we should take
if (fabs(f1[j]) < fabs(f2[j]))
bestguess_bal[j] = x1_bal[j];
else
bestguess_bal[j] = x2_bal[j];
// this algorithm can "run away" to infinity so make sure
// we stay in bounds
if (tmp_bal[j] > 255)
tmp_bal[j] = 255;
else if (tmp_bal[j] < 0)
tmp_bal[j] = 0;
theDACs[num_dacs] = d_vbal_lgain[j];
theDAC_Values[num_dacs] = tmp_bal[j];
num_dacs++;
// now process rest of this loop before running
// pedestal once to get all the rest of the
// information.
}
}
}
if (multiloadsDac(num_dacs,theDACs,theDAC_Values,crate,select_reg) != 0){
printsend("Error loading Dacs. Aborting.\n");
free(pmt_buf);
return REG_ERROR;
}
num_dacs = 0;
// do a pedestal run with this new balance unless all
// channels are balanced,
// i.e. none are active
if (activeChannels != 0x0) {
if (DEBUG) {
printsend( "Next step, iteration %i.\n", iterations + 1);
//SNO_printerr(7, INIT_FAC, err_str);
}
if (getPedestal(tmp_ch, ChParams, crate,select_reg) != 0) {
printsend(PED_ERROR_MESSAGE);
//SNO_printerr(5, INIT_FAC, err_str);
free(pmt_buf);
return PED_ERROR;
}
// now switch LGI sel bit
xl3_rw(CMOS_LGISEL_R + select_reg + WRITE_REG,0x1,&result,crate);
// now get low gain long integrate
if (getPedestal(tmpl_ch, ChParams, crate,select_reg) != 0) {
printsend(PED_ERROR_MESSAGE);
//SNO_printerr(5, INIT_FAC, err_str);
free(pmt_buf);
return PED_ERROR;
}
// now switch LGI sel bit back
xl3_rw(CMOS_LGISEL_R + select_reg + WRITE_REG,0x0,&result,crate);
for (j = 0; j <= 31; j++) {
if ((activeChannels & (0x1L << j)) != 0) {
// secant method -- always keep last two points.
x1_ch[j] = x2_ch[j];
x1l_ch[j] = x2l_ch[j];
x1_bal[j] = x2_bal[j];
x2_ch[j] = tmp_ch[j];
x2l_ch[j] = tmpl_ch[j];
x2_bal[j] = tmp_bal[j];
}
}
}
} while (BalancedChs != orig_activeChannels); // loop until
// the balanced channels equal the active channels.
// ----------------------------------------
if (DEBUG) {
printsend("End of balancing loops.\n");
//SNO_printerr(5, INIT_FAC, err_str);
}
// reset this
activeChannels = orig_activeChannels;
printsend("\nFinal VBAL table.\n");
///////////////////////
// PRINT OUT RESULTS //
///////////////////////
// now report some results, and store in DB struct if requested
for (j = 0; j <= 31; j++) {
if ((activeChannels & (0x1L << j)) != 0) {
if ((ChParam[j].hiBalanced == 1) && (ChParam[j].loBalanced == 1)) {
printsend( "Ch %2i High: %3i. low: %3i -> balanced \n", j,
ChParam[j].highGainBalance, ChParam[j].lowGainBalance);
//SNO_printerr(5, INIT_FAC, err_str);
if ((ChParam[j].highGainBalance == 255)
|| (ChParam[j].highGainBalance == 0)
|| (ChParam[j].lowGainBalance == 255)
|| (ChParam[j].lowGainBalance == 0)) {
if(ChParam[j].highGainBalance == 255)
ChParam[j].highGainBalance = 150;
if(ChParam[j].highGainBalance == 0)
ChParam[j].highGainBalance = 150;
if(ChParam[j].lowGainBalance == 255)
ChParam[j].lowGainBalance = 150;
if(ChParam[j].lowGainBalance == 0)
ChParam[j].lowGainBalance = 150;
printsend(" >>Extreme balance, setting to 150 ");
error_flags[j] = 1;
}
if ((ChParam[j].highGainBalance > 225)
|| (ChParam[j].highGainBalance < 50)
|| (ChParam[j].lowGainBalance > 225)
|| (ChParam[j].lowGainBalance < 50)) {
printsend(" >>Warning: extreme balance value. ");
error_flags[j] = 2;
}
// store for db
vbal_temp[0][j] = ChParam[j].highGainBalance;
vbal_temp[1][j] = ChParam[j].lowGainBalance;
}
// partially balanced
else if ((ChParam[j].hiBalanced == 1)
|| (ChParam[j].loBalanced == 1)) {
error_flags[j] = 3;
printsend( "Ch %2i High: %3i. low: %3i -> part balanced, set to 150 if extreme\n",
j, ChParam[j].highGainBalance, ChParam[j].lowGainBalance);
//SNO_printerr(5, INIT_FAC, err_str);
//set to 150 if extreme
if(ChParam[j].highGainBalance == 255)
ChParam[j].highGainBalance = 150;
if(ChParam[j].highGainBalance == 0)
ChParam[j].highGainBalance = 150;
if(ChParam[j].lowGainBalance == 255)
ChParam[j].lowGainBalance = 150;
if(ChParam[j].lowGainBalance == 0)
ChParam[j].lowGainBalance = 150;
// store for db
vbal_temp[0][j] = ChParam[j].highGainBalance;
vbal_temp[1][j] = ChParam[j].lowGainBalance;
returnValue += 1; // i.e. failure
}else { // unbalanced
error_flags[j] = 4;
printsend( "Ch %2i -> unbalanced, set to 150\n", j);
//SNO_printerr(5, INIT_FAC, err_str);
//if failed, set to 150
ChParam[j].highGainBalance = 150;
ChParam[j].lowGainBalance = 150;
// store for db
vbal_temp[0][j] = ChParam[j].highGainBalance;
vbal_temp[1][j] = ChParam[j].lowGainBalance;
returnValue += 1; // i.e. failure
}//end of switch over balanced state
}//end of loop for masked channels
}//end of loop over channels for printout, putting results in db struct
xl3_rw(GENERAL_CSR_R + select_reg + WRITE_REG,0xF,&result,crate); //golden rule #3
deselect_fecs(crate); //golden rule #2
///////////////
// UPDATE DB //
///////////////
//now lets update the database entry for this slot
if (update_db){
printsend("updating the database\n");
JsonNode *newdoc = json_mkobject();
json_append_member(newdoc,"type",json_mkstring("crate_cbal"));
JsonNode* vbal_high_new = json_mkarray();
JsonNode* vbal_low_new = json_mkarray();
JsonNode* error_new = json_mkarray();
int fail_flag = 0;
for (i=0;i<32;i++){
json_append_element(vbal_high_new,json_mknumber((double)vbal_temp[0][i]));
json_append_element(vbal_low_new,json_mknumber((double)vbal_temp[1][i]));
if (error_flags[i] == 0)
json_append_element(error_new,json_mkstring("none"));
else if (error_flags[i] == 1)
json_append_element(error_new,json_mkstring("Extreme balance set to 150"));
else if (error_flags[i] == 2)
json_append_element(error_new,json_mkstring("Extreme balance values"));
else if (error_flags[i] == 3)
json_append_element(error_new,json_mkstring("Partially balanced"));
else if (error_flags[i] == 4)
json_append_element(error_new,json_mkstring("Unbalanced, set to 150"));
if (error_flags[i] != 0)
fail_flag = 1;
}
json_append_member(newdoc,"vbal_low",vbal_low_new);
json_append_member(newdoc,"vbal_high",vbal_high_new);
json_append_member(newdoc,"errors",error_new);
if (fail_flag == 0){
json_append_member(newdoc,"pass",json_mkstring("yes"));
}else{
json_append_member(newdoc,"pass",json_mkstring("no"));
}
if (final_test)
json_append_member(newdoc,"final_test_id",json_mkstring(ft_ids[is]));
post_debug_doc(crate,is,newdoc);
json_delete(newdoc); // delete the head
}
}//end of masked slot loop
}// end loop over slots
printsend("End of balanceChannels.\n");
//SNO_printerr(7, INIT_FAC, err_str);
printsend("**********************************\n");
//SNO_printerr(7, INIT_FAC, err_str);
free(pmt_buf);
return returnValue;
} // end balanceChannels
////////////////////////////////////////////////////////////
// CRATE_CBAL UTILITIES //
////////////////////////////////////////////////////////////
// getPedestal -- returns pedestal in form of channels struct.
// error checking and returns should be done in the calling
// function.
//short getPedestal(pedestal_t *pedestals )
short getPedestal(struct pedestal *pedestals,
struct channelParams *ChParams, int crate, uint32_t select_reg)
{
// ----------------------> variables
u_long i, j;
uint32_t regAddress, dataValue;
uint32_t WordsInMem, currentWord, Max_errors;
uint16_t dram_error=0;
int FirstWord = 1;
short num_errors = 0, num_events = 0;
FEC32PMTBundle PMTdata;
XL3_Packet packet;
uint32_t activeChannels;
uint32_t NumPulses;
uint32_t Min_num_words;
double x;
// max acceptable RMS for test.
float Max_RMS_Qlx;
float Max_RMS_Qhl;
float Max_RMS_Qhs;
float Max_RMS_TAC;
Max_RMS_Qlx = 2.0;
Max_RMS_Qhl = 2.0;
Max_RMS_Qhs = 10.0;
Max_RMS_TAC = 3.0;
NumPulses = 25 * 16; //want a multiple of number of cells (16)
printsend(".");
fflush(stdout);
Min_num_words = (NumPulses - 25) * 3UL * 32UL; //check number of bundles
activeChannels = 0xffffffff; //enable all channels
Max_errors = 250; // max number of errors before aborting DRAM readout.
uint32_t result;
// ----------------------> end variables
// make sure pedestal pointer is not null and initalize structs.