forked from vigoux/CALOA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.py
1708 lines (1354 loc) · 57.4 KB
/
application.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (C) 2018 Thomas Vigouroux
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from threading import RLock, Event
import traceback
from queue import Queue
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox as tMsg
import tkinter.filedialog as tkFileDialog
import BNC
import logging
import logger_init
import time
import spectro
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
from numpy import linspace
from pickle import Pickler, Unpickler
import os
# Config file to manage functionnalities
import config
# Used to send automatic bug reports
import requests
import json
import platform
# Used to open caloa documentation
import webbrowser
logger = logging.getLogger(__name__)
experiment_logger = logging.getLogger(__name__+".experiment")
main_lock = RLock()
# %% Scope_Display Object, useful to manage scope display
class Scope_Display(tk.Frame, Queue):
"""
Live scope display (right panel in normal mode)
"""
SCOPE_UPDATE_SEQUENCE = "<<SCOPEUPDATE>>"
PLOT_TYPE_2D = "2D"
PLOT_TYPE_TIME = "Time"
DEBUG_DISPLAY = "DEBUG"
def __init__(self, master, nameList):
"""
Initializes self.
Display is a queue, in wich you put the scopes what you want to draw.
To allow multi-threading, Scope_Display uses a bind to a special event.
Parameters:
- master -- The master widget where self needs to be drawn.
- nameList -- A list of 2-tuples containing as follows
(panel name, panel type id), it is used to initialize all panels
"""
#
Queue.__init__(self)
# Setting up the GUI
tk.Frame.__init__(self, master=master)
# The global NoteBook wich contains all scopes
self.globalPwnd = ttk.Notebook(master=self)
# Create the panelsDict used to store all useful objects to display
# spectrum. panelsDict is a dict containing as keys the names of all
# panels, and as values a 3-tuple containing :
# (panel axes, panel canvas, panel type id)
self.panelsDict = dict([])
for name in nameList:
figure = Figure(figsize=(6, 5.5), dpi=100) # The scope figure
plot = figure.add_subplot(111)
frame = tk.Frame(self.globalPwnd)
canvas = FigureCanvasTkAgg(figure,
master=frame) # Get the tkinter canvas
# Add the canvas to global NoteBook
self.globalPwnd.add(frame, text=name[0])
canvas.get_tk_widget().pack(fill=tk.BOTH) # Pack the canvas
self.panelsDict[name[0]] = plot, canvas, name[1]
# If developer mode is enabled, we create the debug display
# to allow us to display all spectra sent to the scope display
if config.DEVELOPER_MODE_ENABLED:
figure = Figure(figsize=(6, 5.5), dpi=100) # The scope figure
plot = figure.add_subplot(111)
frame = tk.Frame(self.globalPwnd)
# Get the tkinter canvas
canvas = FigureCanvasTkAgg(figure,
master=frame)
# Add the canvas to global NoteBook
self.globalPwnd.add(frame, text=self.DEBUG_DISPLAY)
canvas.get_tk_widget().pack(fill=tk.BOTH) # Pack the canvas
self.panelsDict[self.DEBUG_DISPLAY] =\
plot, canvas, self.PLOT_TYPE_2D
self.bind(self.SCOPE_UPDATE_SEQUENCE, self.reactUpdate)
self.globalPwnd.pack(fill=tk.BOTH) # Pack the Global Notebook
def putSpectrasAndUpdate(self, frame_id, spectras):
"""
Use this method to update a live screen.
This will send an instruction to the queue.
Spectra must be :
- if display is a 2D live display, the list of spectrum to display
as given by Spectrum_Storage[folder_id, subfolder_id, :] :
[(channel_id, spectrum), ...]
- if display is a 3D live display, the list of spectra to display
as given by Spectrum_Storage[folder_id, :, channel_id] :
[(subfolder_id, spectrum), ...]
If developer mode is enabled and a spectrum is sent to scope display
with a frame id not equal to self.DEBUG_DISPLAY, this spectrum will be
sent to debug display too.
"""
self.put((frame_id, spectras))
# If developer mode is enabled, we push the new spectrum to
# debug display.
# if config.DEVELOPER_MODE_ENABLED and frame_id != self.DEBUG_DISPLAY:
# self.put((self.DEBUG_DISPLAY, spectras))
self.event_generate(self.SCOPE_UPDATE_SEQUENCE)
def reactUpdate(self, event):
"""
This method is called whenever a new instruction is received.
"""
try: # This block asserts that we don't get too far in Queue
tp_instruction = self.get()
except Exception:
pass
else:
# Extract useful objects
plotting_area = self.panelsDict[tp_instruction[0]][0]
canvas = self.panelsDict[tp_instruction[0]][1]
plot_type = self.panelsDict[tp_instruction[0]][2]
plotting_area.clear()
plotting_area.grid()
if plot_type == self.PLOT_TYPE_2D:
# In this case we should have a list of spectrum as given
# by Spectrum_Storage[folder_id, subfolder_id, :]:
# {channel_id: spectrum, ...}
for channel_name, spectrum in tp_instruction[1].items():
plotting_area.plot(
spectrum.lambdas, spectrum.values,
label=channel_name)
plotting_area.legend()
elif self.PLOT_TYPE_TIME:
# In this case we should have a list of spectra as given by
# Spectrum_Storage[folder_id, :, channel_id] :
# {subfolder_id: spectrum, ...}
# To find some other colormap ideas :
# https://matplotlib.org/examples/color/colormaps_reference.html
# This part of the work is based on an answers to a
# StackOverflow question :
# Using colomaps to set color of line in matplotlib
values = list(tp_instruction[1].keys())
colormap = plt.get_cmap(config.COLORMAP_NAME)
cNorm = colors.Normalize(vmin=values[0], vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=colormap)
for val in values:
spectrum = tp_instruction[1][val]
colorVal = scalarMap.to_rgba(val)
plotting_area.plot(
spectrum.lambdas, spectrum.values,
color=colorVal
)
canvas.draw()
# %% Application Object, true application is happening here
class Application(tk.Frame):
"""
GUI and pilot of the application.
"""
#####
# Useful constants
####
# Parameters and entries
SEPARATOR_ID = "[SEPARATOR]"
DISPLAY_KEYS = (
"T_TOT",
"INT_T",
"N_C",
"N_D",
SEPARATOR_ID,
"STARTLAM",
"ENDLAM",
"NRPTS",
SEPARATOR_ID
)
(T_TOT_ID, INT_T_ID, N_C_ID, N_D_ID, _1,
STARTLAM_ID, ENDLAM_ID, NRPTS_ID, _2) = DISPLAY_KEYS
DISPLAY_TEXTS = {
T_TOT_ID: "Total experiment time (in ms)",
INT_T_ID: "Integration time (in ms)",
N_C_ID: "Averaging number (integer)",
N_D_ID: "Delay Number (integer)",
STARTLAM_ID: "Starting lambda (in nm)",
ENDLAM_ID: "Ending lambda (in nm)",
NRPTS_ID: "Points number (integer)"
}
PARAMETERS_KEYS = (
"ROUTINE_DISPLAY_PERIOD",
"ROUTINE_INT_TIME",
"ROUTINE_INTERPOLATION",
"ROUTINE_STARTING_LAMBDA",
"ROUTINE_ENDING_LAMBDA",
"ROUTINE_NR_POINTS"
)
(ROUT_PERIOD, ROUT_INT_TIME, ROUT_INTERP_INT,
ROUT_START_LAM, ROUT_END_LAM, ROUT_NR_POINTS) = PARAMETERS_KEYS
PARAMETERS_TEXTS = {
ROUT_PERIOD: "Live display's period (>500 ms)",
ROUT_INT_TIME: "Live display's integration time (in ms)",
ROUT_INTERP_INT:
"Live display's smoothing window width (7 - 51 data pts)",
ROUT_START_LAM: "Live display's starting wavelength (in nm)",
ROUT_END_LAM: "Live display's ending wavelength (in nm)",
ROUT_NR_POINTS: "Live display's # of points (integer)"
}
# Files
BACKUP_CONFIG_FILE_NAME = "temporary_cfg.ctcf"
BACKUP_BLACK_FILE_NAME = "backup_black.crs"
BACKUP_WHITE_FILE_NAME = "backup_white.crs"
# Live Display Key names
LIVE_SCOPE = "Live scope"
LIVE_ABS = "Live abs."
BLACK_PANE = "Black"
WHITE_PANE = "White"
HARD_ABS_PANE = "Machine abs."
EXP_SCOPE = "Exp. scope"
EXP_ABS = "Exp. abs."
def __init__(self, master=None):
"""
Inits self.
Parameters:
- master -- Master widget to draw application in.
"""
super().__init__(master)
logger.debug("Initializing data structures.")
self.spectra_storage = spectro.Spectrum_Storage()
self.config_dict = dict([])
self.experiment_on = False
logger.debug("Opening connections.")
self._bnc = BNC.BNC(P_dispUpdate=False)
self.avh = spectro.AvaSpec_Handler()
logger.debug("Creating screen.")
self.createScreen()
self.initMenu()
# Set focus and pack
self.focus_set()
self.pack()
if os.path.exists("VERSION_INFO"):
with open("VERSION_INFO", "r") as file:
self._version = " ".join(
(
file.read().strip("\n"),
"(DEV)" if config.DEVELOPER_MODE_ENABLED else ""
)
)
logger.debug("Loading config file.")
try: # to open preceding config file
with open(self.BACKUP_CONFIG_FILE_NAME, "rb") as file:
self._rawLoadConfig(file)
except Exception as e: # File not found
logger.info("Impossible to open config file.", exc_info=e)
logger.debug("Loading B/W files.")
if os.path.exists(self.BACKUP_BLACK_FILE_NAME):
self.loadSpectra(
"Basic",
"Black",
path=self.BACKUP_BLACK_FILE_NAME,
display_screen=self.BLACK_PANE
)
else:
logger.info("No black spectra found.")
if os.path.exists(self.BACKUP_WHITE_FILE_NAME):
self.loadSpectra(
"Basic",
"White",
path=self.BACKUP_WHITE_FILE_NAME,
display_screen=self.WHITE_PANE
)
else:
logger.info("No white spectra found.")
def createScreen(self):
"""Creates and draw main app screen."""
self.mainOpt = ttk.Notebook(self) # Main display
# Normal mode
wind2 = self.createWidgetsSimple(self.mainOpt)
self.mainOpt.add(wind2, text="Normal")
# Advanced mode
wind = self.createWidgetsAdvanced(self.mainOpt)
self.mainOpt.add(wind, text="Advanced")
self.mainOpt.pack()
def initMenu(self):
"""Inits and draw menubar."""
menubar = tk.Menu(self.master)
filemenu = tk.Menu(menubar, tearoff=0) # Create the file menu scroll
filemenu.add_command(label="Open config", command=self.loadConfig)
filemenu.add_command(label="Save current config",
command=self.saveConfig)
filemenu.add_separator()
filemenu.add_command(label="Quit", command=self.goodbye_app)
menubar.add_cascade(label="File", menu=filemenu) # Add it to menubar
# Create the general spectra management menu
spectra_menu = tk.Menu(menubar, tearoff=0)
# Create the White menu
white_menu = tk.Menu(spectra_menu, tearoff=0)
# Technique using lambda functions to pass arguments to functions is
# advised by answer to StackOverflow question :
# https://stackoverflow.com/questions/6920302/how-to-pass-arguments-to-a-button-command-in-tkinter
white_menu.add_command(
label="Save White",
command=lambda: self.saveSpectra("Basic", "White")
)
white_menu.add_command(
label="Load White",
command=lambda: self.loadSpectra(
"Basic", "White", display_screen=self.WHITE_PANE
)
)
spectra_menu.add_cascade(
label="White",
menu=white_menu
)
black_menu = tk.Menu(spectra_menu, tearoff=0)
black_menu.add_command(
label="Save Black",
command=lambda: self.saveSpectra("Basic", "Black")
)
black_menu.add_command(
label="Load Black",
command=lambda: self.loadSpectra(
"Basic", "Black", display_screen=self.BLACK_PANE
)
)
spectra_menu.add_cascade(
label="Black",
menu=black_menu
)
spectra_menu.add_command(
label="Save all spectra",
command=self.saveSpectrumStorage
)
menubar.add_cascade(
label="Spectra",
menu=spectra_menu
)
menubar.add_command(label="Preferences...",
command=self.display_preference_menu)
menubar.add_command(
label="?",
command=self.displayHelp
)
self.master.config(menu=menubar)
def display_preference_menu(self):
"""Display the preference pane, for better parameter handling."""
config_pane = tk.Toplevel()
config_pane.title("Preferences")
for i, key in enumerate(self.PARAMETERS_KEYS):
tk.Label(
config_pane,
text=self.PARAMETERS_TEXTS[key]
).grid(row=i, column=0, sticky=tk.W)
tk.Entry(config_pane,
textvariable=self.config_dict[key]).grid(row=i, column=1)
def displayHelp(self):
"""
Open a popup showing a help frame.
"""
help_frame = tk.Toplevel()
help_frame.title("Help")
# CALOA version
tk.Label(
help_frame, text="CALOA {}".format(self._version)
).grid(row=0)
# Copyright
tk.Label(
help_frame,
text="Copyright (C) 2018 Thomas Vigouroux"
).grid(row=10)
# Open documentation button.
# the <commmand> part of this button is the combination of two
# StackOverflow questions :
# https://stackoverflow.com/questions/6920302/how-to-pass-arguments-to-a-button-command-in-tkinter
# https://stackoverflow.com/questions/4302027/how-to-open-a-url-in-python
tk.Button(
help_frame,
text="Open documentation.",
command=lambda: webbrowser.open(
"https://github.com/Mambu38/CALOA/blob/master/README.md"
)
).grid(row=20, sticky=tk.W+tk.E)
def updateScreen(self):
"""Easier way to update the screen."""
self.mainOpt.update()
def get_selected_absorbance(self, scopes):
"""
This method returns the absorbance spectra using the channel
selected in the GUI.
Parameters :
- scopes -- this is the spectra dict as given by
Spectrum_Storage[folder_id, subfolder_id, :]
"""
# As defined in createWidgetsSimple, referenceChannel is a textvariable
# containing an int corresponding to an AvsHandle.
# In AvaSpec_Handler.devList, keys are AvsHandles and items are
# (m_aUserFriendlyId, Callbackfunc)
# In Spectrum_Storage, spectra are indexed using m_aUserFriendlyId
# thus the next line is used to get m_aUserFriendlyId of the choosen
# channel as reference.
chosen = self.avh.devList[int(self.referenceChannel.get())][0]
ref_spectrum = scopes[chosen] # This is the reference spectrum
# We now generate absorbance spectra and format them in the correct way
# as acceptable by Spectrum_Storage.putSpectra()
# Naming convention for absorbance spectrum is as follows :
# "ABSORBANCE-{channel_id}"
abs_spectras = dict([])
for key in scopes:
# This is not useful to compute the absorbanceSpectrum of the
# referenceChannel, thus we don't do it.
if key != chosen:
abs_spectras["abs-{}".format(key)] = \
spectro.Spectrum.absorbanceSpectrum(
ref_spectrum, scopes[key])
return abs_spectras
def routine_data_sender(self):
"""
This routine is meant to send data to scope display.
This is a live-display-like feature.
"""
if not self.pause_live_display.wait(0):
self.avh.acquire()
try:
self.avh.prepareAll(
intTime=float(self.config_dict[self.ROUT_INT_TIME].get()),
triggerred=False,
nrAverages=1
)
except Exception:
self.avh.prepareAll(
triggerred=False,
nrAverages=1
)
scopes = self.avh.startAllAndGetScopes()
# list.copy() is realy important because of the
# eventual further modification of the list.
# Send raw spectras.
interpolated_scopes = dict([])
for key in scopes:
interpolated_scopes[key] =\
scopes[key].getInterpolated(
startingLamb=float(self.config_dict[
self.ROUT_START_LAM
].get()),
endingLamb=float(self.config_dict[
self.ROUT_END_LAM
].get()),
nrPoints=int(self.config_dict[
self.ROUT_NR_POINTS
].get()),
smoothing=True,
windowSize=int(self.config_dict[
self.ROUT_INTERP_INT
].get()),
polDegree=5
)
self.liveDisplay.putSpectrasAndUpdate(
self.LIVE_SCOPE, interpolated_scopes.copy()
)
if self.referenceChannel.get() != "":
# Compute absorbance (live)
try:
absorbanceSpectrum = self.get_selected_absorbance(
scopes
)
# Display absorbance
to_disp_abs = dict([])
for key in absorbanceSpectrum:
to_disp_abs[key] =\
absorbanceSpectrum[key].getInterpolated(
startingLamb=float(self.config_dict[
self.ROUT_START_LAM
].get()),
endingLamb=float(self.config_dict[
self.ROUT_END_LAM
].get()),
nrPoints=int(self.config_dict[
self.ROUT_NR_POINTS
].get()),
smoothing=True,
windowSize=int(self.config_dict[
self.ROUT_INTERP_INT
].get()),
polDegree=5
)
self.liveDisplay.putSpectrasAndUpdate(
self.LIVE_ABS, to_disp_abs
)
except Exception:
pass
self.avh.release()
try:
assert(int(self.config_dict[self.ROUT_PERIOD].get()) > 10)
self.after(
int(self.config_dict[self.ROUT_PERIOD].get()),
self.routine_data_sender
)
except Exception:
self.after(250, self.routine_data_sender)
elif not self.stop_live_display.wait(0):
self.after(1000, self.routine_data_sender)
# Save and load
def loadConfig(self):
"""Loads a config file selected by user."""
with tkFileDialog.askopenfile(mode="rb",
filetypes=[("CALOA Config file",
"*.cbc")]) as saveFile:
self._rawLoadConfig(saveFile)
def _rawLoadConfig(self, file):
"""Loads the file at file path given as parameter file."""
unpick = Unpickler(file)
tp_config_tup = unpick.load()
try:
self._bnc.load_from_pick(tp_config_tup[0])
for key in tp_config_tup[1].keys():
self.config_dict[key].set(tp_config_tup[1][key])
except Exception as e:
logger.critical("Error while loading file :", exc_info=e)
finally:
self.updateScreen()
def get_saving_dict(self):
"""Gather all configuration information that needs to be saved"""
tp_config_dict = dict([])
for key in self.config_dict.keys():
tp_config_dict[key] = self.config_dict[key].get()
return self._bnc.save_to_pickle(), tp_config_dict
def _rawSaveConfig(self, file):
"""Saves all config at file given as parameter file."""
pick = Pickler(file)
total_list = self.get_saving_dict()
pick.dump(total_list)
def saveConfig(self):
"""Saves config in a user selected location."""
saveFileName = tkFileDialog.asksaveasfilename(
defaultextension=".cbc",
filetypes=[("CALOA Config file",
"*.cbc")])
with open(saveFileName, "wb") as saveFile:
self._rawSaveConfig(saveFile)
def saveSpectra(self, folder_id, subfolder_id, path=None):
"""
Saves spectra located at folder_id, subfolder_id
Parameters :
- folder_id -- A folder id contained in Spectrum_Storage
- subfolder_id -- A subfolder_id contained in folder_id
"""
logger.debug("Starting to save {}-{}".format(folder_id, subfolder_id))
if path is None:
# Ask to select a save file
path = tkFileDialog.asksaveasfilename(
title="Saving spectra.",
defaultextension=".crs")
if path is not None: # if selected
with open(path, "wb") as save_file: # open it
pick = Pickler(save_file) # Create a Pickler
pick.dump(
self.spectra_storage. # NOT END OF LINE
_hidden_directory[folder_id][subfolder_id]
) # Save spectra
logger.debug("Saved {}-{}".format(folder_id, subfolder_id))
def loadSpectra(self, folder_id, subfolder_id, path=None,
display_screen=None):
"""
Loads spectra.
Parameters :
- folder_id/subfolder_id -- see Application.saveSpectra
- display_screen -- If set to a value (str), will display loaded
spectra in the live display using
Scope_Display.putSpectrasAndUpdate(display_screen, loaded data)
"""
logger.debug("Starting to load {}-{}".format(folder_id, subfolder_id))
if path is None:
# Ask to select a file
path = tkFileDialog.askopenfilename(
title="Saving spectra.",
defaultextension=".crs")
tp_spectra = None
if path is not None: # if selected
with open(path, "rb") as load_file: # open it
unpick = Unpickler(load_file) # crete an Unpickler
tp_spectra = unpick.load() # Load data
self.spectra_storage.\
_hidden_directory[folder_id][subfolder_id] = tp_spectra
else:
logger.critical("No file selected.")
return None
if display_screen is not None: # if a display_screen is set
# Display loaded spectra
self.liveDisplay.putSpectrasAndUpdate(
display_screen,
tp_spectra
)
logger.debug("Loaded {}-{}".format(folder_id, subfolder_id))
def saveSpectrumStorage(self):
"""
Saves spectrum storage into a selected file.
"""
# Select a file name
save_path = tkFileDialog.asksaveasfilename(
title="Save all spectra.",
defaultextension=".csf"
)
if save_path != "": # If selected
with open(save_path, "wb") as save_file:
pick = Pickler(save_file) # Create a Pickler
pick.dump(self.spectra_storage) # Dump spectra_storage
save_file.close() # For safety reasons, close file
else: # If not selected raise a warning to the user
raise UserWarning(
"Invalid file path."
)
# TODO: Enhance advanced frame aspect id:32
# Mambu38
# 39092278+Mambu38@users.noreply.github.com
# https://github.com/Mambu38/CALOA/issues/43
def createWidgetsAdvanced(self, master):
"""
Creates the advanced pane.
"""
wind = tk.PanedWindow(master, orient=tk.HORIZONTAL)
self.Lframe = tk.Frame(wind)
wind.add(self.Lframe)
bnc_frame = self._bnc.drawComplete(self.Lframe)
bnc_frame.pack(side=tk.LEFT)
sep1 = ttk.Separator(wind, orient=tk.VERTICAL)
wind.add(sep1)
self.Mframe = tk.Frame(wind)
wind.add(self.Mframe)
tk.Button(
self.Mframe, command=self._bnc.reset,
text="Reset BNC"
).pack(side=tk.RIGHT)
wind.pack()
return wind
def createWidgetsSimple(self, master):
"""
Draw the simple pane.
"""
frame = tk.Frame(master)
# Drawing BNC Frame
bnc_fen = self._bnc.drawSimple(frame)
bnc_fen.pack(side=tk.LEFT)
# Drawing Button Frame
button_fen = tk.LabelFrame(frame, text="Experiment parameters")
tk.Button(button_fen, text="Set Black",
command=self.set_black).grid(row=0, columnspan=2,
sticky=tk.E+tk.W)
tk.Button(button_fen, text="Set White",
command=self.set_white).grid(row=1, columnspan=2,
sticky=tk.E+tk.W)
tk.Button(button_fen, text="Start experiment",
command=self.experiment).grid(row=2, columnspan=2,
sticky=tk.E+tk.W)
# Here we make all interactible for experiment configuration.
sub_fen = tk.Frame(button_fen)
for i, key in enumerate(self.DISPLAY_KEYS):
if key == self.SEPARATOR_ID:
ttk.Separator(sub_fen,
orient=tk.HORIZONTAL).grid(row=i,
columnspan=2,
sticky=tk.E+tk.W,
pady=5)
elif key in self.DISPLAY_TEXTS:
tk.Label(sub_fen,
text=self.DISPLAY_TEXTS[key]).grid(row=i, column=0,
sticky=tk.W)
self.config_dict[key] = tk.StringVar(value="0")
tk.Entry(sub_fen,
textvariable=self.config_dict[key]).\
grid(row=i, column=1)
sub_fen.grid(row=3, rowspan=len(self.DISPLAY_KEYS), columnspan=2)
for key in self.PARAMETERS_KEYS:
self.config_dict[key] = tk.StringVar(value="0")
tk.Label(button_fen,
text="Reference channel").\
grid(row=90, column=0, rowspan=self.avh._nr_spec_connected)
self.referenceChannel = tk.StringVar(value="0")
for i, avsHandle in enumerate(self.avh.devList):
tk.Radiobutton(button_fen,
text=self.avh.devList[avsHandle][0],
variable=self.referenceChannel,
value=avsHandle).grid(row=90+i, column=1)
ttk.Separator(button_fen,
orient=tk.HORIZONTAL).grid(columnspan=2,
sticky=tk.E+tk.W,
pady=5)
self.processing_text = tk.Label(
button_fen, text="No running experiment...")
self.processing_text.grid(columnspan=2)
tk.Button(
button_fen, text="Abort current observation.",
command=self.stop_experiment
).grid(columnspan=2, sticky=tk.E+tk.W)
button_fen.pack(side=tk.LEFT, fill=tk.Y, padx=10, pady=10)
# Drawing Scope Frame
scope_fen = tk.Frame(frame)
self.pause_live_display = Event()
self.stop_live_display = Event()
self.liveDisplay = Scope_Display(
scope_fen,
[
(self.LIVE_SCOPE, Scope_Display.PLOT_TYPE_2D),
(self.LIVE_ABS, Scope_Display.PLOT_TYPE_2D),
(self.BLACK_PANE, Scope_Display.PLOT_TYPE_2D),
(self.WHITE_PANE, Scope_Display.PLOT_TYPE_2D),
(self.HARD_ABS_PANE, Scope_Display.PLOT_TYPE_2D),
(self.EXP_SCOPE, Scope_Display.PLOT_TYPE_2D),
(self.EXP_ABS, Scope_Display.PLOT_TYPE_TIME)
]
)
self.liveDisplay.pack(fill=tk.BOTH)
self.after(0, self.routine_data_sender)
scope_fen.pack(side=tk.RIGHT, padx=10, pady=10, fill=tk.BOTH)
return frame
def stop_experiment(self):
self.experiment_on = False
def set_black(self):
# Inform user that blakc is going to be set
self.processing_text["text"] = "Preparing black-setting..."
self.pause_live_display.set()
experiment_logger.info("Starting to set black")
# Gather informations about experiment parameters
try:
p_T_tot = float(self.config_dict[self.T_TOT_ID].get())
p_T = float(self.config_dict[self.INT_T_ID].get())
p_N_c = int(self.config_dict[self.N_C_ID].get())
except ValueError as e:
raise UserWarning(e.args[0]) # e.args[0] is the message
self._bnc.setmode("SINGLE")
self._bnc.settrig("TRIG")
self.avh.acquire()
self.avh.prepareAll(p_T, True)
for pulse in self._bnc:
pulse[BNC.WIDTH] = pulse.experimentTuple[BNC.WIDTH].get()
pulse[BNC.STATE] = pulse.experimentTuple[BNC.STATE].get()
self._bnc.run()
n_black = 0
tp_scopes = None
while n_black < p_N_c:
# Inform user
self.processing_text["text"] = "Processing experiment :\n"\
+ "\tAverage : {}/{}\n".format(n_black, p_N_c)
self.update()
# Get current time in milliseconds and compute estimated
# end time for experiment
start_time_in_ms = int(time.time()*1E3)
estimated_end_time_in_ms = start_time_in_ms + p_T_tot
self.avh.startAll(1) # Start avaspec
self._bnc.sendtrig() # Send trigger to BNC
# Wait appropriate time
self.after(
int(estimated_end_time_in_ms - int(time.time()*1E3))
)
n_black += 1
self.avh.waitAll()
spectra = self.avh.getScopes()
# If one spectrum is saturated, we inform user of it
# Feature asked in #81
for key in spectra:
if spectra[key].isSaturated():
self.processing_text["text"] += (
"\nWarning, {} is saturated.".format(key)
)
self.update()
if config.DEVELOPER_MODE_ENABLED:
self.liveDisplay.putSpectrasAndUpdate(
Scope_Display.DEBUG_DISPLAY, spectra
)