-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainFormQT.py
1345 lines (1251 loc) · 65.3 KB
/
MainFormQT.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from PySide6 import QtWidgets, QtCore, QtGui
from PySide6.QtUiTools import QUiLoader
from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg
import sys # We need sys so that we can pass argv to QApplication
import os
import numpy as np
from multiprocessing.pool import ThreadPool
from DataExtractors.DataExtractorH5single import DataExtractorH5single
from DataExtractors.DataExtractorH5multiple import DataExtractorH5multiple
from DataExtractors.DataExtractorUQtoolsDAT import DataExtractorUQtoolsDAT
import time
import json
import Icons
import pyqtgraph.exporters as pgExp
from PostProcessors import*
from functools import partial
from Cursors.Cursor_Cross import Cursor_Cross
from Cursors.Cursor_Vertical import Cursor_Vertical
from Cursors.Analy_Cursors import*
class ColourMap:
def __init__(self):
pass
@classmethod
def fromMatplotlib(cls, cmap_name, display_name):
retObj = cls()
retObj._cmap = pg.colormap.getFromMatplotlib(cmap_name)
retObj._display_name = display_name
return retObj
@classmethod
def fromCustom(cls, cm_data, display_name):
retObj = cls()
#Assuming uniformly sampled colour maps (i.e. not specifying pos)
retObj._cmap = pg.ColorMap(pos=None, color=cm_data)
retObj._display_name = display_name
return retObj
@property
def Name(self):
return self._display_name
@property
def CMap(self):
return self._cmap
class MainWindow:
def __init__(self, app, win, plot_layout_widget):
self.plot_layout_widget = plot_layout_widget
self.win = win
self.app = app
self.data_extractor = None
hour = [1,2,3,4,5,6,7,8,9,10]
temperature = [30,32,34,32,33,31,29,32,35,45]
self.analysis_cursors = []
self.cursors = [] #Holds: (latest x value, latest y value, colour as a 3-vector RGB or character, Cursor_Cross object)
self.colbar_cursors = []
self.win.btn_cursor_add.clicked.connect(self._event_btn_cursor_add)
self.win.btn_cursor_del.clicked.connect(self._event_btn_cursor_del)
# plot data: x, y values
self.setup_axes(1)
self.data_line = self.plt_main.plot(hour, temperature)
self.plot_type = 1
self.data_img = None
self.dep_vars = None
self.timer = QtCore.QTimer()
self.timer.setInterval(50)
self.timer.timeout.connect(self.update_plot_data)
self.timer.start()
self.file_path = ""
self.data_thread_pool = None
self.default_win_title = self.win.windowTitle()
win.actionFopenH5.triggered.connect(self._event_btn_open_H5)
win.actionFopenH5dir.triggered.connect(self._event_btn_open_H5dir)
win.actionFopenDat.triggered.connect(self._event_btn_open_DAT)
win.actionresetCursor.triggered.connect(self._event_btn_cursor_reset)
win.actiongetFileAttributes.triggered.connect(self._event_btn_get_attrs)
win.actiongetFileFigure.triggered.connect(self._event_btn_get_fig)
win.actiongotoFilePrev.triggered.connect(self._open_file_prev)
win.actiongotoFileNext.triggered.connect(self._open_file_next)
win.actionExportNpyPython.triggered.connect(self._export_npy_matplotlib)
#Plot Axis Radio Buttons
self.win.rbtn_plot_1D.toggled.connect(self.event_rbtn_plot_axis)
self.win.rbtn_plot_2D.toggled.connect(self.event_rbtn_plot_axis)
#Setup the slicing variables
self.dict_var_slices = {} #They values are given as: (currently set slicing index, numpy array of values)
self.cur_slice_var_keys_lstbx = []
self.win.lstbx_param_slices.itemSelectionChanged.connect(self._event_slice_var_selection_changed)
self.win.sldr_param_slices.valueChanged.connect(self._event_sldr_slice_vars_val_changed)
self.win.btn_slice_vars_val_inc.clicked.connect(self._event_btn_slice_vars_val_inc)
self.win.btn_slice_vars_val_dec.clicked.connect(self._event_btn_slice_vars_val_dec)
#Setup available postprocessors
self.post_procs_all = PostProcessors.get_all_post_processors()
self.win.lstbx_plot_analy_funcs.addItems(self.post_procs_all.keys())
self.win.lstbx_plot_analy_funcs.itemSelectionChanged.connect(self._event_lstbxPPfunction_changed)
self.win.btn_plot_anal_add_func.clicked.connect(self._event_btn_post_proc_add)
#Currently selected postprocessors
self.cur_post_procs = []
self.cur_post_proc_output = "dFinal"
self.frm_proc_disp_children = []
self.win.lstbx_cur_post_procs.itemSelectionChanged.connect(self._event_lstbx_proc_current_changed)
self.win.btn_proc_list_up.clicked.connect(self._event_btn_post_proc_up)
self.win.btn_proc_list_down.clicked.connect(self._event_btn_post_proc_down)
self.win.btn_proc_list_del.clicked.connect(self._event_btn_post_proc_delete)
#Setup current post-processing analysis ListBox and select the first entry (the final output entry)
self._post_procs_fill_current(0)
win.btn_proc_list_open.clicked.connect(self._event_btn_proc_list_open)
win.btn_proc_list_save.clicked.connect(self._event_btn_proc_list_save)
self._post_procs_update_configs_from_file()
#Setup colour maps from Matplotlib
self._def_col_maps = [('viridis', "Viridis"), ('afmhot', "AFM Hot"), ('hot', "Hot"), ('gnuplot', "GNU-Plot"), ('inferno', "Inferno"), ('coolwarm', "Cool-Warm"), ('seismic', "Seismic"), ('rainbow', "Rainbow")]
self.colour_maps = []
for cur_col_map in self._def_col_maps:
self.colour_maps.append(ColourMap.fromMatplotlib(cur_col_map[0], cur_col_map[1]))
#
self._aux_col_maps = []
file_path = 'ColourMaps/'
json_files = [pos_json for pos_json in os.listdir(file_path) if pos_json.endswith('.json')]
for cur_json_file in json_files:
with open(file_path + cur_json_file) as json_file:
data = json.load(json_file)
self._aux_col_maps.append(np.array(data))
self.colour_maps.append(ColourMap.fromCustom(np.array(data)*255.0, cur_json_file[:-5])) #Still specify colour maps from 0 to 1. PyQTgraph just requires it from 0-255
#Commit colour maps to ComboBox
self.win.cmbx_ckey.addItems([x.Name for x in self.colour_maps])
self.win.cmbx_ckey.currentIndexChanged.connect(partial(self._event_cmbx_key_changed) )
self.win.cmbx_colbar_num_marks.addItems([str(x) for x in range(2,9)])
self.win.cmbx_colbar_num_marks.currentIndexChanged.connect(partial(self._event_cmbx_colbar_marks_changed) )
self.win.btn_colbar_reset.clicked.connect(self._event_btn_colbar_reset)
self.win.btn_colbar_histeq.clicked.connect(self._event_btn_colbar_histeq)
#Hide the differential cursors...
self.win.tbl_cursor_diffs.setVisible(False)
self.win.tbl_cursor_diffs.setColumnCount(6)
self.win.tbl_cursor_diffs.setHorizontalHeaderLabels(["", "", "Δx", "Δy", "1/Δx", "1/Δy"])
headerView = self.win.tbl_cursor_diffs.horizontalHeader()
headerView.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
headerView.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
headerView.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
headerView.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
headerView.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
headerView.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
#Setup analysis cursors
#Setup a dictionary which maps the cursor name to the cursor class...
self.possible_cursors = Analy_Cursor.get_all_analysis_cursors()
self.win.cmbx_anal_cursors.addItems(self.possible_cursors.keys())
self.win.btn_analy_cursor_add.clicked.connect(self._event_btn_anal_cursor_add)
self.win.btn_analy_cursor_del.clicked.connect(self._event_btn_anal_cursor_del)
#
self.win.tbl_analy_cursors.setColumnCount(4)
self.win.tbl_analy_cursors.setHorizontalHeaderLabels(["Show", "Name", "Type", "Value"])
headerView = self.win.tbl_analy_cursors.horizontalHeader()
headerView.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
headerView.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
headerView.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
headerView.setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch)
self._anal_cursor_add_block_event = False
self.win.tbl_analy_cursors.itemChanged.connect(self._event_chkbx_anal_cursor_show)
#Initial update time-stamp
self.last_update_time = time.time()
def _event_cmbx_key_changed(self, idx):
if self.colBarItem != None:
self.colBarItem.setColorMap(self.colour_maps[self.win.cmbx_ckey.currentIndex()].CMap)
def _event_cmbx_colbar_marks_changed(self, idx):
self.set_colbar_cursors(int(self.win.cmbx_colbar_num_marks.currentText()))
def _event_btn_colbar_reset(self):
self.reset_colbar_ticks()
def _event_btn_colbar_histeq(self):
if isinstance(self.z_data, np.ndarray) and len(self.colbar_cursors) > 0:
vals = np.linspace(0,1, len(self.colbar_cursors) + 2)
vals = np.nanquantile(self.z_data.flatten(), vals[1:-1:])
for m, cur_col_curse in enumerate(self.colbar_cursors):
cur_col_curse.set_value(vals[m])
def trLst(self, lst):
return [self.app.tr(x) for x in self.indep_vars]
def setup_plot_vars(self):
self.indep_vars = self.data_extractor.get_independent_vars()
if self.indep_vars != [self.win.cmbx_axis_x.itemText(x) for x in range(self.win.cmbx_axis_x.count())]:
cur_sel = self.win.cmbx_axis_x.currentText()
cur_sel_ind = 0
if self.win.cmbx_axis_x.currentText() != '' and cur_sel in self.indep_vars:
cur_sel_ind = self.indep_vars.index(cur_sel)
self.win.cmbx_axis_x.clear()
self.win.cmbx_axis_x.addItems(self.indep_vars)
self.win.cmbx_axis_x.setCurrentIndex(cur_sel_ind)
#
cur_sel = self.win.cmbx_axis_y.currentText()
cur_sel_ind = 0
if self.win.cmbx_axis_y.currentText() != '' and cur_sel in self.indep_vars:
cur_sel_ind = self.indep_vars.index(cur_sel)
self.win.cmbx_axis_y.clear()
self.win.cmbx_axis_y.addItems(self.indep_vars)
self.win.cmbx_axis_y.setCurrentIndex(cur_sel_ind)
self.dep_vars = self.data_extractor.get_dependent_vars()
if self.dep_vars != [self.win.cmbx_dep_var.itemText(x) for x in range(self.win.cmbx_dep_var.count())]:
cur_sel = self.win.cmbx_dep_var.currentText()
cur_sel_ind = 0
if self.win.cmbx_dep_var.currentText() != '' and cur_sel in self.dep_vars:
cur_sel_ind = self.dep_vars.index(cur_sel)
self.win.cmbx_dep_var.clear()
self.win.cmbx_dep_var.addItems(self.dep_vars)
self.win.cmbx_dep_var.setCurrentIndex(cur_sel_ind)
def event_rbtn_plot_axis(self, value):
if self.win.rbtn_plot_1D.isChecked():
self.setup_axes(1)
else:
self.setup_axes(2)
def setup_axes(self, plot_dim):
#Clear plots
for m in range(len(self.cursors)):
if self.cursors[m][3] != None:
# self.cursors[m][3].release_from_plots()
del self.cursors[m][3]
self.cursors[m] += [None]
for cur_anal_curse in self.analysis_cursors:
cur_anal_curse.release_from_plots()
for cur_colbar_curse in self.colbar_cursors:
self.plt_main.removeItem(cur_colbar_curse)
self.colbar_cursors.clear()
self.plot_layout_widget.clear()
#
self.data_line = None
#
self.plt_main = None
self.data_img = None
self.colBarItem = None
self.cur_col_map = None
self.plt_curs_x = None
self.plt_curs_y = None
self.data_curs_x = []
self.data_curs_y = []
self.plt_colhist = None
self.data_colhist = None
#
self.y_data = None
self.z_data = None
if plot_dim == 1:
self.win.gpbx_col_scheme.setEnabled(False)
self.plt_main = self.plot_layout_widget.addPlot(row=0, col=0)
self.data_line = self.plt_main.plot([], [])
self.update_all_cursors()
self.update_all_anal_cursors()
else:
self.win.gpbx_col_scheme.setEnabled(True)
self.plt_main = self.plot_layout_widget.addPlot(row=1, col=1)
self.plt_curs_x = self.plot_layout_widget.addPlot(row=0, col=1)
self.data_curs_x = [self.plt_curs_x.plot([],[],pen=pg.mkPen(self.cursors[x][2])) for x in range(len(self.cursors))]
self.plt_curs_x.setXLink(self.plt_main)
self.plt_curs_y = self.plot_layout_widget.addPlot(row=1, col=0)
self.data_curs_y = [self.plt_curs_y.plot([],[],pen=pg.mkPen(self.cursors[x][2])) for x in range(len(self.cursors))]
self.plt_curs_y.showAxis('right')
self.plt_curs_y.hideAxis('left')
self.plt_curs_y.invertX(True)
self.plt_curs_y.setYLink(self.plt_main)
self.plt_colhist = self.plot_layout_widget.addPlot(row=0, col=0)
self.data_colhist = self.plt_colhist.plot([],[])
self.data_img = pg.ImageItem()
self.plt_main.addItem( self.data_img )
self.update_all_cursors()
self.update_all_anal_cursors()
cm = self.colour_maps[self.win.cmbx_ckey.currentIndex()].CMap
self.colBarItem = pg.ColorBarItem( values= (0, 1), colorMap=cm, orientation='horizontal' , interactive=False)
self.colBarItem.setImageItem( self.data_img, insert_in=self.plt_colhist )
self.set_colbar_cursors(int(self.win.cmbx_colbar_num_marks.currentText()))
self.plot_layout_widget.ci.layout.setRowStretchFactor(0, 1)
self.plot_layout_widget.ci.layout.setRowStretchFactor(1, 4)
self.plot_layout_widget.ci.layout.setColumnStretchFactor(0, 1)
self.plot_layout_widget.ci.layout.setColumnStretchFactor(1, 4)
self.plot_type = plot_dim
def find_new_colour(self, used_colours):
col = ''
col_pool = ['r', 'g', 'b', 'c', 'm', 'y', 'w']
for cur_cand_col in col_pool:
if not cur_cand_col in used_colours:
col = cur_cand_col
break
#Just pick random colour if all colours are already taken...
if col == '':
import random
col = col_pool[random.randint(0, len(col_pool)-1)]
return col
def get_text_colour(self, col):
textcol = pg.mkPen(col)
return QtGui.QColor(textcol.color().red(), textcol.color().green(), textcol.color().blue(), 255)
def update_cursor_x(self, curse_num, leCursor=None):
#Run the cursors
if self.cursors[curse_num][3] == None:
cur_x, cur_y = self.cursors[curse_num][:2]
else:
cur_x, cur_y = self.cursors[curse_num][3].get_value()
self.cursors[curse_num][1] = cur_y
self.update_lstbx_cursors()
if not isinstance(self.y_data, np.ndarray) or len(self.data_curs_x) <= curse_num:
return
ind = np.argmin(np.abs(cur_y - self.y_data))
self.data_curs_x[curse_num].setData(self.x_data, self.z_data[:,ind])
def update_cursor_y(self, curse_num, leCursor=None):
#Run the cursors
if self.cursors[curse_num][3] == None:
cur_x, cur_y = self.cursors[curse_num][:2]
else:
cur_x, cur_y = self.cursors[curse_num][3].get_value()
self.cursors[curse_num][0] = cur_x
self.update_lstbx_cursors()
if not isinstance(self.y_data, np.ndarray) or len(self.data_curs_x) <= curse_num:
return
ind = np.argmin(np.abs(cur_x - self.x_data))
self.data_curs_y[curse_num].setData(self.z_data[ind,:], self.y_data)
def update_all_cursors(self):
new_cursors = []
for m, cur_curse in enumerate(self.cursors):
new_cursor_obj = Cursor_Cross(cur_curse[0], cur_curse[1], cur_curse[2]) #clear() deletes the C++ object!
new_cursors += [[cur_curse[0], cur_curse[1], cur_curse[2], new_cursor_obj]]
new_cursor_obj.connect_plt_to_move_event(self.plt_main)
self.plt_main.addItem(new_cursor_obj)
new_cursor_obj.sigChangedCurX.connect(partial(self.update_cursor_y, m))
new_cursor_obj.sigChangedCurY.connect(partial(self.update_cursor_x, m))
self.cursors = new_cursors
def update_lstbx_cursors(self):
while self.win.lstbx_cursors.count() > len(self.cursors):
self.win.lstbx_cursors.takeItem(self.win.lstbx_cursors.count()-1)
while self.win.lstbx_cursors.count() < len(self.cursors):
self.win.lstbx_cursors.addItem('')
for m in range(len(self.cursors)):
cur_x, cur_y, col = self.cursors[m][:3]
self.win.lstbx_cursors.item(m).setText(f"X: {self._get_units(cur_x)}, Y: {self._get_units(cur_y)}")
self.win.lstbx_cursors.item(m).setForeground(QtGui.QBrush(pg.mkBrush(col)))
#Update differential cursors
if len(self.cursors) > 1:
self.win.tbl_cursor_diffs.setVisible(True)
#Generate combinations to show
show_combs = []
for m in range(len(self.cursors)-1):
for n in range(m+1,len(self.cursors)):
show_combs += [(m,n)]
#Add differences to the table
cur_table = self.win.tbl_cursor_diffs
cur_table.setRowCount(len(show_combs))
for m, cur_comb in enumerate(show_combs):
textcol = self.get_text_colour(self.cursors[cur_comb[0]][2])
item = QtWidgets.QTableWidgetItem('■'); item.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
item.setForeground(textcol)
cur_table.setItem(m,0,item)
#
textcol = self.get_text_colour(self.cursors[cur_comb[1]][2])
item = QtWidgets.QTableWidgetItem('■'); item.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
item.setForeground(textcol)
cur_table.setItem(m,1,item)
#
dx = self.cursors[cur_comb[0]][0]-self.cursors[cur_comb[1]][0]
item = QtWidgets.QTableWidgetItem(f'{self._get_units(dx)}')
item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
cur_table.setItem(m,2,item)
#
dy = self.cursors[cur_comb[0]][1]-self.cursors[cur_comb[1]][1]
item = QtWidgets.QTableWidgetItem(f'{self._get_units(dy)}')
item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
cur_table.setItem(m,3,item)
#
if abs(dx) > 0:
item = QtWidgets.QTableWidgetItem(f'{self._get_units(1/dx)}')
else:
item = QtWidgets.QTableWidgetItem(f'N/A')
item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
cur_table.setItem(m,4,item)
#
if abs(dy) > 0:
item = QtWidgets.QTableWidgetItem(f'{self._get_units(1/dy)}')
else:
item = QtWidgets.QTableWidgetItem(f'N/A')
item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
cur_table.setItem(m,5,item)
else:
self.win.tbl_cursor_diffs.setVisible(False)
def _event_btn_cursor_add(self):
if self.plt_main != None:
xRng = self.plt_main.getAxis('bottom').range
yRng = self.plt_main.getAxis('left').range
x,y = 0.5*(xRng[0]+xRng[1]), 0.5*(yRng[0]+yRng[1])
else:
x,y = 0,0
#Find new colour
col = self.find_new_colour([x[2] for x in self.cursors])
#
if self.plt_main == None:
self.cursors += [[x,y, col, None]]
else:
obj = Cursor_Cross(x, y, col)
self.cursors += [[x,y, col, obj]]
obj.connect_plt_to_move_event(self.plt_main)
self.plt_main.addItem(obj)
if self.plot_type == 2:
self.data_curs_x += [self.plt_curs_x.plot([],[],pen=pg.mkPen(col))]
self.data_curs_y += [self.plt_curs_y.plot([],[],pen=pg.mkPen(col))]
m = len(self.cursors) - 1
obj.sigChangedCurX.connect(partial(self.update_cursor_y, m))
obj.sigChangedCurY.connect(partial(self.update_cursor_x, m))
self.update_lstbx_cursors()
def _event_btn_cursor_del(self):
sel_ind = self.get_listbox_sel_ind(self.win.lstbx_cursors)
if sel_ind == -1:
return
cur_curse = self.cursors.pop(sel_ind)
if self.plot_type == 2:
self.data_curs_x.pop(sel_ind).clear()
self.data_curs_y.pop(sel_ind).clear()
self.plt_main.removeItem(cur_curse[3])
del cur_curse[3]
self.update_lstbx_cursors()
def _event_btn_cursor_reset(self):
if not isinstance(self.x_data, np.ndarray) or not isinstance(self.y_data, np.ndarray):
return
xMin = self.x_data.min()
xMax = self.x_data.max()
yMin = self.y_data.min()
yMax = self.y_data.max()
new_x = 0.5*(xMin+xMax)
new_y = 0.5*(yMin+yMax)
for m in range(len(self.cursors)):
cur_x, cur_y = self.cursors[m][:2]
if cur_x < xMin or cur_x > xMax:
x = new_x
else:
x = cur_x
if cur_y < yMin or cur_y > yMax:
y = new_y
else:
y = cur_y
if self.cursors[m][3] == None:
self.cursors[m][:2] = x, y
else:
self.cursors[m][3].set_value(x, y)
for cur_curse in self.analysis_cursors:
cur_curse.reset_bounds((xMin,xMax, yMin,yMax))
def update_all_anal_cursors(self):
for cur_curse in self.analysis_cursors:
cur_curse.init_cursor(self.plt_main)
def _event_btn_anal_cursor_add(self):
cur_sel = self.win.cmbx_anal_cursors.currentText()
#
#Find previous names
prev_names = []
for cur_curse in self.analysis_cursors:
if cur_curse.Type == cur_sel:
prev_names += [cur_curse.Name]
#Choose new name
new_prefix = self.possible_cursors[cur_sel].Prefix
m = 0
while f'{new_prefix}{m}' in prev_names:
m += 1
new_name = f'{new_prefix}{m}'
#
#Find new colour
col = self.find_new_colour([x.Colour for x in self.analysis_cursors])
#
new_anal_curse = self.possible_cursors[cur_sel](new_name, col, self._event_anal_cursor_changed)
self.analysis_cursors += [new_anal_curse]
new_anal_curse.Visible = True #Set initial default to show cursor...
#
#Add to the table
cur_table = self.win.tbl_analy_cursors
num_prev_items = cur_table.rowCount()
cur_table.setRowCount(num_prev_items+1)
textcol = self.get_text_colour(col)
#
self._anal_cursor_add_block_event = True
item = QtWidgets.QTableWidgetItem()
item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
if new_anal_curse.Visible:
item.setCheckState(QtCore.Qt.Checked)
else:
item.setCheckState(QtCore.Qt.Unchecked)
item.setTextAlignment(QtCore.Qt.AlignHCenter) #TODO: Fix this - it doesn't work as it inserts text next to the check-box...
cur_table.setItem(num_prev_items,0,item)
item = QtWidgets.QTableWidgetItem(new_anal_curse.Name)
item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
item.setForeground(textcol)
cur_table.setItem(num_prev_items,1,item)
item = QtWidgets.QTableWidgetItem(new_anal_curse.Type)
item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
item.setForeground(textcol)
cur_table.setItem(num_prev_items,2,item)
item = QtWidgets.QTableWidgetItem(new_anal_curse.Summary)
item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
item.setForeground(textcol)
cur_table.setItem(num_prev_items,3,item)
self._anal_cursor_add_block_event = False
#
#Link to plot if applicable
if self.plt_main:
if not isinstance(self.x_data, np.ndarray) or not isinstance(self.y_data, np.ndarray):
xMin, xMax, yMin, yMax = 0,1,0,1
else:
xMin = self.x_data.min()
xMax = self.x_data.max()
yMin = self.y_data.min()
yMax = self.y_data.max()
new_anal_curse.init_cursor(self.plt_main, (xMin, xMax, yMin, yMax))
def _event_btn_anal_cursor_del(self):
cur_row = self.win.tbl_analy_cursors.currentRow()
if cur_row < 0: #It actually returns -1!!!
return
del_name = self.win.tbl_analy_cursors.item(cur_row,1).text()
self.win.tbl_analy_cursors.removeRow(cur_row)
#Assuming list and table are concurrent!!!
found_curse = self.analysis_cursors.pop(cur_row)
found_curse.release_from_plots()
if self.plt_main:
self.plt_main.removeItem(found_curse)
del found_curse
def _get_units(self, val):
if isinstance(val, float) or isinstance(val, int):
thinspace = u"\u2009"
def clip_val(value):
return f'{value:.12g}'
if np.abs(val) < 1e-6:
return f'{clip_val(val*1e9)}{thinspace}n'
if np.abs(val) < 1e-3:
return f'{clip_val(val*1e6)}{thinspace}μ'
if np.abs(val) < 1:
return f'{clip_val(val*1e3)}{thinspace}m'
if np.abs(val) < 1000:
return val
if np.abs(val) < 1e6:
return f'{clip_val(val*1e-3)}{thinspace}k'
if np.abs(val) < 1e9:
return f'{clip_val(val*1e-6)}{thinspace}M'
return f'{clip_val(val*1e-9)}{thinspace}G'
else:
return val
def set_colbar_cursors(self, num):
reset = len(self.colbar_cursors) != num
while len(self.colbar_cursors) > num - 2:
self.plt_colhist.removeItem( self.colbar_cursors.pop() )
while len(self.colbar_cursors) < num - 2:
self.colbar_cursors.append(Cursor_Vertical(0.7, 'red', self._callback_colbar_get_bounds))
self.plt_colhist.addItem(self.colbar_cursors[-1], ignoreBounds=True )
if reset:
self.reset_colbar_ticks()
def reset_colbar_ticks(self):
if isinstance(self.z_data, np.ndarray):
zMin = np.nanmin(self.z_data)
zMax = np.nanmax(self.z_data)
vals = np.linspace(zMin, zMax, len(self.colbar_cursors)+2)
else:
vals = np.linspace(0,1, len(self.colbar_cursors)+2)
for m, x in enumerate(vals[1:-1:]):
self.colbar_cursors[m].set_value(x)
def _callback_colbar_get_bounds(self):
if isinstance(self.z_data, np.ndarray):
return np.nanmin(self.z_data), np.nanmax(self.z_data)
else:
return 0, 1
def _event_chkbx_anal_cursor_show(self, item):
if self._anal_cursor_add_block_event or item.column() != 0:
return
self.analysis_cursors[item.row()].Visible = item.checkState() == QtCore.Qt.CheckState.Checked
def _event_anal_cursor_changed(self, anal_cursor):
for cur_row in range(self.win.tbl_analy_cursors.rowCount()):
if anal_cursor.Name == self.win.tbl_analy_cursors.item(cur_row,1).text():
self.win.tbl_analy_cursors.item(cur_row,3).setText(anal_cursor.Summary)
return
def _event_btn_get_attrs(self):
clip_str = f"File: {self.file_path}\n"
cb = self.app.clipboard()
cb.clear(mode=cb.Clipboard )
cb.setText(clip_str, mode=cb.Clipboard)
def _event_btn_get_fig(self):
#Store figure as a temporary image
exptr = pgExp.ImageExporter( self.plot_layout_widget.scene() )
exptr.export('tempClipFig.png')
cb = self.app.clipboard()
cb.clear(mode=cb.Clipboard )
cb.setImage(QtGui.QImage('tempClipFig.png'))
os.remove('tempClipFig.png')
def update_plot_data(self):
if self.data_extractor:
self.setup_plot_vars() #Mostly relevant for the directory version which may get more variables with time...
if self.data_extractor.data_ready():
(indep_params, final_data, dict_rem_slices) = self.data_extractor.get_data()
cur_var_ind = self.dep_vars.index(self.win.cmbx_dep_var.currentText())
if not self.update_plot_post_proc(indep_params, final_data):
#Not post-processed (hence not plotted) - so do so now...
if self.plot_type == 1 and len(indep_params) == 1:
self.plot_1D(indep_params[0], final_data[cur_var_ind], self.win.cmbx_dep_var.currentText())
elif self.plot_type == 2 and len(indep_params) == 2:
self.plot_2D(indep_params[0], indep_params[1], final_data[cur_var_ind])
#
#Populate the slice candidates
#
cur_lstbx_vals = []
prev_dict = self.dict_var_slices.copy()
self.dict_var_slices = {} #Clear previous dictionary and only leave entries if it had previous slices present...
#Gather currently selected value so it stays selected
cur_sel = self.get_listbox_sel_ind(self.win.lstbx_param_slices)
if cur_sel != -1:
cur_var = self.cur_slice_var_keys_lstbx[cur_sel]
else:
cur_var = ""
cur_sel = -1
#Update the current list of slicing variables with the new list...
self.cur_slice_var_keys_lstbx = []
for m, cur_key in enumerate(dict_rem_slices.keys()):
#Check if key already exists
if cur_key in prev_dict:
self.dict_var_slices[cur_key] = (prev_dict[cur_key][0], dict_rem_slices[cur_key])
else:
self.dict_var_slices[cur_key] = (0, dict_rem_slices[cur_key])
cur_lstbx_vals += [self._slice_Var_disp_text(cur_key, self.dict_var_slices[cur_key])]
self.cur_slice_var_keys_lstbx += [cur_key]
if cur_var == cur_key:
cur_sel = m
self.listbox_safe_clear(self.win.lstbx_param_slices)
for ind, cur_val in enumerate(cur_lstbx_vals):
cur_item = QtWidgets.QListWidgetItem(cur_val)
self.win.lstbx_param_slices.addItem(cur_item)
if cur_sel == ind:
self.win.lstbx_param_slices.setCurrentItem(cur_item)
#Setup new request if no new data is being fetched
if not self.data_extractor.isFetching:
#Get current update time
cur_update_time = 1 #self.update_times[self.cmbx_update_rate.get_sel_val(True)]
cur_elapsed = time.time() - self.last_update_time
#Request new data if it's time to update (i.e. comparing the time since last update with a non-zero update time)
if (cur_update_time > 0 and cur_elapsed > cur_update_time): #self.man_update_plot or
xVar = str(self.win.cmbx_axis_x.currentText())
slice_vars = {}
for cur_var in self.dict_var_slices.keys():
slice_vars[cur_var] = self.dict_var_slices[cur_var][0]
if self.plot_type == 1:
self.data_extractor.fetch_data({'axis_vars':[xVar], 'slice_vars':slice_vars})
else:
yVar = str(self.win.cmbx_axis_y.currentText())
if xVar != yVar:
self.data_extractor.fetch_data({'axis_vars':[xVar, yVar], 'slice_vars':slice_vars})
else:
self.write_statusbar("X and Y axes must be different for a 2D plot")
self.last_update_time = time.time()
def listbox_safe_clear(self, listbox):
for i in range(listbox.count()):
item = listbox.item(i)
item.setSelected(False)
listbox.clear()
def get_listbox_sel_inds(self, listbox):
return [x.row() for x in listbox.selectedIndexes()]
def get_listbox_sel_ind(self, listbox):
cur_ind = self.get_listbox_sel_inds(listbox)
if len(cur_ind) == 0: #i.e. empty
return -1
else:
return cur_ind[0]
def _reset_thrds_and_files(self):
if self.data_thread_pool == None:
self.data_thread_pool = ThreadPool(processes=2)
if self.data_extractor != None:
self.data_extractor.close_file()
self.data_thread_pool = ThreadPool(processes=2)
def _event_btn_open_H5(self):
fileName = QtWidgets.QFileDialog.getOpenFileName(self.win, self.app.tr("Open HDF5 File"), "", self.app.tr("HDF5 Files (*.h5)"))
if fileName[0] != '':
self._reset_thrds_and_files()
self.data_extractor = DataExtractorH5single(fileName[0], self.data_thread_pool)
win_str = '/'.join(fileName[0].split('/')[-2:]) #Assuming that it'll always have one slash (e.g. drive letter itself)
self.win.setWindowTitle(f'{self.default_win_title} - HDF5-File: {win_str}')
self.file_path = fileName[0]
self.setup_plot_vars()
def _event_btn_open_H5dir(self):
fileName = QtWidgets.QFileDialog.getOpenFileName(self.win, self.app.tr("Open HDF5 File"), "", self.app.tr("HDF5 Files (*.h5)"))
if fileName[0] != '':
self._reset_thrds_and_files()
self.data_extractor = DataExtractorH5multiple(fileName[0], self.data_thread_pool)
win_str = '/'.join(fileName[0].split('/')[-3:]) #Assuming that it'll always have one slash (e.g. drive letter itself)
self.win.setWindowTitle(f'{self.default_win_title} - HDF5-Directory: {win_str}')
self.file_path = fileName[0]
self.setup_plot_vars()
def _event_btn_open_DAT(self):
fileName = QtWidgets.QFileDialog.getOpenFileName(self.win, self.app.tr("Open UQTools DAT File"), "", self.app.tr("UQTools DAT (*.dat)"))
if fileName[0] != '':
self._reset_thrds_and_files()
self.data_extractor = DataExtractorUQtoolsDAT(fileName[0], self.data_thread_pool)
win_str = '/'.join(fileName[0].split('/')[-2:]) #Assuming that it'll always have one slash (e.g. drive letter itself)
self.win.setWindowTitle(f'{self.default_win_title} - UQTools DAT-File: {win_str}')
self.file_path = fileName[0]
self.setup_plot_vars()
def _open_file_prev(self):
if not isinstance(self.data_extractor, DataExtractorH5single):
return
cur_file = self.data_extractor.file_name
cur_exp_dir = os.path.dirname(cur_file)
cur_parent_dir = os.path.dirname(cur_exp_dir) + '/' #Should exist...
#
dirs = [x[0] for x in os.walk(cur_parent_dir)]
cur_ind = dirs.index(cur_exp_dir)
cur_ind = cur_ind - 1
filename = ''
while cur_ind > 0: #Presuming that the first directory is the base path...
cur_file = dirs[cur_ind]+'/data.h5'
if os.path.exists(cur_file):
filename = cur_file
break
cur_ind = cur_ind - 1
if filename == '':
return
self._reset_thrds_and_files()
self.data_extractor = DataExtractorH5single(filename, self.data_thread_pool)
self.file_path = filename
self.setup_plot_vars()
def _open_file_next(self):
if not isinstance(self.data_extractor, DataExtractorH5single):
return
cur_file = self.data_extractor.file_name
cur_exp_dir = os.path.dirname(cur_file)
cur_parent_dir = os.path.dirname(cur_exp_dir) + '/' #Should exist...
#
dirs = [x[0] for x in os.walk(cur_parent_dir)]
cur_ind = dirs.index(cur_exp_dir)
cur_ind = cur_ind + 1
filename = ''
while cur_ind < len(dirs):
cur_file = dirs[cur_ind]+'/data.h5'
if os.path.exists(cur_file):
filename = cur_file
break
cur_ind = cur_ind + 1
if filename == '':
return
self._reset_thrds_and_files()
self.data_extractor = DataExtractorH5single(filename, self.data_thread_pool)
self.file_path = filename
self.setup_plot_vars()
def _export_npy_matplotlib(self):
if not isinstance(self.x_data, np.ndarray) or not isinstance(self.y_data, np.ndarray):
return
fileName = QtWidgets.QFileDialog.getSaveFileName(self.win, self.app.tr("Export NPY and PY"), "", self.app.tr("Numpy Files (*.npy)"))
if fileName[0] != '':
npy_file = fileName[0]
python_file = fileName[0][:-3]+'py'
if not isinstance(self.z_data, np.ndarray):
np.save(npy_file, {'x_data':self.x_data, 'y_data':self.y_data})
#
with open('Miscellaneous/PythonExportTemplate1D.py', 'r', encoding="utf-8") as file:
filedata = file.read()
filedata = filedata.replace('LEFILENAME', npy_file)
with open(python_file, 'w', encoding='utf-8') as file:
file.write(filedata)
else:
#Colour Bar...
minZ, maxZ = self._callback_colbar_get_bounds()
mkr_pts = [0] + [(x.get_value()-minZ)/(maxZ-minZ) for x in self.colbar_cursors] + [1]
#
dict_data = {'x_data':self.x_data, 'y_data':self.y_data, 'z_data':self.z_data}
if len(self.cursors) > 0:
dict_data['cursor_x'] = np.vstack([cur_cursor.getData()[1] for cur_cursor in self.data_curs_x])
dict_data['cursor_y'] = np.vstack([cur_cursor.getData()[0] for cur_cursor in self.data_curs_y])
#
with open('Miscellaneous/PythonExportTemplate2D.py', 'r', encoding="utf-8") as file:
filedata = file.read()
filedata = filedata.replace('LEFILENAME', npy_file)
#
#CURSORS
filedata = filedata.split('#CURSORPREPARE\n')
if len(self.cursors) > 0:
filedata = ''.join(filedata)
filedata = filedata.split('#CURSORPLOT\n')
filedata = ''.join(filedata)
else:
filedata = filedata[0] + filedata[2]
filedata = filedata.split('#CURSORPLOT\n')
filedata = filedata[0] + filedata[2]
#
#COLOUR-BAR MARKERS
filedata = filedata.split('#HISTNORM\n')
if len(mkr_pts) > 2:
filedata = ''.join(filedata)
dict_data['colorbar'] = mkr_pts
else:
filedata = filedata[0] + filedata[2]
#
#COLOUR-MAP
cur_cmap = self.win.cmbx_ckey.currentIndex()
if cur_cmap < len(self._def_col_maps):
filedata = filedata.replace('LECUSTOMCOLOURMAP', f"'{self._def_col_maps[cur_cmap][0]}'")
else:
filedata = filedata.replace('LECUSTOMCOLOURMAP', "matplotlib.colors.LinearSegmentedColormap.from_list('custom', raw_data.item().get('cmap'))")
dict_data['cmap'] = self._aux_col_maps[cur_cmap - len(self._def_col_maps)]
np.save(npy_file, dict_data)
with open(python_file, 'w', encoding='utf-8') as file:
file.write(filedata)
def _post_procs_update_configs_from_file(self):
#Create file if it does not exist...
if not os.path.isfile('config_post_procs.json'):
with open('config_post_procs.json', 'w') as outfile:
json.dump({}, outfile, indent=4)
self._avail_post_proc_configs = {}
self.listbox_safe_clear(self.win.cmbx_proc_list_open)
return
#
with open('config_post_procs.json', 'r') as outfile:
self._avail_post_proc_configs = json.load(outfile)
self.win.cmbx_proc_list_open.clear()
self.win.cmbx_proc_list_open.addItems(self._avail_post_proc_configs.keys())
def _event_btn_proc_list_open(self):
cur_file = str(self.win.cmbx_proc_list_open.currentText())
if cur_file == '':
return
#Transfer the configuration (gathered from the file earlier) into the current list of post-processors
self.cur_post_procs = self._avail_post_proc_configs[cur_file]
#Create the post-processor objects appropriately
for cur_proc in self.cur_post_procs:
cur_proc['ProcessObj'] = self.post_procs_all[cur_proc['ProcessName']]
#Select the last post-processor to display...
self._post_procs_fill_current(len(self.cur_post_procs)-1)
def _event_btn_proc_list_save(self):
self._post_procs_update_configs_from_file()
cur_name = self.win.tbx_proc_list_save.text()
if cur_name == "":
return
self._avail_post_proc_configs[cur_name] = self.cur_post_procs
with open('config_post_procs.json', 'w') as outfile:
json.dump(self._avail_post_proc_configs, outfile, indent=4, default=lambda o: '<not serializable>')
self._post_procs_update_configs_from_file()
def _slice_Var_disp_text(self, slice_var_name, cur_slice_var_params):
'''
Generates the text to display the summary in the ListBox for slicing variables.
Input:
- slice_var_name - String name of the current slicing variable to display in the ListBox
- cur_slice_var_params - A tuple given as (current index, numpy array of allowed values)
Returns a string of the text to display - i.e. Name current-val (min-val, max-val).
'''
cur_val = cur_slice_var_params[1][cur_slice_var_params[0]]
return f"{slice_var_name}: {cur_val}"
def _event_slice_var_selection_changed(self):
cur_ind = self.get_listbox_sel_ind(self.win.lstbx_param_slices)
if cur_ind == -1: #i.e. empty
return
cur_slice_var = self.dict_var_slices[self.cur_slice_var_keys_lstbx[cur_ind]]
self.win.sldr_param_slices.setMinimum(0)
self.win.sldr_param_slices.setMaximum(cur_slice_var[1].size-1)
self.win.sldr_param_slices.setValue(cur_slice_var[0])
self._update_label_slice_var_val(cur_ind)
def _update_label_slice_var_val(self, var_ind):
#Update Label (should be safe as the callers have verified that there is a selected index...)
cur_var_name = self.cur_slice_var_keys_lstbx[var_ind]
min_val = np.min(self.dict_var_slices[cur_var_name][1])
max_val = np.max(self.dict_var_slices[cur_var_name][1])
self.win.lbl_param_slices.setText(f"Range: {min_val}➜{max_val}")
def _event_sldr_slice_vars_val_changed(self):
new_index = self.win.sldr_param_slices.value()
#Calculate the index of the array with the value closest to the proposed value
cur_sel_ind = self.get_listbox_sel_ind(self.win.lstbx_param_slices)
if cur_sel_ind == -1: #i.e. empty
return
cur_var_name = self.cur_slice_var_keys_lstbx[cur_sel_ind]
if new_index != self.dict_var_slices[cur_var_name][0]:
#Update the array index
self.dict_var_slices[cur_var_name] = (new_index, self.dict_var_slices[cur_var_name][1])
#Update ListBox
item = self.win.lstbx_param_slices.item(cur_sel_ind)
item.setText(self._slice_Var_disp_text(cur_var_name, self.dict_var_slices[cur_var_name]))
#Update Label
self._update_label_slice_var_val(cur_sel_ind)
def _event_btn_slice_vars_val_inc(self):
cur_sel_ind = self.get_listbox_sel_ind(self.win.lstbx_param_slices)
if cur_sel_ind == -1:
return
cur_var_name = self.cur_slice_var_keys_lstbx[cur_sel_ind]
cur_len = self.dict_var_slices[cur_var_name][1].size
cur_ind = int(float(self.win.sldr_param_slices.value()))
if cur_ind + 1 < cur_len:
self.win.sldr_param_slices.setValue(cur_ind + 1)
def _event_btn_slice_vars_val_dec(self):
cur_sel_ind = self.get_listbox_sel_ind(self.win.lstbx_param_slices)
if cur_sel_ind == -1:
return
cur_ind = int(float(self.win.sldr_param_slices.value()))
if cur_ind > 0:
self.win.sldr_param_slices.setValue(cur_ind - 1)
def _event_lstbxPPfunction_changed(self):
sel_items = self.win.lstbx_plot_analy_funcs.selectedItems()
if len(sel_items) == 0: #i.e. empty - shouldn't happen as it should be safe as it's only populated once; but just in case...
return
cur_func = sel_items[0].text()
self.win.lbl_plot_analy_funcs.setText( "Description: " + self.post_procs_all[cur_func].get_description() )
def _event_btn_post_proc_add(self):
sel_items = self.win.lstbx_plot_analy_funcs.selectedItems()
if len(sel_items) == 0: #i.e. empty - shouldn't happen as it should be safe as it's only populated once; but just in case...
return
cur_func = sel_items[0].text()
cur_func_obj = self.post_procs_all[cur_func]
self.cur_post_procs += [{
'ArgsInput' : cur_func_obj.get_default_input_args(),
'ArgsOutput' : cur_func_obj.get_default_output_args(),
'ProcessName' : cur_func,
'ProcessObj' : cur_func_obj,
'Enabled' : True
}]
self._post_procs_fill_current(len(self.cur_post_procs)-1)
def _post_procs_current_disp_text(self, cur_proc):
'''
Generates the string shown in each entry in the ListBox of current processes used in the post-processing.
Inputs:
cur_proc - Current process to be displayed. It is simply one of the tuples in the array self.cur_post_procs.
'''
#Filter to only show the data arguments
arr_args_in = []
for ind, cur_arg in enumerate(cur_proc['ProcessObj'].get_input_args()):
if cur_arg[1] == 'data':
arr_args_in += [cur_proc['ArgsInput'][ind]]
arr_args_in = tuple(arr_args_in)
#
arr_args_out = []
for ind, cur_arg in enumerate(cur_proc['ProcessObj'].get_output_args()):
if cur_arg[1] == 'data':
arr_args_out += [cur_proc['ArgsOutput'][ind]]
arr_args_out = tuple(arr_args_out)
#
#If all arguments are to be shown, comment the above and uncomment that below:
# arr_args_in = tuple(cur_proc['ArgsInput'])
# arr_args_out = tuple(cur_proc['ArgsOutput'])
#Note that it also has to be changed in callback functions like _callback_tbx_post_procs_disp_callback_Int etc...
if cur_proc['Enabled']:
cur_str = ""
else:
cur_str = "⊘"
cur_str += str(arr_args_in)
cur_str += "→"
cur_str += cur_proc['ProcessName']
cur_str += "→"
cur_str += str(arr_args_out)
return cur_str.replace('\'','')
def _post_procs_fill_current(self, sel_index = -1):
cur_proc_strs = []
for cur_proc in self.cur_post_procs:
cur_proc_strs += [self._post_procs_current_disp_text(cur_proc)]
cur_proc_strs += ["Final Output: "+self.cur_post_proc_output]
self.listbox_safe_clear(self.win.lstbx_cur_post_procs)
self.win.lstbx_cur_post_procs.addItems(cur_proc_strs)
if sel_index != -1: