-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_ETROC.py
1549 lines (1303 loc) · 61.5 KB
/
test_ETROC.py
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
from tamalero.ETROC import ETROC
from tamalero.ETROC_Emulator import ETROC2_Emulator as software_ETROC2
from tamalero.DataFrame import DataFrame
from tamalero.utils import get_kcu
from tamalero.ReadoutBoard import ReadoutBoard
from tamalero.PixelMask import PixelMask
from tamalero.colors import red, green, yellow
import numpy as np
from scipy.optimize import curve_fit
from matplotlib import pyplot as plt
from tqdm import tqdm
import pandas as pd
import os
import sys
import json
import time
import datetime
from yaml import load, dump
import traceback
import pickle
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
# ====== HELPER FUNCTIONS ======
# run N L1A's and return packaged ETROC2 dataformat
def run(ETROC, N, fifo=None):
# currently uses the software ETROC to produce fake data
if ETROC.isfake:
return ETROC2.run(N)
else:
fifo.send_l1a(N)
return fifo.pretty_read(None, raw=True)
def toPixNum(row, col, w):
return col*w+row
def fromPixNum(pix, w):
row = pix%w
col = int(np.floor(pix/w))
return row, col
def sigmoid(k,x,x0):
return 1/(1+np.exp(k*(x-x0)))
# take x,y values and perform fit to sigmoid function
# return steepness(k) and mean(x0)
def sigmoid_fit(x_axis, y_axis):
res = curve_fit(
#sigmoid,
lambda x,a,b: 1/(1+np.exp(a*(x-b))), # for whatever reason this fit only works with a lambda function?
x_axis-x_axis[0],
y_axis,
maxfev=10000,
bounds=([-np.inf,-np.inf],[0,np.inf])
)
return res[0][0], res[0][1]+x_axis[0]
# parse ETROC dataformat into 1D list of # of hits per pixel
def parse_data(data, N_pix):
results = np.zeros(N_pix)
pix_w = int(round(np.sqrt(N_pix)))
for word in data:
datatype, res = DF.read(word)
if datatype == 'data':
pix = toPixNum(res['row_id'], res['col_id'], pix_w)
results[pix] += 1
return results
def vth_scan(ETROC2, vth_min=693, vth_max=709, vth_step=1, decimal=False, fifo=None, absolute=False):
# N_l1a = 3200 # how many L1As to send
N_l1a = 3200 # how many L1As to send
vth_min = vth_min # scan range
vth_max = vth_max
if not decimal:
vth_step = ETROC2.DAC_step # step size
else:
vth_step = vth_step
N_steps = int((vth_max-vth_min)/vth_step)+1 # number of steps
N_pix = 16*16 # total number of pixels
vth_axis = np.linspace(vth_min, vth_max, N_steps)
run_results = np.empty([N_steps, N_pix])
for vth in vth_axis:
print(f"Working on threshold {vth=}")
if decimal:
ETROC2.wr_reg('DAC', int(vth), broadcast=True)
#print("Acc value", ETROC2.get_ACC(row=0, col=0)) #doesn't work here
else:
ETROC2.set_Vth_mV(vth)
i = int((vth-vth_min)/vth_step)
run_results[i] = parse_data(run(ETROC2, N_l1a, fifo=fifo), N_pix)
# transpose so each 1d list is for a pixel & normalize
if absolute:
run_results = run_results.transpose()
else:
run_results = run_results.transpose()/N_l1a
return [vth_axis.tolist(), run_results.tolist()]
def vth_scan_internal(ETROC2, row=0, col=0, dac_min=0, dac_max=500, dac_step=1):
N_steps = int((dac_max-dac_min)/dac_step)+1 # number of steps
dac_axis = np.linspace(dac_min, dac_max, N_steps)
ETROC2.setup_accumulator(row, col)
results = []
for i in range(dac_min, dac_max+1, dac_step):
results.append(
etroc.check_accumulator(DAC=i, row=row, col=col)
)
run_results = np.array(results)
return [dac_axis, run_results]
# initiate
ETROC2 = software_ETROC2() # currently using Software ETROC2 (fake)
print("ETROC2 emulator instantiated, base configuration successful")
DF = DataFrame('ETROC2')
if __name__ == '__main__':
# argsparser
import argparse
argParser = argparse.ArgumentParser(description = "Argument parser")
argParser.add_argument('--test_readwrite', action='store_true', default=False, help="Test simple read/write functionality?")
argParser.add_argument('--test_chip', action='store_true', default=False, help="Test simple read/write functionality for real chip?")
argParser.add_argument('--config_chip', action='store_true', default=False, help="Configure chip?")
argParser.add_argument('--configuration', action='store', default='modulev0', choices=['modulev0', 'modulev0b', 'multimodule', 'modulev1'], help="Board configuration to be loaded")
argParser.add_argument('--vth', action='store_true', default=False, help="Parse Vth scan plots?")
argParser.add_argument('--rerun', action='store_true', default=False, help="Rerun Vth scan and overwrite data?")
argParser.add_argument('--fitplots', action='store_true', default=False, help="Create individual vth fit plots for all pixels?")
argParser.add_argument('--kcu', action='store', default='192.168.0.10', help="IP Address of KCU105 board")
argParser.add_argument('--module', action='store', default=0, choices=['1','2','3'], help="Module to test")
argParser.add_argument('--etroc', action='store', default=0, choices=['0','1','2','3'], help="Module to test")
argParser.add_argument('--rb', action='store', default=0, choices=['0','1','2','3'], help="Module to test")
argParser.add_argument('--host', action='store', default='localhost', help="Hostname for control hub")
argParser.add_argument('--partial', action='store_true', default=False, help="Only read data from corners and edges")
argParser.add_argument('--qinj_scan', action='store_true', default=False, help="Run the phase scan for Qinj")
argParser.add_argument('--qinj', action='store_true', default=False, help="Run some charge injection tests")
argParser.add_argument('--qinj_vth_scan', action='store_true', default=False, help="Run some charge injection tests")
argParser.add_argument('--charge', action='store', default=15, help="Charge to be injected")
argParser.add_argument('--hard_reset', action='store_true', default=False, help="Hard reset of selected ETROC2 chip")
argParser.add_argument('--skip_sanity_checks', action='store_true', default=False, help="Don't run sanity checks of ETROC2 chip")
argParser.add_argument('--pixelscan', action='store', default='none', choices=['none', 'full', 'simple', 'internal'], help="Which threshold scan to run with ETROC2")
argParser.add_argument('--mode', action='store', default='dual', choices=['dual', 'single'], help="Port mode for ETROC2")
argParser.add_argument('--threshold', action='store', default='auto', help="Use thresholds from manual or automatic scan?")
argParser.add_argument('--internal_data', action='store_true', help="Set up internal data generation")
argParser.add_argument('--enable_power_board', action='store_true', help="Enable Power Board (all modules). Jumpers must still be set as well.")
argParser.add_argument('--timing_scan', action='store_true', help="Perform L1Adelay timing scan")
argParser.add_argument('--row', action='store', default=4, help="Pixel row to be tested")
argParser.add_argument('--col', action='store', default=3, help="Pixel column to be tested")
argParser.add_argument('--pixel_mask', action='store', default=None, help="Pixel mask to apply")
argParser.add_argument('--moduleid', action='store', default=0, help="")
argParser.add_argument('--charges', action = 'store', default = [15], nargs = '*', type = int, help = 'Charges to inject')
argParser.add_argument('--vth_axis', action = 'store', default = [415, 820, 406], nargs = '*', type = int, help = 'Threshold DAC values to scan over')
argParser.add_argument('--nl1a', action = 'store', type = int, default = 3200, help = 'Number of Qinj/L1A pulses to send')
argParser.add_argument('--multi', action='store_true', help="Run multiple modules at once (for data taking only!)")
args = argParser.parse_args()
if args.test_chip or args.config_chip:
assert int(args.moduleid)>0, "Module ID is not specified. This is a new feature, please run with --moduleid MODULEID, where MODULEID is the number on the module test board."
MID = args.moduleid
else:
MID = "software"
ietroc = int(args.etroc)
timestamp = time.strftime("%Y-%m-%d-%H-%M-%S")
result_dir = f"results/{MID}/{timestamp}/"
out_dir = f"outputs/{MID}/{timestamp}/"
if not os.path.isdir(result_dir):
os.makedirs(result_dir)
if not os.path.isdir(out_dir):
os.makedirs(out_dir)
print(f"Will test module with ID {MID}.")
print(f"All results will be stored under timestamp {timestamp}")
if args.test_readwrite:
# ==============================
# === Test simple read/write ===
# ==============================
print("<--- Test simple read/write --->")
print("Testing read/write to addresses...")
test_val = 0x2
print(f"Broadcasting {test_val=} to CLSel in-pixel registers")
ETROC2.wr_reg('CLSel', test_val, broadcast=True)
assert ETROC2.rd_reg('CLSel', row=2, col=3) == test_val, "Did not read back the expected value"
print("Test passed.\n")
test_val = 2**8 + 2**5
print(f"Broadcasting {test_val=} to DAC in-pixel registers")
ETROC2.wr_reg('DAC', test_val, broadcast=True)
assert ETROC2.rd_reg('DAC', row=5, col=4) == test_val, "Did not read back the expected value"
print("Test passed.\n")
test_val = 2**11 + 2**5
print(f"Trying to broadcast too large value {test_val=} to DAC in-pixel registers")
try:
ETROC2.wr_reg('DAC', test_val, broadcast=True)
raise NotImplementedError("Test failed.")
except RuntimeError:
print("Succesfully failed, as expected.")
pass
print("Test passed.\n")
test_val = 700.25
print(f"Trying to set the threshold to {test_val=}mV")
ETROC2.set_Vth_mV(test_val)
read_val = ETROC2.get_Vth_mV(row=4, col=5)
if abs(read_val-test_val)>ETROC2.DAC_step:
raise RuntimeError("Returned discriminator threshold is off.")
else:
print(f"Threshold is currently set to {read_val=} mV")
print("Test passed.\n")
elif args.multi:
from tamalero.FIFO import FIFO
from tamalero.DataFrame import DataFrame
df = DataFrame()
kcu = get_kcu(args.kcu, control_hub=True, host=args.host, verbose=False)
if (kcu == 0):
# if not basic connection was established the get_kcu function returns 0
# this would cause the RB init to fail.
sys.exit(1)
rb_0 = ReadoutBoard(int(args.rb), kcu=kcu, config=args.configuration)
data = 0xabcd1234
kcu.write_node("LOOPBACK.LOOPBACK", data)
if (data != kcu.read_node("LOOPBACK.LOOPBACK")):
print("No communications with KCU105... quitting")
sys.exit(1)
fifo = FIFO(rb=rb_0)
fifo.send_l1a(1)
fifo.reset()
from tamalero.Module import Module
print("\n - Getting modules")
modules = []
connected_modules = []
for i in [1,2,3]:
# FIXME we might want to hard reset all ETROCs at this point?
moduleid = int(args.moduleid) if i==int(args.module) else (i+200) # NOTE: at some point we should also include the RB number, e.g. (rb << 4) | (module)
m_tmp = Module(rb=rb_0, i=i, enable_power_board=args.enable_power_board, moduleid = moduleid)
modules.append(m_tmp)
if m_tmp.ETROCs[ietroc].is_connected(): # NOTE assume that module is connected if first ETROC is connected
connected_modules.append(i)
for e_tmp in m_tmp.ETROCs:
if args.hard_reset:
print(f"Running hard reset and default config on module {i}")
e_tmp.reset(hard=True)
e_tmp.default_config()
time.sleep(1.1)
#e_tmp.default_config()
#
print("Setting ETROCs into workMode 0")
e_tmp.wr_reg("workMode", 0, broadcast=True)
time.sleep(0.1)
rb_0.enable_etroc_readout()
rb_0.enable_etroc_readout(slave=True)
rb_0.reset_data_error_count()
for module in modules:
module.show_status()
fifo.reset()
print("\n - Testing fast command communication - Sending two L1As")
fifo.send_l1a(2)
for x in fifo.pretty_read(df):
print(x)
elif args.config_chip:
start_time = time.time()
kcu = get_kcu(args.kcu, control_hub=True, host=args.host, verbose=False)
if (kcu == 0):
# if not basic connection was established the get_kcu function returns 0
# this would cause the RB init to fail.
sys.exit(1)
int_time = time.time()
rb_0 = ReadoutBoard(int(args.rb), kcu=kcu, config=args.configuration)
data = 0xabcd1234
kcu.write_node("LOOPBACK.LOOPBACK", data)
if (data != kcu.read_node("LOOPBACK.LOOPBACK")):
print("No communications with KCU105... quitting")
sys.exit(1)
from tamalero.Module import Module
int2_time = time.time()
# FIXME the below code is still pretty stupid
modules = []
for i in [1,2,3]:
m_tmp = Module(rb=rb_0, i=i)
if m_tmp.ETROCs[ietroc].connected: # NOTE assume that module is connected if first ETROC is connected
modules.append(m_tmp)
end_time = time.time()
print("KCU init done in {:.2f}s".format(int_time-start_time))
print("RB init done in {:.2f}s".format(int2_time-int_time))
print("Module init done in {:.2f}s".format(end_time-int2_time)) # default config is what's slow
elif args.test_chip:
kcu = get_kcu(args.kcu, control_hub=True, host=args.host, verbose=False)
if (kcu == 0):
# if not basic connection was established the get_kcu function returns 0
# this would cause the RB init to fail.
sys.exit(1)
rb_0 = ReadoutBoard(int(args.rb), kcu=kcu, config=args.configuration)
data = 0xabcd1234
kcu.write_node("LOOPBACK.LOOPBACK", data)
if (data != kcu.read_node("LOOPBACK.LOOPBACK")):
print("No communications with KCU105... quitting")
sys.exit(1)
from tamalero.Module import Module
# FIXME the below code is still pretty stupid
modules = []
connected_modules = []
for i in [1,2,3]:
# FIXME we might want to hard reset all ETROCs at this point?
moduleid = int(args.moduleid) if i==int(args.module) else (i+200)
m_tmp = Module(rb=rb_0, i=i, enable_power_board=args.enable_power_board, moduleid = moduleid)
modules.append(m_tmp)
if m_tmp.ETROCs[ietroc].is_connected(): # NOTE assume that module is connected if first ETROC is connected
connected_modules.append(i)
for e_tmp in m_tmp.ETROCs:
if args.hard_reset:
print(f"Running hard reset and default config on module {i}")
e_tmp.reset(hard=True)
e_tmp.default_config()
time.sleep(1.1)
#e_tmp.default_config()
#
print("Setting ETROCs into workMode 0")
e_tmp.wr_reg("workMode", 0, broadcast=True)
#for i in [1,2,3]:
# m_tmp = Module(rb=rb_0, i=i, enable_power_board=args.enable_power_board)
# modules.append(m_tmp)
# if m_tmp.ETROCs[0].connected: # NOTE assume that module is connected if first ETROC is connected
# connected_modules.append(i)
print(f"Found {len(connected_modules)} connected modules")
if int(args.module) > 0:
module = int(args.module)
else:
module = connected_modules[0]
print(f"Will proceed with testing Module {module}")
print("Module status:")
modules[module-1].show_status()
etroc = modules[module-1].ETROCs[ietroc]
if args.hard_reset:
etroc.reset(hard=True)
etroc.default_config()
if args.mode == 'single':
print(f"Setting the ETROC in single port mode ('right')")
etroc.set_singlePort("right")
etroc.set_mergeTriggerData("separate")
elif args.mode == 'dual':
print(f"Setting the ETROC in dual port mode ('both')")
etroc.set_singlePort("both")
etroc.set_mergeTriggerData("merge")
#etroc = ETROC(rb=rb_0, i2c_adr=96, i2c_channel=1, elinks={0:[0,2]})
# Load a pixel mask if specified
masked_pixels = []
if args.pixel_mask:
mask = PixelMask.from_file(args.pixel_mask)
masked_pixels = mask.get_masked_pixels()
print("\n - Will apply the following pixel mask:")
mask.show()
if not args.skip_sanity_checks:
print("\n - Checking peripheral configuration:")
etroc.print_perif_conf()
print("\n - Checking peripheral status:")
etroc.print_perif_stat()
print("\n - Running pixel sanity check:")
res = etroc.pixel_sanity_check(verbose=False)
if res:
print("Passed!")
else:
print("Failed")
print("\n - Running pixel random check:")
res = etroc.pixel_random_check(verbose=False)
if res:
print("Passed!")
else:
print("Failed")
print("\n - Checking configuration for pixel (4,5):")
etroc.print_pixel_conf(row=4, col=5)
print("\n - Checking status for pixel (4,5):")
etroc.print_pixel_stat(row=4, col=5)
## pixel broadcast
print("\n - Checking pixel broadcast.")
etroc.wr_reg('workMode', 0, broadcast=True)
tmp = etroc.rd_reg('workMode', row=10, col=10)
etroc.wr_reg('workMode', 1, broadcast=True)
test0 = True
for row in range(16):
for col in range(16):
test0 &= (etroc.rd_reg('workMode', row=row, col=col) == 1)
tmp2 = etroc.rd_reg('workMode', row=10, col=10)
tmp3 = etroc.rd_reg('workMode', row=3, col=12)
etroc.wr_reg('workMode', 0, broadcast=True)
tmp4 = etroc.rd_reg('workMode', row=10, col=10)
test1 = (tmp != tmp2)
test2 = (tmp2 == tmp3)
test3 = (tmp == tmp4)
if test0 and test1 and test2 and test3:
print("Passed!")
else:
print(f"Failed: {test0=}, {test1=}, {test2=}, {test3=}")
else:
# still run sanity check but quietly
# this is needed so that we can deactivate problematic / hot pixels
res = etroc.pixel_sanity_check(verbose=False)
print("\n - Deactivating problematic / hot pixels")
etroc.deactivate_hot_pixels(pixels=masked_pixels)
# NOTE below is WIP code for tests of the actual data readout
from tamalero.FIFO import FIFO
from tamalero.DataFrame import DataFrame
df = DataFrame()
# NOTE this is for single port tests right now, where we only get elink 2
fifo = FIFO(rb=rb_0)
#fifo.select_elink(0)
#fifo.ready()
print("\n - Checking elinks")
#print("Disabling readout for all elinks but the ETROC under test")
## FIXME this is still problematic...
#rb_0.disable_etroc_readout(all=True)
#rb_0.reset_data_error_count()
##rb_0.enable_etroc_readout()
#for lpgbt in etroc.elinks:
# if lpgbt == 0:
# slave = False
# else:
# slave = True
# for link in etroc.elinks[lpgbt]:
# print(f"Enabling elink {link}, slave is {slave}")
# rb_0.enable_etroc_readout(link, slave=slave)
# #time.sleep(0.5)
# #rb_0.reset_data_error_count()
# #fifo.select_elink(link, slave)
# #fifo.ready()
# rb_0.rerun_bitslip()
# time.sleep(1.5)
# rb_0.reset_data_error_count()
# stat = rb_0.get_link_status(link, slave=slave, verbose=False)
# if stat:
# rb_0.get_link_status(link, slave=slave)
# start_time = time.time()
# while not stat:
# #rb_0.disable_etroc_readout(link, slave=slave)
# rb_0.enable_etroc_readout(link, slave=slave)
# #time.sleep(0.5)
# #time.sleep(0.1)
# #rb_0.reset_data_error_count()
# #fifo.select_elink(link, slave)
# #fifo.ready()
# rb_0.rerun_bitslip()
# time.sleep(1.5)
# rb_0.reset_data_error_count()
# stat = rb_0.get_link_status(link, slave=slave, verbose=False
# )
# if stat:
# rb_0.get_link_status(link, slave=slave)
# break
# if time.time() - start_time > 2:
# print('Link not good, but continuing')
# rb_0.get_link_status(link, slave=slave)
# break
## Bloc below to be retired
## Keeping it for one more iteration
#locked = kcu.read_node(f"READOUT_BOARD_0.ETROC_LOCKED").value()
#if (locked & 0b101) == 5:
# print(green('Both elinks (0 and 2) are locked.'))
#elif (locked & 1) == 1:
# print(yellow('Only elink 0 is locked.'))
#elif (locked & 4) == 4:
# print(yellow('Only elink 2 is locked.'))
#else:
# print(red('No elink is locked.'))
# The block below is a bit unclear
# The first FIFO read (fifo.pretty_read(df)) will always fail,
# but with a reset afterwards it should get in a stable state
start_time = time.time()
while True:
try:
fifo.reset()
fifo.send_l1a(10)
_ = fifo.pretty_read(df)
fifo.reset()
break
except:
print("Initial (re)set of FIFO.")
if time.time() - start_time > 1:
print("FIFO state is unexpected.")
raise
etroc.reset()
print("\n - Getting internal test data")
etroc.wr_reg("DAC", 0, broadcast=True) # make sure that we're not additionally picking up any noise
etroc.wr_reg("selfTestOccupancy", 2, broadcast=True)
if not args.partial:
etroc.wr_reg("workMode", 0x1, broadcast=True)
else:
etroc.wr_reg("selfTestOccupancy", 70, broadcast=True)
etroc.wr_reg("workMode", 0x0, broadcast=True)
## center pixels
#etroc.wr_reg("workMode", 0x1, row=15, col=7)
etroc.wr_reg("workMode", 0x1, row=7, col=7)
etroc.wr_reg("workMode", 0x1, row=7, col=8)
etroc.wr_reg("workMode", 0x1, row=8, col=7)
etroc.wr_reg("workMode", 0x1, row=8, col=8)
# corner pixels
etroc.wr_reg("workMode", 0x1, row=0, col=0)
etroc.wr_reg("workMode", 0x1, row=15, col=15)
etroc.wr_reg("workMode", 0x1, row=0, col=15)
etroc.wr_reg("workMode", 0x1, row=15, col=0)
# edge pixels
etroc.wr_reg("workMode", 0x1, row=7, col=0)
etroc.wr_reg("workMode", 0x1, row=8, col=0)
etroc.wr_reg("workMode", 0x1, row=0, col=7)
etroc.wr_reg("workMode", 0x1, row=0, col=8)
etroc.wr_reg("workMode", 0x1, row=7, col=15)
etroc.wr_reg("workMode", 0x1, row=8, col=15)
etroc.wr_reg("workMode", 0x1, row=15, col=7)
etroc.wr_reg("workMode", 0x1, row=15, col=8)
etroc.deactivate_hot_pixels(pixels=masked_pixels)
etroc.wr_reg("onChipL1AConf", 0x2) # NOTE: internal L1A is around 1MHz, so we're only turning this on for the shortest amount of time.
etroc.wr_reg("onChipL1AConf", 0x0)
test_data = []
while fifo.get_occupancy() > 0:
test_data += fifo.pretty_read(df)
import hist
import matplotlib.pyplot as plt
import mplhep as hep
plt.style.use(hep.style.CMS)
hits_total = np.zeros((16,16))
row_axis = hist.axis.Regular(16, -0.5, 15.5, name="row", label="row")
col_axis = hist.axis.Regular(16, -0.5, 15.5, name="col", label="col")
hit_matrix = hist.Hist(col_axis,row_axis)
n_events_total = 0
n_events_hit = 0
n_events_err = 0
for d in test_data:
if d[0] == 'trailer':
n_events_total += 1
if d[1]['hits'] > 0:
n_events_hit += 1
if d[0] == 'data':
hit_matrix.fill(row=d[1]['row_id'], col=d[1]['col_id'])
hits_total[d[1]['row_id']][d[1]['col_id']] += 1
try:
if d[1]['row_id'] != d[1]['row_id2']:
print("Unpacking error in row ID")
n_events_err += 1
except KeyError:
print("Unpacking error in row ID")
n_events_err += 1
try:
if d[1]['col_id'] != d[1]['col_id2']:
print("Unpacking error in col ID")
n_events_err += 1
except KeyError:
print("Unpacking error in col ID")
n_events_err += 1
try:
if d[1]['test_pattern'] != 0xaa:
print(f"Unpacking error in test pattern, expected 0xAA but got {d[1]['test_pattern']=}")
n_events_err += 1
except KeyError:
print(f"Unpacking error in test pattern: didn't find a test pattern!")
n_events_err += 1
print(f"Got number of total events {n_events_total=}")
print(f"Events with at least one hit {n_events_hit=}")
print(f"Events with some error in data unpacking {n_events_err=}")
fig, ax = plt.subplots(1,1,figsize=(7,7))
hit_matrix.plot2d(
ax=ax,
)
ax.set_ylabel(r'$Row$')
ax.set_xlabel(r'$Column$')
hep.cms.label(
"ETL Preliminary",
data=True,
lumi='0',
com=0,
loc=0,
ax=ax,
fontsize=15,
)
name = 'hit_matrix_internal_test_pattern'
fig.savefig(os.path.join(result_dir, f"{name}.pdf"))
fig.savefig(os.path.join(result_dir, f"{name}.png"))
fifo.reset()
print("\n - Testing fast command communication - Sending two L1As")
fifo.send_l1a(2)
for x in fifo.pretty_read(df):
print(x)
#etroc.QInj_unset(broadcast=True)
fifo.reset()
if not args.partial:
print("Will use workMode 1 to get some occupancy (no noise or charge injection)")
etroc.wr_reg("workMode", 0x1, broadcast=True) # this overwrites disDataReadout!
etroc.deactivate_hot_pixels(pixels=masked_pixels)
#etroc.deactivate_hot_pixels(pixels=[(i,1) for i in range(16)])
for j in range(1):
# One go is enough, but can run through this loop many times if there's any issue
# with FIFO / data readout at any point
print(j)
### Another occupancy map
i = 0
occupancy = 0
print("\n - Will send L1As until FIFO is full.")
#etroc.QInj_set(30, 0, row=3, col=3, broadcast=False)
start_time = time.time()
with tqdm(total=65536, bar_format='{l_bar}{bar:20}{r_bar}{bar:-20b}') as pbar:
while not fifo.is_full():
fifo.send_l1a()
#fifo.send_QInj(delay=j)
#fifo.send_QInj()
i +=1
if i%100 == 0:
tmp = fifo.get_occupancy()
pbar.update(tmp-occupancy)
occupancy = tmp
#if time.time()-start_time>5:
# print("Time out")
# break
test_data = []
while fifo.get_occupancy() > 0:
test_data += fifo.pretty_read(df)
hits_total = np.zeros((16,16))
hit_matrix = hist.Hist(col_axis,row_axis)
n_events_total = 0
n_events_hit = 0
for d in test_data:
if d[0] == 'trailer':
n_events_total += 1
if d[1]['hits'] > 0:
n_events_hit += 1
if d[0] == 'data':
hit_matrix.fill(row=d[1]['row_id'], col=d[1]['col_id'])
hits_total[d[1]['row_id']][d[1]['col_id']] += 1
# NOTE could do some CRC check.
print(f"Got number of total events {n_events_total=}")
print(f"Events with at least one hit {n_events_hit=}")
fig, ax = plt.subplots(1,1,figsize=(7,7))
hit_matrix.plot2d(
ax=ax,
)
ax.set_ylabel(r'$Row$')
ax.set_xlabel(r'$Column$')
hep.cms.label(
"ETL Preliminary",
data=True,
lumi='0',
com=0,
loc=0,
ax=ax,
fontsize=15,
)
name = 'hit_matrix_external_L1A'
fig.savefig(os.path.join(result_dir, "{}.pdf".format(name)))
fig.savefig(os.path.join(result_dir, "{}.png".format(name)))
print("\nOccupancy vs column:")
hit_matrix[{"row":sum}].show(columns=100)
print("\nOccupancy vs row:")
hit_matrix[{"col":sum}].show(columns=100)
# Set the chip back into well-defined workMode 0
etroc.wr_reg("workMode", 0x0, broadcast=True)
if args.threshold == 'auto':
# using broadcast.
# NOTE: not working in ETROC2, so this part is currently being skipped
if False:
print ("Using auto-threshold calibration with broadcast")
baseline, noise_width = etroc.auto_threshold_scan(broadcast=True)
fig, ax = plt.subplots(1,1,figsize=(7,7))
cax = ax.matshow(baseline)
ax.set_ylabel(r'$Row$')
ax.set_xlabel(r'$Column$')
fig.colorbar(cax,ax=ax)
name = 'baseline_auto_broadcast'
fig.savefig(os.path.join(plot_dir, "{}.pdf".format(name)))
fig.savefig(os.path.join(plot_dir, "{}.png".format(name)))
fig, ax = plt.subplots(1,1,figsize=(7,7))
cax = ax.matshow(noise_width)
ax.set_ylabel(r'$Row$')
ax.set_xlabel(r'$Column$')
fig.colorbar(cax,ax=ax)
name = 'noisewidth_auto_broadcast'
fig.savefig(os.path.join(plot_dir, "{}.pdf".format(name)))
fig.savefig(os.path.join(plot_dir, "{}.png".format(name)))
# not using broadcast
print ("\n - Using auto-threshold calibration for individual pixels")
print ("Info: if progress is slow, probably most pixel threshold calibrations time out because of high noise levels.")
baseline = np.empty([16, 16])
noise_width = np.empty([16, 16])
#pixel = 0
with tqdm(total=256, bar_format='{l_bar}{bar:20}{r_bar}{bar:-20b}') as pbar:
for pixel in range(256):
row = pixel & 0xF
col = (pixel & 0xF0) >> 4
#print(pixel, row, col)
baseline[row][col], noise_width[row][col] = etroc.auto_threshold_scan(row=row, col=col, broadcast=False)
#print(pixel)
pbar.update()
#pbar.close()
#pixel += 1
#for i, j in pixels: in range(16):
# for j in range(16):
print ("Done with threshold scan")
fig, ax = plt.subplots(1,1,figsize=(7,7))
cax = ax.matshow(baseline)
ax.set_ylabel(r'$Row$')
ax.set_xlabel(r'$Column$')
fig.colorbar(cax,ax=ax)
name = 'baseline_auto_individual'
fig.savefig(os.path.join(result_dir, "{}.pdf".format(name)))
fig.savefig(os.path.join(result_dir, "{}.png".format(name)))
fig, ax = plt.subplots(1,1,figsize=(7,7))
cax = ax.matshow(noise_width)
ax.set_ylabel(r'$Row$')
ax.set_xlabel(r'$Column$')
fig.colorbar(cax,ax=ax)
name = 'noisewidth_auto_individual'
fig.savefig(os.path.join(result_dir, "{}.pdf".format(name)))
fig.savefig(os.path.join(result_dir, "{}.png".format(name)))
with open(f'{result_dir}/thresholds.yaml', 'w') as f:
dump((baseline+noise_width).tolist(), f)
with open(f'{result_dir}/baseline.yaml', 'w') as f:
dump((baseline).tolist(), f)
with open(f'{result_dir}/noise_width.yaml', 'w') as f:
dump((noise_width).tolist(), f)
elif args.threshold == "manual":
# Prescanning a random pixel to get an idea of the threshold
row = int(args.row)
col = int(args.col)
elink, slave = etroc.get_elink_for_pixel(row, col)
rb_0.reset_data_error_count()
print("\n - Running simple threshold scan on single pixel")
print(f"Found this pixel on elink {elink}, lpGBT is servant: {slave}")
vth = []
count = []
#etroc.reset(hard=True)
#etroc.default_config()
rb_0.get_link_status(elink, slave=slave)
print("Coarse scan to find the peak location")
first_val = 1023
for i in range(0, 1000, 3):
etroc.wr_reg("DAC", i, row=row, col=col)
fifo.send_l1a(2000)
vth.append(i)
data_cnt = rb_0.read_data_count(elink, slave=slave)
count.append(data_cnt)
if data_cnt > 0:
print(i, data_cnt)
first_val = i
rb_0.reset_data_error_count()
if i > (first_val + 10):
# break the loop early because this scan is sloooow
print("I've seen enough, breaking coarse scan.")
break
vth_a = np.array(vth)
count_a = np.array(count)
vth_max = vth_a[np.argmax(count_a)]
print(f"Found maximum count at DAC setting vth_max={vth_max}")
### threshold scan draft
dac_min = max(0, vth_max - 75) # don't run into negatives!
dac_max = vth_max + 75
vth_scan_data = vth_scan(
etroc,
vth_min = dac_min,
vth_max = dac_max,
decimal = True,
fifo = fifo,
absolute = True,
)
vth_axis = np.array(vth_scan_data[0])
hit_rate = np.array(vth_scan_data[1])
N_pix = len(hit_rate) # total # of pixels
N_pix_w = int(round(np.sqrt(N_pix))) # N_pix in NxN layout
max_indices = np.argmax(hit_rate, axis=1)
maximums = vth_axis[max_indices]
max_matrix = np.empty([N_pix_w, N_pix_w])
noise_matrix = np.empty([N_pix_w, N_pix_w])
threshold_matrix = np.empty([N_pix_w, N_pix_w])
rawout = {vth_axis[i]:hit_rate.T[i].tolist() for i in range(len(vth_axis))}
with open(out_dir + '/manual_thresh_scan_data.json', 'w') as f:
json.dump(rawout, f)
# for pix in range(N_pix):
# plt.plot(vth_axis[hit_rate[pix] > 0], hit_rate[pix][hit_rate[pix] > 0])
# plt.savefig(f"./hit_rate/hit_rate_{pix}.png")
# plt.close()
for pix in range(N_pix):
r, c = fromPixNum(pix, N_pix_w)
max_matrix[r][c] = maximums[pix]
noise_matrix[r][c] = np.size(np.nonzero(hit_rate[pix]))
max_value = vth_axis[hit_rate[pix]==max(hit_rate[pix])]
if isinstance(max_value, np.ndarray):
max_value = max_value[-1]
zero_dac_values = vth_axis[((vth_axis>(max_value)) & (hit_rate[pix]==0))]
if len(zero_dac_values)>0:
threshold_matrix[r][c] = zero_dac_values[0] + 2
else:
threshold_matrix[r][c] = dac_max + 2
# 2D histogram of the mean
# this is based on the code for automatic sigmoid fits
# for software emulator data below
fig, ax = plt.subplots(2,1, figsize=(15,15))
ax[0].set_title("Peak values of threshold scan")
ax[1].set_title("Noise width of threshold scan")
cax1 = ax[0].matshow(max_matrix)
cax2 = ax[1].matshow(noise_matrix)
fig.colorbar(cax1,ax=ax[0])
fig.colorbar(cax2,ax=ax[1])
ax[0].set_xticks(np.arange(N_pix_w))
ax[0].set_yticks(np.arange(N_pix_w))
ax[1].set_xticks(np.arange(N_pix_w))
ax[1].set_yticks(np.arange(N_pix_w))
for i in range(N_pix_w):
for j in range(N_pix_w):
text = ax[0].text(j, i, int(max_matrix[i,j]),
ha="center", va="center", color="w", fontsize="xx-small")
text1 = ax[1].text(j, i, int(noise_matrix[i,j]),
ha="center", va="center", color="w", fontsize="xx-small")
fig.savefig(f'{result_dir}/peak_and_noiseWidth_thresholds.png')
plt.show()
plt.close(fig)
del fig, ax
fig, ax = plt.subplots()
plt.title("Thresholds from manual scan")
cax = ax.matshow(threshold_matrix)
fig.colorbar(cax)
ax.set_xticks(np.arange(N_pix_w))
ax.set_yticks(np.arange(N_pix_w))
for i in range(N_pix_w):
for j in range(N_pix_w):
text = ax.text(j, i, int(threshold_matrix[i,j]),
ha="center", va="center", color="w", fontsize="xx-small")
ax.set_xlabel("Column")
ax.set_ylabel("Row")
fig.savefig(f'{result_dir}/thresholds.png')
plt.show()
plt.close(fig)
del fig, ax
with open(f'{result_dir}/thresholds.yaml', 'w') as f:
dump(threshold_matrix.tolist(), f)
with open(f'{result_dir}/baseline.yaml', 'w') as f:
dump(max_matrix.tolist(), f)
with open(f'{result_dir}/noise_width.yaml', 'w') as f:
dump(noise_matrix.tolist(), f)
else:
print(f"Trying to load tresholds from the following file: {args.threshold}")
with open(args.threshold, 'r') as f:
threshold_matrix = load(f)
for row in range(16):
for col in range(16):
etroc.wr_reg('DAC', int(threshold_matrix[row][col]), row=row, col=col)
if args.pixelscan == 'simple':
row = 4
col = 3
elink, slave = etroc.get_elink_for_pixel(row, col)
rb_0.reset_data_error_count()
print("\n - Running simple threshold scan on single pixel")
vth = []
count = []
etroc.reset(hard=True)
etroc.default_config()
print("Coarse scan to find the peak location")
for i in range(0, 1000, 5):
# this could use a tqdm
etroc.wr_reg("DAC", i, row=row, col=col)
fifo.send_l1a(2000)
vth.append(i)
count.append(rb_0.read_data_count(elink, slave=slave))
print(i, rb_0.read_data_count(elink, slave=slave))
rb_0.reset_data_error_count()
vth_a = np.array(vth)
count_a = np.array(count)
vth_max = vth_a[np.argmax(count_a)]
print(f"Found maximum count at DAC setting vth_max={vth_max}")