-
Notifications
You must be signed in to change notification settings - Fork 0
/
start_gui
executable file
·1714 lines (1321 loc) · 73.9 KB
/
start_gui
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
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import GdkPixbuf
from gi.repository import Gdk
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import GObject
import sys
import os
import subprocess
import signal
import os.path
from collections import Counter
from time import sleep, time
import csv
from petsys import daqd
from fcntl import fcntl, F_GETFL, F_SETFL
from os import O_NONBLOCK, read
from matplotlib.backends.backend_gtk3agg import (FigureCanvasGTK3Agg as FigureCanvas)
#from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo as FigureCanvas
#import matplotlib
#matplotlib.use('GTK3Cairo')
#import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import numpy as np
class GUI:
def __init__ (self):
self.builder = Gtk.Builder()
self.builder.add_from_file('gui/gui_layout.glade')
self.MainWindow = self.builder.get_object("MainWindow")
self.processWindow = self.builder.get_object("executeWindow")
self.readTempWindow = self.builder.get_object("readTempWindow")
self.readTempPlotWindow = self.builder.get_object("readTempPlotWindow")
self.builder.connect_signals(self)
self.__daqd_switch_handle_set = False
self.__daqdPid = None
self.__process = None
self.__temperatureProcess = None
self.tempPlot = None
self.canvas = None
self.__terminalPid = None
self.__workingFolder = None
self.__febdTopology = []
self.__hasClockTrigger = False
self.__fem_switch_handle_set = False
self.__bias_switch_handle_set = False
self.__scroll = True
self.__usedStopButton = False
self.__usedTempStopButton = False
self.__tempLogFileName = None
self.__initialiseTempPlot = False
self.hasSensorInfo = False
def on_executeStopButton_clicked(self, button):
if self.__process is not None:
if self.show_confirmation_dialog("","Stop the process?", self.processWindow):
self.__usedStopButton = True
os.killpg(os.getpgid(self.__process.pid), signal.SIGTERM)
return True
def on_scrollButton_toggled(self, button):
isActive = self.builder.get_object("executeScrollButton").get_active()
if isActive:
self.__scroll = True
else:
self.__scroll = False
def execute(self,command, processName ="", message1="", message2=""):
self.__usedStopButton = False
self.__process = subprocess.Popen(command, shell=True, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid)
flags = fcntl(self.__process.stdout, F_GETFL) # get current p.stdout flags
fcntl(self.__process.stdout, F_SETFL, flags | O_NONBLOCK)
flags = fcntl(self.__process.stderr, F_GETFL) # get current p.stdout flags
fcntl(self.__process.stderr, F_SETFL, flags | O_NONBLOCK)
# turn off sensitive property of all widgets that are not on the execute process window
for widget in self.builder.get_objects():
if widget.find_property("sensitive") is not None:
if ("execute" in Gtk.Buildable.get_name(widget)) or ("readTemp" in Gtk.Buildable.get_name(widget)):
widget.set_sensitive(True)
else:
widget.set_sensitive(False)
self.builder.get_object("executeScrollButton").set_sensitive(True)
self.builder.get_object("executeStopButton").set_sensitive(True)
self.processWindow.set_title("%s (running)" % processName)
self.processWindow.show()
self.builder.get_object("executeSpinner").start()
GLib.io_add_watch(self.__process.stdout, # file descriptor
GLib.IO_IN, # condition
self.write_to_textview ) # callback
GLib.io_add_watch(self.__process.stderr, # file descriptor
GLib.IO_IN, # condition
self.write_to_textview ) # callback
data = [processName, message1, message2]
self.timeout_id = GLib.timeout_add(1000, self.check_if_finished, data)
def read_temperature(self,command, processName ="", message1="", message2=""):
self.__usedTempStopButton = False
self.__temperatureProcess = subprocess.Popen(command, shell=True, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid)
flags = fcntl(self.__temperatureProcess.stdout, F_GETFL) # get current p.stdout flags
fcntl(self.__temperatureProcess.stdout, F_SETFL, flags | O_NONBLOCK)
flags = fcntl(self.__temperatureProcess.stderr, F_GETFL) # get current p.stdout flags
fcntl(self.__temperatureProcess.stderr, F_SETFL, flags | O_NONBLOCK)
self.readTempWindow.set_title("Read Temperature Sensors (running)")
#self.readTempWindow.show()
self.builder.get_object("readTempSpinner").start()
GLib.io_add_watch(self.__temperatureProcess.stdout, # file descriptor
GLib.IO_IN, # condition
self.write_to_textview_temp ) # callback
GLib.io_add_watch(self.__temperatureProcess.stderr, # file descriptor
GLib.IO_IN, # condition
self.write_to_textview_temp ) # callback
data = [processName, message1, message2]
self.timeout_id = GLib.timeout_add(1000, self.check_if_temp_finished, data)
def check_if_finished(self, data):
message1 = data[1]
message2 = data[2]
if self.__process is None:
return True
if self.__process.poll() is not None:
self.builder.get_object("readTempSpinner").stop()
GLib.source_remove(self.timeout_id)
# Make all widgets sensitive again...
for widget in self.builder.get_objects():
if widget.find_property("sensitive") is not None:
widget.set_sensitive(True)
self.builder.get_object("executeScrollButton").set_sensitive(False)
self.builder.get_object("executeStopButton").set_sensitive(False)
if not self.__usedStopButton:
self.processWindow.set_title("%s (finished)" % data[0])
else:
self.processWindow.set_title("%s (stopped by user)" % data[0])
#comboBox = self.builder.get_object("processingConvertBoxOptions")
#self.on_processingConvertBoxOptions_changed(comboBox)
textView = self.builder.get_object("executeTextView")
self.scroll_to_end(textView)
buf = textView.get_buffer()
buf.insert_at_cursor("\n\n")
self.__process = None
if message1 != "" and not self.__usedStopButton:
self.show_info_dialog(message1, message2, self.processWindow)
return True
def check_if_temp_finished(self, data):
message1 = data[1]
message2 = data[2]
if self.__temperatureProcess is None:
return True
if self.__temperatureProcess.poll() is not None:
self.builder.get_object("readTempSpinner").stop()
if not self.__usedTempStopButton:
self.readTempWindow.set_title("%s (finished)" % data[0])
else:
self.readTempWindow.set_title("%s (stopped by user)" % data[0])
textView = self.builder.get_object("readTempTextView")
self.scroll_to_end(textView)
buf = textView.get_buffer()
buf.insert_at_cursor("\n\n")
self.__temperatureProcess = None
if message1 != "" and not self.__usedTempStopButton:
self.show_info_dialog(message1, message2, self.processWindow)
return True
def write_to_textview(self, fd, condition):
if condition == GLib.IO_IN:
char = fd.read().decode()
tview = self.builder.get_object("executeTextView")
buf = self.builder.get_object("executeTextView").get_buffer()
if "Python:: Acquired" in char:
if "\r" in char:
char = char[:-1]
nLines = buf.get_line_count()
lineIterStart = buf.get_iter_at_line_index(nLines-1,0)
lineIterEnd = buf.get_end_iter()
buf.delete(lineIterStart, lineIterEnd)
buf.place_cursor(buf.get_end_iter())
buf.insert_at_cursor(char)
if self.__scroll:
self.scroll_to_end(self.builder.get_object("executeTextView"))
return True
else:
return False
def write_to_textview_temp(self, fd, condition):
if condition == GLib.IO_IN:
char = fd.read().decode()
tview = self.builder.get_object("readTempTextView")
buf = self.builder.get_object("readTempTextView").get_buffer()
if "Python:: Acquired" in char:
if "\r" in char:
char = char[:-1]
nLines = buf.get_line_count()
lineIterStart = buf.get_iter_at_line_index(nLines-1,0)
lineIterEnd = buf.get_end_iter()
buf.delete(lineIterStart, lineIterEnd)
buf.place_cursor(buf.get_end_iter())
buf.insert_at_cursor(char)
if self.__scroll:
self.scroll_to_end(self.builder.get_object("readTempTextView"))
return True
else:
return False
def scroll_to_end(self,textview):
i = textview.props.buffer.get_end_iter()
mark = textview.props.buffer.get_insert()
textview.props.buffer.place_cursor(i)
textview.scroll_to_mark(mark, 0.0, True, 0.0, 1.0)
def on_MainWindow_delete_event(self, MainWindow, data):
if self.show_confirmation_dialog("This will close any running process","Exit?"):
if self.__process is not None:
os.killpg(os.getpgid(self.__process.pid), signal.SIGTERM)
if self.__daqdPid != None and self.is_daqd_running():
os.kill(int(self.__daqdPid), signal.SIGTERM)
sleep(0.3)
if self.__terminalPid != None:
os.kill(int(self.__terminalPid), signal.SIGKILL)
Gtk.main_quit()
return True
def on_executeWindow_delete_event(self, window, data):
if self.__process is not None:
if self.show_confirmation_dialog("Closing window will stop the running process. Proceed?", "", self.processWindow):
os.killpg(os.getpgid(self.__process.pid), signal.SIGTERM)
window.hide()
else:
if self.show_confirmation_dialog("","Close window?", self.processWindow):
window.hide()
return True
def on_readTempWindow_delete_event(self, window, data):
if self.__temperatureProcess is not None:
if self.show_confirmation_dialog("Closing window will stop temperature monitoring. Proceed?", "", self.readTempWindow):
os.killpg(os.getpgid(self.__temperatureProcess.pid), signal.SIGTERM)
window.hide()
else:
if self.show_confirmation_dialog("","Close window?", self.readTempWindow):
window.hide()
return True
# Main menu handler functions
def on_menuFileQuit_activate(self, menuFileQuit): # quit with Quit button
if self.show_confirmation_dialog("This will close any running process","Exit?"):
if self.__process is not None:
os.killpg(os.getpgid(self.__process.pid), signal.SIGTERM)
if self.__daqdPid != None and self.is_daqd_running():
os.kill(int(self.__daqdPid), signal.SIGTERM)
sleep(0.3)
if self.__terminalPid != None:
os.kill(int(self.__terminalPid), signal.SIGKILL)
Gtk.main_quit()
def on_menuHelpAbout_activate(self, menuHelpAbout):
about = Gtk.AboutDialog.new()
about.set_transient_for(self.MainWindow)
# about.set_version("v2019.03.07")
about.set_logo(GdkPixbuf.Pixbuf.new_from_file("gui/logo_PETsys2.png"))
about.set_website("http://www.petsyselectronics.com")
about.set_website_label("petsyselectronics.com")
about.set_program_name("TOFPET2 Data Acquisition Software")
about.set_authors(["Ricardo Bugalho","Luis Ferramacho"])
about.show()
def on_menuHelpDoc_activate(self, menuHelpDoc):
Gtk.show_uri_on_window(None, "https://drive.google.com/drive/u/0/folders/0BxJ0aPS8qNAxZmtLVEdBWUdicWs?ogsrc=32",0)
#Daqd section handler function
def on_daqdSwitch_state_set(self, daqdSwitch, isON):
isGBE = self.builder.get_object("radioButtonGBE").get_active()
if isGBE:
command = "./daqd --socket-name /tmp/d.sock --daq-type GBE"
else:
command = "./daqd --socket-name /tmp/d.sock --daq-type PFP_KX7"
# command2 = "gnome-terminal -e 'bash -c \"%s; exec bash\"'" % command
command2 = "xterm -hold -e \"%s\"" % command
if isON:
# Check if there are other instances of daqd
if not self.__daqd_switch_handle_set:
if self.is_daqd_running():
daqdPids = subprocess.check_output(["pidof", "daqd"])
pidsToKill = daqdPids.decode("ascii").split(" ")
if self.show_confirmation_dialog("There are other instances of daqd running in the system. Kill them and open a new instance?"):
for pid in pidsToKill:
os.kill(int(pid), signal.SIGTERM)
else:
self.__daqdPid = pidsToKill[0]
return
#Check if socket and shm files exist
if os.path.exists('/tmp/d.sock'):
subprocess.call("rm /tmp/d.sock", shell=True)
if os.path.exists('/dev/shm/daqd_shm'):
subprocess.call("rm /dev/shm/daqd_shm", shell=True)
#Open ./daqd
daqdOpenPipe = subprocess.Popen(command2, shell=True)
sleep(1.5)
# Check if daqd opened successfully and store pids of processes
if self.is_daqd_running():
daqdPid = subprocess.check_output(["pidof", "daqd"])
self.__daqdPid = daqdPid.decode("ascii").split(" ")[0]
else:
self.show_error_dialog("daqd server was unable to start correctly. Please check error message in the terminal and retry")
self.__daqdPid = None
self.__daqd_switch_handle_set = True
daqdSwitch.set_active(False)
self.__daqd_switch_handle_set = False
return True
terminalPid = subprocess.check_output(["pidof", "xterm"])
terminalPids = terminalPid.decode("ascii").split(" ")
for pid in terminalPids:
pid2 = pid.strip('\n')
command3 = "ps -o etime= -p \"%s\"" % pid2
time = subprocess.check_output(command3, shell=True )
time2 = time.decode("ascii").strip('\n')
if time2.count(':') == 1 and time2.count('-')==0:
timeSec = sum(x * int(t) for x, t in zip([60, 1], time2.split(":")))
elif time2.count(':') == 2 and time2.count('-') ==0:
timeSec = sum(x * int(t) for x, t in zip([3600,60, 1], time2.split(":")))
else:
continue
if timeSec < 5:
self.__terminalPid = pid2
else:
if not self.__daqd_switch_handle_set:
isDaqdPresent = subprocess.call(["pidof", "daqd"], stdout= subprocess.PIPE) == 0
if self.__daqdPid != None and self.is_daqd_running():
os.kill(int(self.__daqdPid), signal.SIGTERM)
sleep(0.3)
if self.__terminalPid != None:
os.kill(int(self.__terminalPid), signal.SIGKILL)
def is_daqd_running(self):
isDaqdPresent = subprocess.call(["pidof", "daqd"], stdout= subprocess.PIPE) == 0
return isDaqdPresent
def on_dataFolderChooseButton_clicked(self, dataFolderChooseButton):
folderChooser = self.builder.get_object("dataFolderChooser")
folderEntry = self.builder.get_object("dataFolderEntry")
folderChooser.set_default_size(1200, 400)
response = folderChooser.run()
if response == Gtk.ResponseType.OK:
folderEntry.set_text(folderChooser.get_filename())
self.__workingFolder = folderChooser.get_filename()+"/"
self.check_bias_settings_file()
self.check_disc_settings_file()
elif response == Gtk.ResponseType.CANCEL:
folderChooser.hide()
folderChooser.hide()
def check_bias_settings_file(self):
filename = self.__workingFolder + "bias_settings.tsv"
if not os.path.exists(filename):
return
# Check if bias settings file exists and is not custom made (all 4 last collumns have equal values)
offset = []
prebd = []
bd = []
ov = []
with open(filename) as csvfile:
reader = csv.DictReader(csvfile, delimiter='\t')
for row in reader:
offset.append(row['Offset'])
prebd.append(row['Pre-breakdown'])
bd.append(row['Breakdown'])
ov.append(row['Overvoltage'])
if (len(set(offset)) == 1 and len(set(prebd)) == 1 and len(set(bd)) == 1 and len(set(ov)) == 1):
self.builder.get_object("biasSpinButton1").set_value(float(prebd[0]))
self.builder.get_object("biasSpinButton2").set_value(float(bd[0]))
self.builder.get_object("biasSpinButton3").set_value(float(ov[0]))
self.show_info_dialog("WARNING: Simple Bias Settings file detected in working folder", "Values were updated in the Bias Settings Section")
else:
self.builder.get_object("biasSpinButton1").set_value(0)
self.builder.get_object("biasSpinButton2").set_value(0)
self.builder.get_object("biasSpinButton3").set_value(0)
self.show_info_dialog("WARNING: Custom Bias Settings file detected in working folder", "Save button in Bias Settings Section can override them")
def check_disc_settings_file(self):
filename = self.__workingFolder + "disc_settings.tsv"
if not os.path.exists(filename):
return
# Check if bias settings file exists and is not custom made (all 4 last collumns have equal values)
vth_t1 = []
vth_t2 = []
vth_e = []
with open(filename) as csvfile:
reader = csv.DictReader(csvfile, delimiter='\t')
for row in reader:
vth_t1.append(row['vth_t1'])
vth_t2.append(row['vth_t2'])
vth_e.append(row['vth_e'])
if (len(set(vth_t1)) == 1 and len(set(vth_t2)) == 1 and len(set(vth_e)) == 1):
self.builder.get_object("threshSpinButton1").set_value(float(vth_t1[0]))
self.builder.get_object("threshSpinButton2").set_value(float(vth_t2[0]))
self.builder.get_object("threshSpinButton3").set_value(float(vth_e[0]))
self.show_info_dialog("WARNING: Simple Discriminator Thresholds Settings file detected in working folder", "Values were updated in the ASIC Thresholds Settings Section")
else:
self.builder.get_object("threshSpinButton1").set_value(0)
self.builder.get_object("threshSpinButton2").set_value(0)
self.builder.get_object("threshSpinButton3").set_value(0)
self.show_info_dialog("WARNING: Custom Discriminator Thresholds Settings file detected in working folder", "Caution: Save button in ASIC Thresholds Settings Section will overwrite it!")
def on_dataFolderEntry_activate(self, dataFolderEntry):
folderExists= os.path.exists(dataFolderEntry.get_text())
if not folderExists:
if self.show_confirmation_dialog("No such folder exists. Create folder?"):
subprocess.call("mkdir "+ dataFolderEntry.get_text(), shell=True)
self.__workingFolder = dataFolderEntry.get_text() + "/"
else:
return True
else:
self.__workingFolder = dataFolderEntry.get_text() + "/"
self.check_bias_settings_file()
self.check_disc_settings_file()
def on_biasApplyButton_clicked(self, biasApplyButton):
if self.__workingFolder == None:
self.show_error_dialog("Please choose a working folder.")
return
if not os.path.exists(self.__workingFolder + "config.ini"):
self.show_error_dialog("'config.ini' file not found in the working folder. Please use the detect and save button to create one.")
return
if not os.path.exists(self.__workingFolder + "bias_calibration.tsv"):
self.show_error_dialog("Bias Calibration file not detected in working folder. Please use the detect and save button in 'System Configuration' section.")
return
preBD = self.builder.get_object("biasSpinButton1").get_value()
BD = self.builder.get_object("biasSpinButton2").get_value()
OV = self.builder.get_object("biasSpinButton3").get_value()
configFile = self.__workingFolder + "config.ini"
outFile = self.__workingFolder + "bias_settings.tsv"
if os.path.exists(outFile):
if not self.show_confirmation_dialog("A Bias Settings file exists in the working folder. Overwrite?"):
return
command = "./make_simple_bias_settings_table --config %s --offset 0.75 --prebd %.2f --bd %.2f --over %.2f -o %s" % (configFile, preBD, BD, OV, outFile)
subprocess.call(command, shell=True)
self.show_info_dialog("Bias Settings saved","")
def on_biasEditButton_clicked(self, biasEditButton):
if self.__workingFolder == None:
self.show_error_dialog("Please choose a working folder.")
return
if not os.path.exists(self.__workingFolder + "bias_settings.tsv"):
self.show_error_dialog("Please use the save button before editing the bias settings file.")
appChooser = self.builder.get_object("applicationChooser")
response = appChooser.run()
if response == Gtk.ResponseType.OK:
info = appChooser.get_app_info()
biasFile = Gio.File.new_for_path(self.__workingFolder + "bias_settings.tsv")
info.launch([biasFile], None)
appChooser.hide()
def on_threshEditButton_clicked(self, threshEditButton):
if self.__workingFolder == None:
self.show_error_dialog("Please choose a working folder.")
return
if not os.path.exists(self.__workingFolder + "disc_settings.tsv"):
self.show_error_dialog("Please use the save button before editing the discriminator settings file.")
appChooser = self.builder.get_object("applicationChooser")
response = appChooser.run()
if response == Gtk.ResponseType.OK:
info = appChooser.get_app_info()
discFile = Gio.File.new_for_path(self.__workingFolder + "disc_settings.tsv")
info.launch([discFile], None)
appChooser.hide()
def on_editMapsButton_clicked(self, mapsEditButton):
if self.__workingFolder == None:
self.show_error_dialog("Please choose a working folder.")
return
if not os.path.exists(self.__workingFolder + "map_channel.tsv"):
self.show_error_dialog("Please use the detect and save button before editing the channel and trigger maps.")
appChooser = self.builder.get_object("applicationChooser")
response = appChooser.run()
if response == Gtk.ResponseType.OK:
info = appChooser.get_app_info()
file1 = Gio.File.new_for_path(self.__workingFolder + "map_channel.tsv")
file2 = Gio.File.new_for_path(self.__workingFolder + "map_trigger.tsv")
info.launch([file1, file2], None)
appChooser.hide()
def on_editConfigButton_clicked(self, mapsEditButton):
if self.__workingFolder == None:
self.show_error_dialog("Please choose a working folder.")
return
if not os.path.exists(self.__workingFolder + "config.ini"):
self.show_error_dialog("'config.ini' file not found in the working folder. Please use the detect button and save a valid configuration")
appChooser = self.builder.get_object("applicationChooser")
response = appChooser.run()
if response == Gtk.ResponseType.OK:
info = appChooser.get_app_info()
configFile = Gio.File.new_for_path(self.__workingFolder + "config.ini")
info.launch([configFile], None)
appChooser.hide()
def on_threshApplyButton_clicked(self, threshApplyButton):
if self.__workingFolder == None:
self.show_error_dialog("Please choose a working folder.")
return
if not os.path.exists(self.__workingFolder + "config.ini"):
self.show_error_dialog("'config.ini' file not found in the working folder. Please use the detect and save button to create one.")
return
if not os.path.exists(self.__workingFolder + "disc_calibration.tsv"):
self.show_error_dialog("Discriminator Calibration file not detected in working folder. Please perform ASIC calibration.")
return
vth_t1 = self.builder.get_object("threshSpinButton1").get_value()
vth_t2 = self.builder.get_object("threshSpinButton2").get_value()
vth_e = self.builder.get_object("threshSpinButton3").get_value()
configFile = self.__workingFolder + "config.ini"
outFile = self.__workingFolder + "disc_settings.tsv"
if os.path.exists(outFile):
if not self.show_confirmation_dialog("A Discriminator Threshold Settings file exists in the working folder. Overwrite?"):
return
command = "./make_simple_disc_settings_table --config %s --vth_t1 %d --vth_t2 %d --vth_e %d -o %s" % (configFile, int(vth_t1), int(vth_t2), int(vth_e), outFile)
subprocess.call(command, shell=True)
self.show_info_dialog("Threshold Settings saved","")
def on_systemDetectButton_clicked(self, systemButton):
if not self.is_daqd_running():
self.show_error_dialog("daqd communication server is not running.")
return
systemTopology = []
self.__febdTopology = []
self.__febdNumber = 0
connection = daqd.Connection()
for portID, slaveID in connection.getActiveUnits():
register0 = connection.read_config_register(portID, slaveID, 1, 0x0000)
register1 = connection.read_config_register(portID, slaveID, 1, 0x0001)
if (register0 == 1):
if (register1 == 1):
isEkit = True
else:
isEkit = False
if connection.getBiasType(portID, slaveID) == 1:
unitType = "FEB/D_64P"
else:
unitType = "FEB/D_16P"
self.__febdTopology.append([portID, slaveID, 0, unitType,""])
if (register0 == 0 and register1 == 1):
self.__hasClockTrigger = True
isEkit = False
unitType = "CLK&TRIGGER"
systemTopology.append([portID, slaveID, 0, unitType,""])
if self.__febdTopology == []:
self.show_error_dialog("No FEB/Ds detected. Please check connections and try again.")
return True
if isEkit and unitType == "FEB/D_64P":
self.show_info_dialog( "Detected Evaluation Kit"," - 1 FEB/D + Bias Mezzanine 64P\n\nCalibration file required. Opening file chooser dialog...")
if not self.choose_BiasCal_File(systemButton, 0, None):
self.show_info_dialog("System configuration not saved","")
return True
if self.show_confirmation_dialog("- 1 FEB/D + Bias Mezzanine 64P with calibration file %s\n\n Save configuration files in Working Data Folder?" % self.__febdTopology[0][4], "Evaluation Kit Configuration"):
self.saveSystemSettings()
else:
self.show_info_dialog("System configuration not saved","")
return True
elif isEkit and unitType == "FEB/D_16P":
if self.show_confirmation_dialog(" - 1 FEB/D + Bias Mezzanine 16P \n\n Save configuration files in Working Data Folder?", "Detected Evaluation Kit"):
self.saveSystemSettings()
return True
else:
topology = ""
for febd in systemTopology:
if febd[3] == "FEB/D_64P":
topology += "- FEB/D + Bias Mezzanine 64P, in DAQ port %d, slave %d\n" % (febd[0], febd[1])
self.__febdNumber += 1
elif febd[3] == "FEB/D_16P":
topology += "- FEB/D + Bias Mezzanine 16P, in DAQ port %d, slave %d\n" % (febd[0], febd[1])
self.__febdNumber += 1
else:
topology += "- Clock & Trigger in DAQ port %d, slave %d\n" % (febd[0], febd[1])
topology += "\n Opening configuration window..."
self.show_info_dialog("Detected SIPM Readout System", topology)
hBox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=20)
self.builder.add_objects_from_file("gui/gui_layout.glade", ("febdConfigDialog","febdConfigDialogBox",""))
febdConfigBox = self.builder.get_object("febdConfigDialogBox")
grid = Gtk.Grid()
febdConfigBox.pack_start(grid, True, True, 0)
label1 = Gtk.Label("portID")
label1.set_margin_right(10)
label1.set_margin_left(10)
label1.set_property("halign",3)
grid.add(label1)
label2 = Gtk.Label("slaveID")
label2.set_margin_right(10)
label2.set_margin_left(10)
label2.set_property("halign",3)
grid.attach_next_to(label2, label1, Gtk.PositionType.RIGHT, 1, 1)
if self.__hasClockTrigger:
label3 = Gtk.Label("triggerID")
label3.set_property("halign",3)
grid.attach_next_to(label3, label2, Gtk.PositionType.RIGHT, 1, 1)
if any(febd[3] == "FEB/D_64P" for febd in self.__febdTopology):
label4 = Gtk.Label("HV-DAC Calibration file")
label4.set_property("halign",3)
grid.attach_next_to(label4, label3, Gtk.PositionType.RIGHT, 2, 1)
elif any(febd[3] == "FEB/D_64P" for febd in self.__febdTopology):
label3 = Gtk.Label("HV-DAC Calibration file")
label3.set_property("halign",3)
grid.attach_next_to(label3, label2, Gtk.PositionType.RIGHT, 2, 1)
portLabelList = [0 for x in range(self.__febdNumber)]
slaveLabelList = [0 for x in range(self.__febdNumber)]
fileButtonList = [0 for x in range(self.__febdNumber)]
triggerSpinButtonList = [0 for x in range(self.__febdNumber)]
triggerSpinAdjustmentList = [0 for x in range(self.__febdNumber)]
fileEntryList = [0 for x in range(self.__febdNumber)]
for i, febd in enumerate(self.__febdTopology):
portLabelList[i] = Gtk.Label()
portLabelList[i].set_text(str(febd[0]))
slaveLabelList[i] = Gtk.Label()
slaveLabelList[i].set_text(str(febd[1]))
triggerSpinButtonList[i] = Gtk.SpinButton()
triggerSpinAdjustmentList[i] = Gtk.Adjustment(febd[2], 0, 32, 1, 1, 0)
triggerSpinButtonList[i].set_adjustment(triggerSpinAdjustmentList[i])
triggerSpinButtonList[i].set_width_chars(1)
triggerSpinButtonList[i].set_max_width_chars(2)
grid.attach(portLabelList[i], 0, i+1, 1, 1)
grid.attach(slaveLabelList[i], 1, i+1, 1, 1)
if self.__hasClockTrigger:
grid.attach(triggerSpinButtonList[i], 2, i+1, 1, 1)
if febd[3] == "FEB/D_64P":
fileEntryList[i] = Gtk.Entry()
grid.attach(fileEntryList[i], 3, i+1, 1, 1)
fileEntryList[i].set_margin_left(10)
fileEntryList[i].set_width_chars(30)
fileEntryList[i].set_max_width_chars(30)
fileButtonList[i] = Gtk.Button("Choose")
grid.attach(fileButtonList[i], 4, i+1, 1, 1)
fileButtonList[i].connect("clicked", self.choose_BiasCal_File, i, fileEntryList[i])
elif febd[3] == "FEB/D_64P":
fileEntryList[i] = Gtk.Entry()
grid.attach(fileEntryList[i], 2, i+1, 1, 1)
fileEntryList[i].set_margin_left(10)
fileEntryList[i].set_width_chars(30)
fileEntryList[i].set_max_width_chars(30)
fileButtonList[i] = Gtk.Button("Choose")
grid.attach(fileButtonList[i], 3, i+1, 1, 1)
fileButtonList[i].connect("clicked", self.choose_BiasCal_File, i, fileEntryList[i])
febdConfigBox.show_all()
febdConfigDialog = self.builder.get_object("febdConfigDialog")
febdConfigDialog.connect("response", self.validate_response2, triggerSpinButtonList)
response2 = febdConfigDialog.run()
topology = ""
for [portID,slaveID, triggerID, biasMezzType, biasCalFile] in self.__febdTopology:
if biasMezzType == "FEB/D_64P":
topology += "- FEB/D + Bias Mezzanine 64P, in DAQ port %d, slave %d, trigger %d, calibration file '%s'\n" % (portID,slaveID, triggerID, biasCalFile)
self.__febdNumber += 1
elif biasMezzType == "FEB/D_16P":
topology += "- FEB/D + Bias Mezzanine 16P, in DAQ port %d, slave %d, trigger %d\n" % (portID,slaveID, triggerID)
self.__febdNumber += 1
for febd in systemTopology:
if febd[3] == "CLK&TRIGGER":
topology += "- Clock & Trigger in DAQ port %d, slave %d\n" % (febd[0], febd[1])
topology += "\n\n\n Save configuration files in Working Data Folder?"
if self.show_confirmation_dialog(topology, "SIPM Readout System configuration"):
self.saveSystemSettings()
else:
self.show_info_dialog("System configuration not saved","")
return True
def saveSystemSettings(self):
if self.__workingFolder == None:
self.show_error_dialog("Please choose a working folder.")
return
if not os.path.exists(self.__workingFolder + "config.ini"):
subprocess.call("cp config.ini "+self.__workingFolder, shell=True)
commandMap = "./make_simple_channel_map -o " + self.__workingFolder + "map"
commandBias = "./make_bias_calibration_table -o " + self.__workingFolder + "bias_calibration.tsv"
commandMapExtension = ""
commandBiasExtension = ""
for [portID,slaveID, triggerID, biasMezzType, biasCalFile] in self.__febdTopology:
if self.__hasClockTrigger:
commandMapExtension += " --port %d --slave %d --trigger %d" % (portID,slaveID, triggerID)
else:
commandMapExtension += " --port %d --slave %d --noTriggerBoard" % (portID,slaveID)
if biasMezzType == "FEB/D_16P":
commandBiasExtension += ""
elif biasMezzType == "FEB/D_64P":
commandBiasExtension += " --port %d --slave %d --filename %s" % (portID,slaveID, biasCalFile)
subprocess.call(commandMap+commandMapExtension, shell=True)
subprocess.call(commandBias+commandBiasExtension, shell=True)
self.show_info_dialog("System configuration saved","")
def validate_response2(self, dialog, response_id, triggerSpinButtonList):
if (response_id == -6):
dialog.hide()
return True
for i in range(self.__febdNumber):
self.__febdTopology[i][2] = triggerSpinButtonList[i].get_value()
valid = self.is_FEBD_Config_Valid()
if valid:
dialog.hide()
return True
def is_FEBD_Config_Valid(self):
if self.__febdTopology == None:
return False
countPorts = Counter([(port,slave) for (port,slave,trigger,biastype,biasFile) in self.__febdTopology])
countTrigger = Counter([trigger for (port,slave,trigger,biastype,biasFile) in self.__febdTopology])
countFiles = Counter([("FEB/D_64P" == biastype, biasFile) for (port,slave,trigger,biastype,biasFile) in self.__febdTopology])
if any(count > 1 for count in countPorts.values()):
self.show_error_dialog("Each FEB/D should have a unique pair of (portID,slaveID).")
return False
if any(count > 1 for count in countTrigger.values()) and self.__hasClockTrigger:
self.show_error_dialog("Each FEB/D should have a unique triggerID value.")
return False
if (True, "") in countFiles:
self.show_error_dialog("Bias calibration file is not defined for all required FEB/Ds.")
return False
return True
def choose_BiasCal_File(self, fileButton, febdID, fileEntry):
dialog = self.builder.get_object("biasCalFileChooser")
dialog.set_transient_for(self.MainWindow)
filter_file = Gtk.FileFilter()
filter_file.set_name(".tsv files")
filter_file.add_pattern("*.tsv")
dialog.add_filter(filter_file)
response = dialog.run()
if response == Gtk.ResponseType.OK:
if fileEntry != None:
fileEntry.set_text(dialog.get_filename())
self.__febdTopology[febdID][4] = dialog.get_filename()
dialog.hide()
return response == Gtk.ResponseType.OK
def on_asicCalStartButton_clicked(self, systemCalStartButton):
if self.__workingFolder == None:
self.show_error_dialog("Please choose a working folder.")
return
if not self.is_daqd_running():
self.show_error_dialog("daqd communication server is not running.")
return
if not os.path.exists(self.__workingFolder+"bias_settings.tsv"):
self.show_error_dialog("Please save bias voltage settings (even if no SIPMs are connected).")
return
ask_cal = [True, True, True]
ask_cal[0] = self.builder.get_object("asicCalCheckButton1").get_active()
ask_cal[1] = self.builder.get_object("asicCalCheckButton2").get_active()
ask_cal[2] = self.builder.get_object("asicCalCheckButton3").get_active()
do_cal = ask_cal
for i,f in enumerate(["disc_calibration.tsv", "tdc_calibration.tsv", "qdc_calibration.tsv"]):
if os.path.exists(self.__workingFolder+f) and ask_cal[i]:
do_cal[i] = self.show_confirmation_dialog("A calibration file '%s' already exists in the working folder. Overwrite?" % (f))
if not any(do_cal):
return
confirm = True
if do_cal[1] or do_cal[2]:
confirm = self.show_confirmation_dialog("Calibration procedure can take more than 40 minutes to complete. Are you sure you want to proceed?")
if not confirm:
return True
start = time()
command = ""
if do_cal[0]:
command += "python3 -u ./acquire_threshold_calibration --config " + self.__workingFolder+"config.ini -o " + self.__workingFolder+"disc_calibration;"
command += "python3 -u ./process_threshold_calibration --config " + self.__workingFolder+"config.ini -i " + self.__workingFolder+"disc_calibration -o " + self.__workingFolder+"disc_calibration.tsv --root-file "+self.__workingFolder+"/disc_calibration.root;"
command += "python3 -u ./make_simple_disc_settings_table --config " + self.__workingFolder+"config.ini --vth_t1 20 --vth_t2 20 --vth_e 15 -o " + self.__workingFolder+"disc_settings.tsv;"
if do_cal[1]:
command += "python3 -u ./acquire_tdc_calibration --config " + self.__workingFolder+"config.ini -o " + self.__workingFolder+"tdc_calibration;"
command += "./process_tdc_calibration --config " + self.__workingFolder+"config.ini -i " + self.__workingFolder+"tdc_calibration -o "+ self.__workingFolder+"tdc_calibration;"
if do_cal[2]:
command += "python3 -u ./acquire_qdc_calibration --config " + self.__workingFolder+"config.ini -o " + self.__workingFolder+"qdc_calibration;"
command += "./process_qdc_calibration --config " + self.__workingFolder+"config.ini -i " + self.__workingFolder+"qdc_calibration -o "+ self.__workingFolder+"qdc_calibration;"
self.execute(command,"ASIC Calibration","Calibration finished", "Please check calibration summary plots.")
#end = time()
#if ((end-start) < 300 and (do_cal[1] or do_cal[2])):
# self.show_error_dialog("Calibration finished too soon! Please check terminal output.")
#else:
# self.show_info_dialog("Calibration finished","Please check calibration summary plots.")
def on_temperatureStartupButton_clicked(self, button):
if self.__workingFolder == None:
self.show_error_dialog("Please choose a working folder.")
return
if not self.is_daqd_running():
self.show_error_dialog("daqd communication server is not running.")
return
self.execute("python3 -u ./read_temperature_sensors --startup", "Check for temperature stability")
#if success:
# self.show_info_dialog("Temperature is stable","ASIC(s) temperatures stable over the last minute. System ready to acquire.")
#else:
# self.show_info_dialog("Temperature is unstable","ASIC(s) temperatures not stable over the last 10 minutes. Please ensure a stable temperature environment or proceed with measurements anyway")
def on_temperatureReadButton_clicked(self, button):
if self.__workingFolder == None:
self.show_error_dialog("Please choose a working folder.")
return
if not self.is_daqd_running():
self.show_error_dialog("daqd communication server is not running.")
return
if not self.__initialiseTempPlot:
self.fig = Figure(figsize=(50, 1), dpi=100)
self.ax = self.fig.add_subplot(111)
self.canvas = FigureCanvas(self.fig) # a Gtk.DrawingArea
self.canvas.set_size_request(300, 300)
self.ax.plot()
self.ax.set_xlabel('Time [seconds]',fontsize=10)
self.ax.set_ylabel('Temperature [degrees Celsius]',fontsize=10)
self.ax.tick_params(labelsize=10)
self.readTempPlotWindow.add_with_viewport(self.canvas)
self.__initialiseTempPlot = True
self.readTempWindow.show_all()
return True
def on_readTempLogToggleButton_clicked(self, button):
if self.builder.get_object("readTempLogToggleButton").get_active():