forked from LabGUI/LabGUI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLabGui.py
1206 lines (848 loc) · 47.2 KB
/
LabGui.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
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 18 05:01:18 2013
Copyright (C) 10th april 2015 Benjamin Schmidt & Pierre-Francois Duc
License: see LICENSE.txt file
nice logging example
http://victorlin.me/posts/2012/08/26/good-logging-practice-in-python
"""
import sys
import PyQt4.QtGui as QtGui
# just grab the parts we need from QtCore
from PyQt4.QtCore import Qt, SIGNAL, QReadWriteLock, QSettings
#from file_treatment_general_functions import load_experiment
import py_compile
#import plot_menu_and_toolbar
import getopt
import os
from os.path import exists
import numpy as np
from collections import OrderedDict
import logging
import logging.config
ABS_PATH = os.path.abspath(os.curdir)
logging.config.fileConfig(os.path.join(ABS_PATH,"logging.conf"))
from importlib import import_module
from LabTools.IO import IOTool
from LabTools.Display import QtTools, PlotDisplayWindow, mplZoomWidget
from LabDrivers import Tool
from LabTools import DataManagement
from LabTools.DataStructure import LabeledData
#FORMAT ='%(asctime)s - %(module)s - %(levelname)s - %(lineno)d -%(message)s'
#logging.basicConfig(level=logging.DEBUG,format=FORMAT)
PYTHON_VERSION = int(sys.version[0])
COREWIDGETS_PACKAGE_NAME = "LabTools.CoreWidgets"
USERWIDGETS_PACKAGE_NAME = "LabTools.UserWidgets"
CONFIG_FILE = IOTool.CONFIG_FILE_PATH
class LabGuiMain(QtGui.QMainWindow):
"""
This project was started in a lab with two sub teams having different experiments but using similar equipment, efforts were made to try capture what was the common core which should be shared and how to make sure we have the more modularity to be able to share the code with others.
One thing is sure, we are physicists and not computer scientists, we learned pyhton on the side and we might lack some standards in code writing/commenting, one of the reason we decided to share the code is to have you seeing the bugs and wierd features we don't notice anymore as we know how the code works internally.
It would be greatly apreciated if you want to report those bugs or contribute.
This is the main window in which all the widgets and plots are displayed and from which one manage the experiments
It is a class and has certains attributes :
-zoneCentrale which is a QMdiArea (where all your plot widget are going to be displayed)
-instr_hub: a class (Tool.InstrumentHub) which is a collection of instruments
-datataker : a class (DataManagment.DataTaker) which take data in a parallel thread so the plots do not freeze
-cmdwin : a class widget which allow you to choose which instrument you want to place in your instrument hub
-loadplotwidget : a class widget which allow loading of previously recorder data for visualization or fitting
-startwidget : a class widger in which you select your script file and where to save, you can also start the experiment from this wigdet
-dataAnalysewidget : a class widget used to do the fitting (this one is still in a beta mode and would need to be improved to be more flexible)
-limitswidget : a class widget to visualise the values of the current plot axis limits in X and Y
-calc widget :
-logTextEdit :
All these instances are "connected" to the fp instance, so they exchange information with the use of QtCore.SIGNAL (read more about this in http://zetcode.com/gui/pyqt4/eventsandsignals/).
You should have a file called config.txt with some keywords, the file config_example.txt contains them.
This is a list of them with some explanation about their role. These don't need to be there, they will just make your life easier :)
DEBUG= "if this is set to True, the instruments will not be actually connected to the computer, this is useful to debug the interface when away from your lab"
SCRIPT="the path to the script and script name (.py) which contains the command you want to send and recieve to and from your instruments, basically this is where you set your experiment"
SETTINGS="the path of the setting file and setting file name (.*) which contains your most used instrument connections so you don't have to reset them manually"
DATAFILE="The path of the older data file and its name to load them into the plotting system"
SAMPLE= "this is simply the sample_name which will display automatically in the filename choosen to save the data
DATA_PATH= "this is the path where the data should be saved"
You can add any keyword you want and get what the value is using the function get_config_setting from the module IOTool
The datataker instance will take care of executing the script you choosed when you click the "play"(green triangle) button or click "start" in the "Run Experiment"(startwidget) panel.
The script is anything you want your instruments to do, a few examples are provided in the script folder under the names demo_*.py
If measures are performed and you want to save them in a file and/or plot them, simply use the signal named "data(PyQt_PyObject)" in your script. The instance of LabGuiMain will catch it save it in a file and relay it through the signal "data_array_updated(PyQt_PyObject)"
The data will always be saved if you use the signal "data(PyQt_PyObject)", and the filename will change automatically in case you stop the datataker and restart it, this way you will never erase your data.
It is therefore quite easy to add your own widget which treats the data and do something else with them, you only need to connect it to the signal "data_array_updated(PyQt_PyObject)" and you will have access to the data.
The comments about each widgets can be found in their respective modules.
A wiki should be created to help understand and contribute to this project
"""
# cmdwin = None
def __init__(self, argv = []):
# run the initializer of the class inherited from6
super(LabGuiMain, self).__init__()
self.settings = QSettings(self)
self.settings.setValue("state", self.saveState())
#debug parameter used to run labgui even when there is no instrument
#to connect to, used to plot past data or test the code
self.DEBUG = True
#variable to store the configfile name
self.config_file = ''
#parse the argument(s) passed inline
try:
#option c is to provide a name for config file
opts, args = getopt.getopt(argv,"c:")
#loop through the arguments on the inline command
for opt, arg in opts:
#user passed configfile
if opt == '-c':
self.config_file = arg
except getopt.GetoptError:
logging.error('configuration file : option -c argument missing')
#verify if the config file passed by the user is valid and exists
if self.config_file:
if not exists(self.config_file):
logging.error("The config file you provided ('%s') doesn't \
exist, '%s' will be used instead"%(self.config_file, CONFIG_FILE))
self.config_file = CONFIG_FILE
else:
#check whether the default config file exists or not
if exists(CONFIG_FILE) == False:
logging.warning("A '%s' file has been generated for you."%(
CONFIG_FILE))
logging.warning("Please modify it to change the default \
script, settings and data locations, or to enter debug mode.")
# creates a config.txt with basic needs
IOTool.create_config_file()
#sets default config file name
self.config_file = CONFIG_FILE
#to make sure the config file is of the right format
#ie that the user didn't specify the name of an existing file which
#isn't a configuration file
config_file_ok = False
while not config_file_ok:
try:
#try to read the DEBUG parameter from the configuration file
#as a test of the good formatting of the file
self.DEBUG = IOTool.get_debug_setting(
config_file_path = self.config_file)
#if this didn't generate errors we allow to get out of the loop
config_file_ok = True
except IOError:
logging.error("The config file you provided ('%s') doesn't \
have the right format, '%s' will be used instead"%(self.config_file,
CONFIG_FILE))
#check whether the default config file exists or not
if exists(CONFIG_FILE) == False:
logging.warning("A '%s' file has been generated for you."%(
CONFIG_FILE))
logging.warning("Please modify it to change the default \
script, settings and data locations, or to enter debug mode.")
# creates a config.txt with basic needs
IOTool.create_config_file()
#sets default config file name
self.config_file = CONFIG_FILE
print("Configuration loaded from : %s"%(self.config_file))
if self.DEBUG == True:
print("*" * 20)
print("Debug mode is set to True")
print("*" * 20)
self.option_display_debug_state()
else:
self.option_display_normal_state()
#create the central part of the application
self.zoneCentrale = QtGui.QMdiArea()
self.zoneCentrale.subWindowActivated.connect(self.update_current_window)
self.setCentralWidget(self.zoneCentrale)
#load the parameter for the GPIB interface setting of the instruments
interface = IOTool.get_interface_setting(config_file_path = self.config_file)
#test if the parameter is correct
if interface not in [Tool.INTF_VISA,Tool.INTF_PROLOGIX]:
msg = """The %s variable of the config file '%s' is not correct
The only two allowed values are : '%s' and '%s' """%(
IOTool.GPIB_INTF_ID,
IOTool.CONFIG_FILE,
Tool.INTF_VISA,
Tool.INTF_PROLOGIX
)
logging.warning(msg)
#default setting
Tool.INTF_GPIB = Tool.INTF_PROLOGIX
else:
Tool.INTF_GPIB = interface
print("*" * 20)
print("The GPIB setting for connecting instruments is %s"%(
Tool.INTF_GPIB))
print("*" * 20)
# the lock is something for multithreading... not sure if it's important in our application.
self.lock = QReadWriteLock()
# InstrumentHub is responsible for storing and managing the user
# choices about which instrument goes on which port
self.instr_hub = Tool.InstrumentHub(parent = self,
debug = self.DEBUG)
# DataTaker is responsible for taking data from instruments in the
# InstrumentHub object
self.datataker = DataManagement.DataTaker(self.lock, self.instr_hub)
# handle data emitted by datataker (basically stuff it into a shared,
# central array)
self.connect(self.datataker, SIGNAL(
"data(PyQt_PyObject)"), self.update_data_array)
#a signal to signify the data taking script is over
self.connect(self.datataker, SIGNAL(
"script_finished(bool)"), self.finished_DTT)
#the array in which the data will be stored
self.data_array = np.array([])
# all actions related to the figure widget (mplZoomWidget.py) are
# set up in the actionmanager
self.action_manager = mplZoomWidget.ActionManager(self)
#this will contain the widget of the latest pdw created upon
#connecting the instrument Hub
self.actual_pdw = None
#this will contain windows settings (labels, checkboxes states, colors)
#of the plotdisplaw window which is created when the user click on
#the connect button
self.plot_window_settings = None
#### set up menus and toolbars
self.fileMenu = self.menuBar().addMenu("File")
self.plotMenu = self.menuBar().addMenu("&Plot")
self.instMenu = self.menuBar().addMenu("&Meas/Connect")
self.windowMenu = self.menuBar().addMenu("&Window")
self.optionMenu = self.menuBar().addMenu("&Options")
self.loggingSubMenu = self.optionMenu.addMenu("&Logger output level")
self.plotToolbar = self.addToolBar("Plot")
self.instToolbar = self.addToolBar("Instruments")
# start/stop/pause buttons
self.start_DTT_action = QtTools.create_action(
self, "Start DTT", slot = self.start_DTT,
shortcut = QtGui.QKeySequence("F5"), icon = "start",
tip = "Start script")
self.stop_DTT_action = QtTools.create_action(
self, "Stop DTT", slot = self.stop_DTT,
shortcut = QtGui.QKeySequence("F6"), icon = "stop",
tip = "stop script")
self.pause_DTT_action = QtTools.create_action(
self, "Pause DTT", slot = self.pause_DTT,
shortcut = QtGui.QKeySequence("F7"), icon = "pause",
tip = "pause script")
self.pause_DTT_action.setEnabled(False)
self.stop_DTT_action.setEnabled(False)
self.instToolbar.setObjectName("InstToolBar")
self.instToolbar.addAction(self.start_DTT_action)
self.instToolbar.addAction(self.pause_DTT_action)
self.instToolbar.addAction(self.stop_DTT_action)
#this will contain the different widgets in the window
self.widgets = {}
cur_path = os.path.dirname(__file__)
#find the path to the widgets folders
widget_path = os.path.join(cur_path,'LabTools')
#these are widgets essential to the interface
core_widget_path = os.path.join(widget_path,'CoreWidgets')
#these are widgets which were added by users
user_widget_path = os.path.join(widget_path,'UserWidgets')
#this is the legitimate list of core widgets
widgets_list = [o.rstrip('.py') for o in os.listdir(core_widget_path)
if o.endswith(".py") and not "__init__" in o]
#this is the legitimate list of user widgets
user_widgets_list = [o.rstrip('.py') for o in os.listdir(user_widget_path)
if o.endswith(".py") and not "__init__" in o]
#the user widgets the user would like to run, given in the config file
user_widgets = IOTool.get_user_widgets(config_file_path = self.config_file)
if user_widgets:
for user_widget in user_widgets:
#check that the given widget is legitimate
if user_widget in user_widgets_list:
#add the given widget to the widget list which will be
#loaded
widgets_list.append(user_widget)
else:
logging.warning("The user widget '%s' is not found at %s"%(
user_widget, user_widget_path))
#add the widgets to the interface
for widget in widgets_list:
widget_name = widget
try:
widget_module = import_module("." + widget_name,
package = COREWIDGETS_PACKAGE_NAME)
except ImportError:
widget_module = import_module("." + widget_name,
package = USERWIDGETS_PACKAGE_NAME)
self.add_widget(widget_module.add_widget_into_main)
###### FILE MENU SETUP ######
self.fileSaveSettingsAction = QtTools.create_action(self,
"Save Instrument Settings", slot = self.file_save_settings,
shortcut = QtGui.QKeySequence.SaveAs,
icon = None, tip = "Save the current instrument settings")
self.fileLoadSettingsAction = QtTools.create_action(self,
"Load Instrument Settings", slot = self.file_load_settings,
shortcut = QtGui.QKeySequence.Open,
icon = None, tip = "Load instrument settings from file")
self.fileLoadDataAction = QtTools.create_action(self,
"Load Previous Data", slot = self.file_load_data, shortcut = None,
icon = None, tip = "Load previous data from file")
"""this is not working I will leave it commented right now"""
# self.filePrintAction = QtTools.create_action(self, "&Print Report", slot=self.file_print, shortcut=QtGui.QKeySequence.Print,
# icon=None, tip="Print the figure along with relevant information")
self.fileSaveCongfigAction = QtTools.create_action(self,
"Save current configuration", slot = self.file_save_config,
shortcut = None, icon = None, tip = "Save the setting file path, \
the script path and the data output path into the config file")
self.fileMenu.addAction(self.fileLoadSettingsAction)
self.fileMenu.addAction(self.fileSaveSettingsAction)
self.fileMenu.addAction(self.fileLoadDataAction)
# self.fileMenu.addAction(self.filePrintAction)
self.fileMenu.addAction(self.action_manager.saveFigAction)
self.fileMenu.addAction(self.fileSaveCongfigAction)
###### PLOT MENU + TOOLBAR SETUP ######
self.plotToolbar.setObjectName("PlotToolBar")
for action in self.action_manager.actions:
self.plotMenu.addAction(action)
self.plotToolbar.addAction(action)
self.clearPlotAction = QtTools.create_action(self,
"Clear All Plots", slot = self.clear_plot, shortcut = None,
icon = "clear_plot", tip = "Clears the live data arrays")
self.removeFitAction = QtTools.create_action(self,
"Remove Fit", slot = self.remove_fit, shortcut = None,
icon = "clear", tip = "Reset the fit data to an empty array")
self.plotMenu.addAction(self.clearPlotAction)
self.plotMenu.addAction(self.removeFitAction)
###### INSTRUMENT MENU SETUP ######
self.read_DTT = QtTools.create_action(self, "Read",
slot = self.single_measure_DTT, shortcut = None, icon = None,
tip = "Take a one shot measure with DTT")
self.connect_hub = QtTools.create_action(self, "Connect Instruments",
slot = self.connect_instrument_hub,
shortcut = QtGui.QKeySequence("Ctrl+I"), icon=None,
tip="Refresh the list of selected instruments")
self.refresh_ports_list_action = QtTools.create_action(self,
"Refresh ports list", slot = self.refresh_ports_list, icon = None,
tip = "Refresh the list of availiable ports")
self.instMenu.addAction(self.start_DTT_action)
self.instMenu.addAction(self.read_DTT)
self.instMenu.addAction(self.connect_hub)
self.instMenu.addAction(self.refresh_ports_list_action)
###### WINDOW MENU SETUP ######
self.add_pdw = QtTools.create_action(self, "Add a Plot",
slot = self.create_pdw, shortcut = None, icon = None,
tip = "Add a recordsweep window")
self.add_pqtw = QtTools.create_action(self, "Add a PyQtplot",
slot = self.create_pqtw, shortcut = None, icon = None,
tip = "Add a pyqt window")
self.windowMenu.addAction(self.add_pdw)
try:
import PyQTWindow
self.windowMenu.addAction(self.add_pqtw)
except:
logging.info("pyqtgraph is unable to load, \
the pyqt window option is disabled")
###### OPTION MENU SETUP ######
self.toggle_debug_state = QtTools.create_action(self,
"Change debug mode", slot = self.option_change_debug_state,
shortcut = None, icon = None,
tip = "Change the state of the debug mode")
# self.toggle_debug_state = QtTools.create_action(self,
# "Change debug mode", slot = self.option_change_debug_state,
# shortcut = None, icon = None,
# tip = "Change the state of the debug mode")
self.optionMenu.addAction(self.toggle_debug_state)
for log_level in ["DEBUG", "INFO", "WARNING", "ERROR"]:
action = QtTools.create_action(self,
log_level, slot = self.option_change_log_level,
shortcut = None, icon = None,
tip = "Change the state of the logger to %s" % log_level)
self.loggingSubMenu.addAction(action)
###############################
#Load the user settings for the instrument connectic and parameters
self.default_settings_fname = IOTool.get_settings_name(config_file_path = self.config_file)
if not exists(self.default_settings_fname):
logging.warning("The filename '%s' wasn't found, using '%s'"%(
self.default_settings_fname,'settings/default_settings.txt'))
self.default_settings_fname = 'settings/default_settings.txt'
if os.path.isfile(self.default_settings_fname):
self.widgets['CalcWidget'].load_settings(
self.default_settings_fname)
self.widgets['InstrumentWidget'].load_settings(
self.default_settings_fname)
# Create the object responsible to display information send by the
# datataker
self.data_displayer = DataManagement.DataDisplayer(self.datataker)
# platform-independent way to restore settings such as toolbar positions,
# dock widget configuration and window size from previous session.
# this doesn't seem to be working at all on my computer (win7 system)
self.settings = QSettings("Gervais Lab", "RecordSweep")
try:
self.restoreState(self.settings.value("windowState").toByteArray())
self.restoreGeometry(self.settings.value("geometry").toByteArray())
except:
logging.info('Using default window configuration') # no biggie - probably means settings haven't been saved on this machine yet
#hide some of the advanced widgets so they don't show for new users
# the objects are not actually deleted, just hidden
def add_widget(self,widget_creation, action_fonctions = None, **kwargs):
"""adds a widget to the MainArea Window
this is a rough stage of this fonction, it calls a fonction from
another module to add its widget to the Qdocks
"""
widget_creation(self)
def closeEvent(self, event):
reply = QtGui.QMessageBox.question(self, 'Message',
"Are you sure you want to quit?", QtGui.QMessageBox.Yes,
QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
#save the current settings
self.file_save_settings(self.default_settings_fname)
self.settings.setValue("windowState", self.saveState())
self.settings.setValue("geometry", self.saveGeometry())
self.settings.remove("script_name")
event.accept()
else:
event.ignore()
def create_pdw(self, num_channels = None, settings = None):
"""
add a new plot display window in the MDI area its channels are labeled according to the channel names on the cmd window.
It is connected to the signal of data update.
"""
if num_channels == None:
num_channels = self.instr_hub.get_instrument_nb() + \
self.widgets['CalcWidget'].get_calculation_nb()
pdw = PlotDisplayWindow.PlotDisplayWindow(data_array = self.data_array,
name="Live Data Window",
default_channels = num_channels)
self.connect(self, SIGNAL("data_array_updated(PyQt_PyObject)"),
pdw.update_plot)
self.connect(pdw.mplwidget, SIGNAL(
"limits_changed(int,PyQt_PyObject)"), self.emit_axis_lim)
# this is here temporary, I would like to change the plw when the live
# fit is ticked
self.connect(self.widgets['AnalyseDataWidget'], SIGNAL(
"data_set_updated(PyQt_PyObject)"), pdw.update_plot)
self.connect(self.widgets['AnalyseDataWidget'], SIGNAL(
"update_fit(PyQt_PyObject)"), pdw.update_fit)
self.connect(self, SIGNAL("remove_fit()"), pdw.remove_fit)
self.connect(self, SIGNAL("colorsChanged(PyQt_PyObject)"),
pdw.update_colors)
self.connect(self, SIGNAL("labelsChanged(PyQt_PyObject)"),
pdw.update_labels)
self.connect(self, SIGNAL(
"markersChanged(PyQt_PyObject)"), pdw.update_markers)
if settings == None:
self.update_labels()
self.update_colors()
else:
#this will set saved settings for the channel controls of the
#plot display window
pdw.set_channels_values(settings)
self.zoneCentrale.addSubWindow(pdw)
pdw.show()
def create_pqtw(self):
"""
add a new pqt plot display window in the MDI area its channels are labeled according to the channel names on the cmd window.
It is connected to the signal of data update.
"""
pqtw = PyQtWindow.PyQtGraphWidget(n_curves=self.instr_hub.get_instrument_nb(
) + self.widgets['CalcWidget'].get_calculation_nb(), parent=self) # self.datataker)
self.connect(self, SIGNAL("spectrum_data_updated(PyQt_PyObject,int)"),
pqtw.update_plot)
# self.connect(pdw.mplwidget,SIGNAL("limits_changed(int,PyQt_PyObject)"),self.emit_axis_lim)
# this is here temporary, I would like to change the plw when the live fit is ticked
# self.connect(self.dataAnalyseWidget, SIGNAL("data_set_updated(PyQt_PyObject)"),pdw.update_plot)
# self.connect(self.dataAnalyseWidget, SIGNAL("update_fit(PyQt_PyObject)"), pdw.update_fit)
# self.connect(self,SIGNAL("remove_fit()"), pdw.remove_fit)
# self.connect(self, SIGNAL("colorsChanged(PyQt_PyObject)"), pdw.update_colors)
# self.connect(self, SIGNAL("labelsChanged(PyQt_PyObject)"), pdw.update_labels)
# self.connect(self, SIGNAL("markersChanged(PyQt_PyObject)"), pdw.update_markers)
# self.update_labels()
# self.update_colors()
self.zoneCentrale.addSubWindow(pqtw)
pqtw.show()
def get_last_window(self, window_ID = "Live"):
"""
should return the window that was created when the
instrument hub was connected
"""
try:
pdw = self.zoneCentrale.subWindowList()[-1].widget()
except IndexError:
logging.error("No pdw available")
return pdw
def update_colors(self):
color_list = self.widgets['InstrumentWidget'].get_color_list() \
+ self.widgets['CalcWidget'].get_color_list()
self.emit(SIGNAL("colorsChanged(PyQt_PyObject)"), color_list)
def update_labels(self):
label_list = self.widgets['InstrumentWidget'].get_label_list() \
+ self.widgets['CalcWidget'].get_label_list()
self.emit(SIGNAL("labelsChanged(PyQt_PyObject)"), label_list)
def emit_axis_lim(self, mode, limits):
"""
emits the limits of the selected axis on the highlighted plot
"""
current_window = self.zoneCentrale.activeSubWindow()
if current_window:
current_widget = self.zoneCentrale.activeSubWindow().widget()
# this is a small check that we are no trying to get the limits from
# the wrong plot
# if current_widget.windowTitle() == "Past Data Window":
try:
paramX = current_widget.get_X_axis_index()
except:
paramX = 0
try:
paramY = current_widget.get_Y_axis_index()
except:
paramY = 1
try:
paramYfit = current_widget.get_fit_axis_index()
except:
paramYfit = 1
# except:
# logging.info( "G2GUI.emit_axis_lim : the params are not defined, the default is X-> Channel 1 and Y->Channel 2")
# else:
# try:
# paramX = current_widget.get_X_axis_index()
# paramY = current_widget.get_Y_axis_index()
# paramYfit = current_widget.get_fit_axis_index()
# except:
# logging.info("G2GUI.emit_axis_lim : the params are not defined, the default is X-> Channel 1 and Y->Channel 2")
# paramX = 0
# paramY = 1
# paramYfit = 1
#
try:
# logging.warning("%i%i"%(paramX,paramY))
x = current_widget.data_array[:, paramX]
xmin = limits[0][0]
xmax = limits[0][1]
imin = IOTool.match_value2index(x, xmin)
imax = IOTool.match_value2index(x, xmax)
self.emit(SIGNAL("selections_limits(PyQt_PyObject,int,int,int,int)"), np.array(
[imin, imax, xmin, xmax]), paramX, paramY, paramYfit, mode)
except IndexError:
logging.debug("There is apparently no data generated yet")
except:
logging.warning("There was an error with the limits")
def single_measure_DTT(self):
self.datataker.initialize()
self.datataker.read_data()
self.datataker.stop()
def start_DTT(self):
if self.datataker.isStopped():
self.start_DTT_action.setEnabled(False)
self.pause_DTT_action.setEnabled(True)
self.stop_DTT_action.setEnabled(True)
self.widgets['InstrumentWidget'].bt_connecthub.setEnabled(False)
#self.startWidget.startStopButton.setText("Stop!")
#self.start_DTT_.setText("Stop DTT")
# just update the color boxes in case
self.update_colors()
self.update_labels()
# read the name of the output file and determine if it exists
of_name = self.widgets['OutputFileWidget'].get_output_fname()
is_new_file = not os.path.exists(of_name)
# if this file is new, the first 2 lines contain the instrument and
# parameters list
if is_new_file:
self.output_file = open(of_name, 'w')
[instr_name_list, dev_list, param_list] = self.collect_instruments()
self.output_file.write(
"#C" + str(self.widgets['InstrumentWidget'].get_label_list()).strip('[]') + '\n')
self.output_file.write(
"#I" + str(self.widgets['InstrumentWidget'].get_descriptor_list()).strip('[]') + '\n')
self.output_file.write(
"#P" + str(param_list).strip('[]') + '\n')
else:
# here I want to perform a check to see whether the number of instrument match
# open it in append mode, so it won't erase previous data
self.output_file = open(of_name, 'a')
self.datataker.initialize(is_new_file)
self.datataker.set_script(self.widgets['SciptWidget'].get_script_fname())
# this command is specific to Qthread, it will execute whatever is defined in
# the method run() from DataManagement.py module
self.datataker.start()
elif self.datataker.isPaused():
# restarting from pause
self.start_DTT_action.setEnabled(False)
self.pause_DTT_action.setEnabled(True)
self.stop_DTT_action.setEnabled(True)
self.datataker.resume()
else:
print("Couldn't start DTT - already running!")
def stop_DTT(self):
if not self.datataker.isStopped():
self.datataker.resume()
self.datataker.stop()
#close the output file
self.output_file.close()
#reopen the output file to read its content
self.output_file = open(self.output_file.name, 'r')
data = self.output_file.read()
self.output_file.close()
#insert the comments written by the user in the first line
self.output_file = open(self.output_file.name, 'w')
self.output_file.write(self.widgets['OutputFileWidget'].get_header_text())
self.output_file.write(data)
self.output_file.close()
# just make sure the pause setting is left as false after ther run
self.start_DTT_action.setEnabled(True)
self.pause_DTT_action.setEnabled(False)
self.stop_DTT_action.setEnabled(False)
# Enable changes to the instrument connections
self.widgets['InstrumentWidget'].bt_connecthub.setEnabled(True)
else:
print("Couldn't stop DTT - it wasn't running!")
def pause_DTT(self):
if not self.datataker.isStopped():
self.start_DTT_action.setEnabled(True)
self.pause_DTT_action.setEnabled(False)
self.stop_DTT_action.setEnabled(True)
self.datataker.pause()
def toggle_DTT(self):
if self.datataker.isStopped():
self.start_DTT()
else:
self.stop_DTT()
def finished_DTT(self, completed):
if completed:
self.stop_DTT()
self.start_DTT_action.setEnabled(True)
self.pause_DTT_action.setEnabled(False)
self.stop_DTT_action.setEnabled(False)
self.widgets['OutputFileWidget'].increment_filename()
# just make sure the pause setting is left as false after ther run
self.datataker.resume()
self.output_file.close()
def write_data(self, data_set):
if self.output_file:
if not self.output_file.closed:
# a quick way to make a comma separated list of the values
stri = str(data_set).strip('[]\n\r')
# numpy arrays include newlines in their strings, get rid of
# them.
stri = stri.replace('\n', '')
# np.loadtxt uses whitespace delimiter by default, so we do too
stri = stri.replace(',', ' ')
self.output_file.write(stri + '\n')
print('>>' + stri)
def update_spectrum_data(self, spectrum_data):
chan_num = 0
self.emit(SIGNAL("spectrum_data_updated(PyQt_PyObject)"),
spectrum_data, chan_num)
def update_data_array(self, data_set):
""" slot for when the thread emits data """
# convert this latest data to an array
data = np.array(data_set)
for calculation in self.widgets['CalcWidget'].get_calculation_list():
calculation = calculation.strip()
if calculation:
data = np.append(data, eval(calculation + '\n'))
#else:
#print "here's the zero"
#data = np.append(data, 0)
# writes data and calculated columns
self.write_data(data.tolist())
# check if this is the first piece of data
if self.data_array.size == 0:
self.data_array = data
# need to make sure the shape is 2D even though there's only
# one line of data so far
self.data_array.shape = [1, self.data_array.size]
else:
# vstack just appends the data
try:
self.data_array = np.vstack([self.data_array, data])
except:
self.data_array = data
self.emit(SIGNAL("data_array_updated(PyQt_PyObject)"), self.data_array)
#
def collect_instruments(self):
"""list properties of the connected instruments (comport, parameter)"""
return self.widgets['InstrumentWidget'].collect_device_info()
def refresh_ports_list(self):
"""Update the availiable port list in the InstrumentWindow module """
self.widgets['InstrumentWidget'].refresh_cbb_port()
def update_current_window(self, x):
''' this changes what self.<object> refers to so that the same shared toolbars can modify whichever plot window has focus right now '''
current_window = self.zoneCentrale.activeSubWindow()
if current_window:
self.action_manager.update_current_widget(
current_window.widget().mplwidget)
if not current_window is None:
current_widget = self.zoneCentrale.activeSubWindow().widget()
window_type = getattr(current_widget, "window_type", "unknown")
if window_type == "unknown":
msg = "The type of PlotDisplayWindow '%s' is unknown"%(window_type)
raise ValueError(msg)
else:
if window_type in PlotDisplayWindow.PLOT_WINDOW_TYPE_PAST:
#get the title of the window
title = str(current_window.windowTitle())
#extract the file name from the window title
#see LoadPlotWidget for more info on that
load_fname = title.split(
PlotDisplayWindow.PLOT_WINDOW_TITLE_PAST)
load_fname = load_fname[1]
#replace the header text by the one stored in memory
self.widgets["loadPlotWidget"].header_text(
self.loaded_data_header[load_fname])
#update the file information in the widget
self.widgets["loadPlotWidget"].load_file_name(load_fname)
# this is only used by Print Figure (which doesn't work anyways)
self.current_pdw = current_widget
# this was only used by saveFig, at least within this file.
self.fig = current_widget.fig
else:
# 20130722 it runs this part of the code everytime I click
# somewhere else that inside the main window
pass
def isrunning(self):
"""indicates whether the datataker is running or not"""
return not self.datataker.stopped
def clear_plot(self):
self.data_array = np.array([])
self.emit(SIGNAL("data_array_updated(PyQt_PyObject)"), self.data_array)
def remove_fit(self):
self.emit(SIGNAL("remove_fit()"))
def file_save_config(self):
"""
this function get the actual values of parameters and save them into the config file
"""
script_fname=str(self.widgets['SciptWidget'].scriptFileLineEdit.text())
IOTool.set_config_setting(IOTool.SCRIPT_ID,script_fname,self.config_file)
output_path = os.path.dirname(self.widgets['OutputFileWidget'].get_output_fname())+os.path.sep
IOTool.set_config_setting(IOTool.SAVE_DATA_PATH_ID,output_path,self.config_file)
if not self.instrument_connexion_setting_fname == "":
IOTool.set_config_setting(IOTool.SETTINGS_ID,self.instrument_connexion_setting_fname,self.config_file)
def file_save_settings(self, fname = None):
"""save the settings for the instruments and plot window into a file
the settings are instrument names, connection ports, parameters
for the instrument and which axis to select for plotting, colors,
markers, linestyles and user defined parameters for the window
"""