-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwxFilter.py
1991 lines (1773 loc) · 89.1 KB
/
wxFilter.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
'''
Filter GUI
Author: Craig Biwer ([email protected])
7/17/2012
'''
import h5py
import math
import os
import time
import wx
import wx.lib.agw.customtreectrl as treemix
import wx.lib.mixins.listctrl as listmix
import wx.lib.agw.ultimatelistctrl as ULC
import file_locker
import filtertools as ft
import mastertoproject as mtp
from instrumentconfig import InstrumentConfiguration
import traceback
from xml.etree.ElementTree import ParseError
POSSIBLE_ATTRIBUTES = ['bad_pixel_map', 'beam_slits', 'bgrflag',
'cnbgr', 'cpow', 'ctan', 'cwidth',
'det_slits', 'geom', 'rnbgr', 'roi', 'rotangle',
'rpow', 'rtan', 'rwidth', 'sample_angles',
'sample_diameter', 'sample_polygon', 'scale']
class filterGUI(wx.Frame):
#class filterGUI(wx.Frame, wxUtil):
'''The GUI window for filtering.'''
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, args[0], -1, title='HDF Project File Builder',
size=(1440, 890))
# Set up shell
#self.shell = None
#self.init_shell()
# The file being filtered
self.filterFile = None
# The associated lock file
self.filterLock = None
#self.set_data('filter_file', self.filterFile)
# All the scans parsed from the file
self.scanItems = []
# The attribute dictionary
self.attrDict = {}
# The possible specfiles
self.allSpecs = {}
# The possible HK pairs
self.allHK = {}
# The possible L values
self.LMin, self.LMax = (float('inf'), float('-inf'))
# The possible scan types
self.allTypes = {}
# The various lists to be passed to the filters
self.possibleYears = []
# The earliest and latest scan dates (epoch format)
self.dateMin, self.dateMax = (float('inf'), float('-inf'))
# The 'More Info:' text
self.allInfo = {}
# The total filter results
self.activeFilters = []
# The results of the spec filter
self.specResult = None
self.specCases = None
# The results of the HK filter
self.hkResult = None
self.hkCases = None
# The results of the L filter
self.LResult = None
self.LCases = None
# The results of the type filter
self.typeResult = None
self.typeCases = None
# The results of the date filter
self.dateResult = None
self.dateCases = None
# The project to be built
self.projectDict = {}
# Instrument configuration file. Map name of parameter coming from the Spec file
self.instConfigFile = InstrumentConfiguration(None)
# Make the window
self.fullWindow = wx.Panel(self)
###############################################################
# In the window:
# fullSizer holds three vertical sizers:
# leftSizer holds the table and associated buttons on the left
# middleSizer holds info in the middle
# rightSizer holds the project layout
###############################################################
self.fullSizer = wx.BoxSizer(wx.HORIZONTAL)
self.leftSizer = wx.BoxSizer(wx.VERTICAL)
self.leftPanel = wx.Panel(self.fullWindow)
self.middleSizer = wx.BoxSizer(wx.VERTICAL)
self.middlePanel = wx.Panel(self.fullWindow)
self.rightSizer = wx.BoxSizer(wx.VERTICAL)
self.rightPanel = wx.Panel(self.fullWindow)
###############################################################
# On the left:
# filterButtonSizer holds the filtering buttons
# tableSizer holds the table in which the scans are displayed
# managementSizer holds the 'Keep Selected' and reset buttons
###############################################################
# The filter buttons
self.filterButtonSizer = wx.BoxSizer(wx.HORIZONTAL)
# Filter by specfile / scan number
self.specButton = wx.Button(self.leftPanel, label='Filter Specfiles ' +
'and Scan #s',
size=(-1, 32))
# Filter by HK pair
self.hkButton = wx.Button(self.leftPanel, label='Filter HKs',
size=(-1, 32))
# Filter by L range
self.LButton = wx.Button(self.leftPanel, label='Filter L Range',
size=(-1, 32))
# Filter by type
self.typeButton = wx.Button(self.leftPanel, label='Filter Types',
size=(-1, 32))
# Filter by date range
self.dateButton = wx.Button(self.leftPanel, label='Filter Date Range',
size=(-1, 32))
# Populate the sizer
self.filterButtonSizer.Add(self.specButton, proportion=210,#168,
flag=wx.EXPAND | wx.TOP | wx.BOTTOM,
border=8)
self.filterButtonSizer.Add(self.hkButton, proportion=79,
flag=wx.EXPAND | wx.TOP | wx.BOTTOM,
border=8)
self.filterButtonSizer.Add(self.LButton, proportion=121,
flag=wx.EXPAND | wx.TOP | wx.BOTTOM,
border=8)
self.filterButtonSizer.Add(self.typeButton, proportion=67,
flag=wx.EXPAND | wx.TOP | wx.BOTTOM,
border=8)
self.filterButtonSizer.AddStretchSpacer(57)
self.filterButtonSizer.Add(self.dateButton, proportion=176,
flag=wx.EXPAND | wx.TOP | wx.BOTTOM,
border=8)
# The data table
self.tableSizer = wx.BoxSizer(wx.HORIZONTAL)
# The multicolumn list serving as the data table
self.dataTable = TableDataCtrl(self.leftPanel, style=wx.LC_REPORT |
wx.LC_HRULES |
wx.LC_VRULES)
self.dataTable.InsertColumn(0, heading='Specfile', width=165)
self.dataTable.InsertColumn(1, heading='#', width=40)
self.dataTable.InsertColumn(2, heading='H Val', width=40)
self.dataTable.InsertColumn(3, heading='K Val', width=38)
self.dataTable.InsertColumn(4, heading='L Start', width=60)
self.dataTable.InsertColumn(5, heading='L Stop', width=60)
self.dataTable.InsertColumn(6, heading='Scan Type', width=66)
self.dataTable.InsertColumn(7, heading='Aborted', width=56)
self.dataTable.InsertColumn(8, heading='Date')
# Add the table to the sizer so it scales properly
self.tableSizer.Add(self.dataTable, proportion=1, flag=wx.EXPAND |
wx.BOTTOM,
border=2)
# The 'Keep Selected' and reset buttons
self.managementSizer = wx.BoxSizer(wx.HORIZONTAL)
# 'Keep Selected' button
self.keepButton = wx.Button(self.leftPanel, label='Keep Selected')
# Reset Button
self.resetButton = wx.Button(self.leftPanel,
label='Reset Filters')# and Reread Data')
# Reread Button
self.rereadButton = wx.Button(self.leftPanel, label='Reread Data')
# Populate the sizer
self.managementSizer.Add(self.keepButton, proportion=2,
flag=wx.EXPAND | wx.BOTTOM, border=2)
self.managementSizer.AddStretchSpacer(5)
self.managementSizer.Add(self.resetButton, proportion=2,
flag=wx.EXPAND | wx.BOTTOM | wx.RIGHT,
border=2)
self.managementSizer.Add(self.rereadButton, proportion=2,
flag=wx.EXPAND | wx.BOTTOM | wx.LEFT, border=2)
# Add a border line
self.managementSizer.Add(wx.StaticLine(self.leftPanel, size=(2, 24)),
flag=wx.LEFT, border=16)
# Arrange the left panel
self.leftSizer.Add(self.filterButtonSizer, proportion=0, flag=wx.EXPAND)
self.leftSizer.Add(self.tableSizer, proportion=1, flag=wx.EXPAND)
self.leftSizer.Add(self.managementSizer, proportion=0,
flag=wx.EXPAND | wx.TOP | wx.BOTTOM, border=4)
self.leftPanel.SetSizerAndFit(self.leftSizer)
###############################################################
# End of the left layout
###############################################################
###############################################################
# In the middle:
# fileSizer holds the filename text
# newAttributeSizer holds attribute adder and list
# Everything else is placed directly into middleSizer
###############################################################
# The file name texts
self.fileSizer = wx.BoxSizer(wx.HORIZONTAL)
# The static text
self.fileLabel = wx.StaticText(self.middlePanel, label='File Name: ')
# The load master file button (changes label based on current file)
self.fileButton = wx.Button(self.middlePanel,
label='Load Master File...')
# Populate the sizer:
self.fileSizer.Add(self.fileLabel, flag=wx.CENTER)
self.fileSizer.Add(self.fileButton, proportion=1,
flag=wx.EXPAND | wx.RIGHT, border=20)
# The middle contents
# The 'More Info:' label
self.moreLabel = wx.StaticText(self.middlePanel, label='More Info:\n')
# The 'More Info' text box
self.moreBox = wx.TextCtrl(self.middlePanel, style=wx.TE_MULTILINE |
wx.TE_READONLY)
# The move buttons
self.rightOne = wx.Button(self.middlePanel, label='>')
self.leftOne = wx.Button(self.middlePanel, label='<')
self.rightAll = wx.Button(self.middlePanel, label='>>')
self.leftAll = wx.Button(self.middlePanel, label='<<')
# Tooltips for the move buttons
self.rightOne.SetToolTipString('Move selected to project')
self.leftOne.SetToolTipString('Remove selected from project')
self.rightAll.SetToolTipString('Move all to project')
self.leftAll.SetToolTipString('Remove all from project')
# The new attribute adder line
self.newAttributeSizer = wx.BoxSizer(wx.HORIZONTAL)
# The drop down list
self.attrSelect = wx.Choice(self.middlePanel, size=(110, -1))
self.attrSelect.SetItems(POSSIBLE_ATTRIBUTES)
# The text box
self.attrSpecify = wx.TextCtrl(self.middlePanel)
# The add button
self.attrAdd = wx.Button(self.middlePanel, label='+', size=(40, -1))
# Arrange the attribute adder line
self.newAttributeSizer.Add(self.attrSelect)
self.newAttributeSizer.Add(self.attrSpecify, proportion=1,
flag=wx.EXPAND)
self.newAttributeSizer.Add(self.attrAdd)
#self.newAttributeSizer.AddSpacer(19)
# The added attribute list
self.attrList = ULC.UltimateListCtrl(self.middlePanel,
agwStyle=wx.LC_REPORT |
wx.LC_VRULES |
wx.LC_HRULES |
ULC.ULC_HAS_VARIABLE_ROW_HEIGHT)
self.attrList.InsertColumn(0, 'Attribute', width=108)
self.attrList.InsertColumn(1, 'Value', width=40)
self.attrList.InsertColumn(2, '', width=36)
self.attrList.SetColumnWidth(1, ULC.ULC_AUTOSIZE_FILL)
# The load / save attribute buttons file line
self.loadSaveAttributeSizer = wx.BoxSizer(wx.HORIZONTAL)
# The load attribute button
self.loadAttrButton = wx.Button(self.middlePanel,
label='Load Attribute File...')
# The save attribute button
self.saveAttrButton = wx.Button(self.middlePanel,
label='Save Attribute File...')
# Arrange the load / save attribute buttons line
self.loadSaveAttributeSizer.Add(self.loadAttrButton, proportion=1,
flag=wx.EXPAND | wx.LEFT,
border=32)
self.loadSaveAttributeSizer.AddSpacer(16)
self.loadSaveAttributeSizer.Add(self.saveAttrButton, proportion=1,
flag=wx.EXPAND | wx.RIGHT,
border=32)
# Arrange the middle panel
self.middleSizer.Add(self.fileSizer, proportion=0,
flag=wx.EXPAND | wx.TOP | wx.LEFT, border=20)
# Add a border line
self.middleSizer.Add(wx.StaticLine(self.middlePanel, size=(332, 2)),
flag=wx.LEFT | wx.TOP | wx.RIGHT |
wx.EXPAND, border=16)
self.middleSizer.Add(self.moreLabel, proportion=0,
flag=wx.TOP | wx.LEFT, border=20)
self.middleSizer.Add(self.moreBox, proportion=1,
flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
border=24)
self.middleSizer.Add(self.rightOne, proportion=0,
flag=wx.CENTER | wx.TOP | wx.BOTTOM, border=4)
self.middleSizer.Add(self.leftOne, proportion=0,
flag=wx.CENTER | wx.TOP | wx.BOTTOM, border=4)
self.middleSizer.Add(self.rightAll, proportion=0,
flag=wx.CENTER | wx.TOP | wx.BOTTOM, border=4)
self.middleSizer.Add(self.leftAll, proportion=0,
flag=wx.CENTER | wx.TOP | wx.BOTTOM, border=4)
self.middleSizer.Add(self.newAttributeSizer, proportion=0,
flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP,
border=24)
self.middleSizer.Add(self.attrList, proportion=1,
flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
border=24)
self.middleSizer.AddSpacer(6)
self.middleSizer.Add(self.loadSaveAttributeSizer, flag=wx.EXPAND)
self.middleSizer.AddSpacer(6)
self.middlePanel.SetSizerAndFit(self.middleSizer)
###############################################################
# End of the middle layout
###############################################################
###############################################################
# On the right:
# projectNameSizer holds the project name label and box
# nextStepSizer holds the buttons for moving to the integrator
# Everything else is placed directly into rightSizer
###############################################################
# The project name label and box
self.projectNameSizer = wx.BoxSizer(wx.HORIZONTAL)
# The static label
self.projectNameText = wx.StaticText(self.rightPanel,
label='Project Name: ')
# The text box
self.projectNameBox = wx.TextCtrl(self.rightPanel)
# Populate the sizer
self.projectNameSizer.Add(self.projectNameText,
flag=wx.CENTER | wx.LEFT, border=8)
self.projectNameSizer.Add(self.projectNameBox, proportion=1,
flag=wx.EXPAND | wx.RIGHT, border=8)
# The new project tree box
self.newProjectTree = myTreeCtrl(self.rightPanel,
style=wx.TR_MULTIPLE |
wx.TR_EXTENDED |
wx.TR_DEFAULT_STYLE)
# The integrator buttons
self.nextStepSizer = wx.BoxSizer(wx.HORIZONTAL)
# Create a new integrator window
self.newIntegrator = wx.Button(self.rightPanel,
label='New Project File')
# Append scans to an existing integrator window
self.appendIntegrator = wx.Button(self.rightPanel,
label='Append Scans To...')
# Populate the sizer
self.nextStepSizer.Add(wx.StaticLine(self.rightPanel, size=(2, 24)),
flag=wx.LEFT | wx.RIGHT, border=1)
self.nextStepSizer.Add(self.newIntegrator, proportion=1,
flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=16)
self.nextStepSizer.Add(self.appendIntegrator, proportion=1,
flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=16)
# Arrange the right panel
self.rightSizer.Add(self.projectNameSizer, proportion=0,
flag=wx.EXPAND | wx.TOP, border=20)
self.rightSizer.Add(self.newProjectTree, proportion=1,
flag=wx.EXPAND | wx.TOP | wx.BOTTOM,
border=4)
self.rightSizer.Add(self.nextStepSizer, proportion=0,
flag=wx.EXPAND | wx.TOP | wx.BOTTOM,
border=4)
self.rightPanel.SetSizerAndFit(self.rightSizer)
###############################################################
# End of the right layout
###############################################################
self.fullSizer.Add(self.leftPanel, proportion=6,
flag=wx.EXPAND | wx.LEFT, border=8)
self.fullSizer.Add(self.middlePanel, proportion=3, flag=wx.EXPAND)
self.fullSizer.Add(self.rightPanel, proportion=3,
flag=wx.EXPAND | wx.RIGHT, border=8)
self.fullWindow.SetSizer(self.fullSizer)
###############################################################
# End of window arrangement
###############################################################
# Make the menu bar
self.menuBar = wx.MenuBar()
# The file menu
self.fileMenu = wx.Menu()
self.loadFile = self.fileMenu.Append(-1, 'Load HDF file...')
self.loadAttr = self.fileMenu.Append(-1, 'Load attribute file...')
self.loadInstConfig = self.fileMenu.Append(-1, 'Load Inst Config file...')
self.exitWindow = self.fileMenu.Append(-1, 'Exit')
self.menuBar.Append(self.fileMenu, 'File')
self.SetMenuBar(self.menuBar)
###############################################################
# Start bindings
###############################################################
# Menu bindings
self.Bind(wx.EVT_MENU, self.loadHDF, self.loadFile)
self.Bind(wx.EVT_MENU, self.loadAttributes, self.loadAttr)
self.Bind(wx.EVT_MENU, self.loadInstrumentConfig, self.loadInstConfig)
self.Bind(wx.EVT_MENU, self.onClose, self.exitWindow)
# Button bindings
# The specfile / number button
self.specButton.Bind(wx.EVT_BUTTON, self.filterSpec)
# The HK button
self.hkButton.Bind(wx.EVT_BUTTON, self.filterHK)
# The L button
self.LButton.Bind(wx.EVT_BUTTON, self.filterL)
# The type button
self.typeButton.Bind(wx.EVT_BUTTON, self.filterType)
# The date button
self.dateButton.Bind(wx.EVT_BUTTON, self.filterDate)
# The keep button
self.keepButton.Bind(wx.EVT_BUTTON, self.keepSelected)
# The reset button
self.resetButton.Bind(wx.EVT_BUTTON, self.resetFilters)
# The reread button
self.rereadButton.Bind(wx.EVT_BUTTON, self.readFile)
# The load project file button
self.fileButton.Bind(wx.EVT_BUTTON, self.loadHDF)
# The single right button
self.rightOne.Bind(wx.EVT_BUTTON, self.moveOneRight)
# The single left button
self.leftOne.Bind(wx.EVT_BUTTON, self.moveOneLeft)
# The all right button
self.rightAll.Bind(wx.EVT_BUTTON, self.moveAllRight)
# The all left button
self.leftAll.Bind(wx.EVT_BUTTON, self.moveAllLeft)
# The new attribute button
self.attrAdd.Bind(wx.EVT_BUTTON, self.addAttribute)
# The load attribute file button
self.loadAttrButton.Bind(wx.EVT_BUTTON, self.loadAttributes)
# The save attribute file button
self.saveAttrButton.Bind(wx.EVT_BUTTON, self.saveAttributes)
# The new button
self.newIntegrator.Bind(wx.EVT_BUTTON, self.newProject)
# The append button
self.appendIntegrator.Bind(wx.EVT_BUTTON, self.appendTo)
# Lost focus on the project name box (rename project tree)
self.projectNameBox.Bind(wx.EVT_KILL_FOCUS, self.newName)
# dataTable click
self.dataTable.Bind(wx.EVT_LIST_ITEM_SELECTED, self.tableClick)
# Window closed
self.Bind(wx.EVT_CLOSE, self.onClose)
###############################################################
# End bindings
###############################################################
# Because the 'Filter Specfile' button is created first,
# it automatically gets the focus. As a result, the button
# glows blue when the window first appears. To change this,
# we put the focus on a static text element before showing
# the window.
self.moreLabel.SetFocus()
self.Show()
# Choose and load an HDF file so it can be filtered
def loadHDF(self, event):
'''Open an HDF file and parse its contents into the filter.'''
loadDialog = wx.FileDialog(self, message='Load file...',
defaultDir=os.getcwd(), defaultFile='',
wildcard='Master files (*.mh5)|*.mh5|'+\
'All files (*.*)|*',
style=wx.OPEN)
if loadDialog.ShowModal() == wx.ID_OK:
if not os.path.isfile(loadDialog.GetPath()):
print 'Error: File does not exist'
return
# Clear all variables and update the table to
# prevent accidental access to the wrong file
del self.filterFile
self.filterFile = None
self.filterFileName = None
self.filterLock = None
self.scanItems = []
self.allSpecs = {}
self.allHK = {}
self.LMin, self.LMax = (float('inf'), float('-inf'))
self.allTypes = {}
self.possibleYears = []
self.dateMin, self.dateMax = (float('inf'), float('-inf'))
self.allInfo = {}
self.projectNameBox.SetValue('')
self.resetFilters(None)
self.updateTable()
self.projectDict = {}
print 'Loading ' + loadDialog.GetPath()
self.filterFile = loadDialog.GetPath()
self.filterFileName = loadDialog.GetPath()
self.filterLock = file_locker.FileLock(self.filterFileName)
self.readFile(None)
self.fileButton.SetLabel(os.path.split(loadDialog.GetPath())[-1])
if self.projectNameBox.GetValue() == '':
projName = os.path.basename(loadDialog.GetPath())
projName = projName.rsplit('.', 1)[0] + '.ph5'
self.projectNameBox.SetValue(projName)
self.newProjectTree.DeleteAllItems()
loadDialog.Destroy()
self.dataTable.SetFocus()
# Load the instrumentConfigFile
def loadInstrumentConfig(self, event):
loadDialog = wx.FileDialog(self, message='Load Instrument Config file...',
defaultDir=os.getcwd(), defaultFile='',
wildcard='Master files (*.xml)|*.xml|'+\
'All files (*.*)|*',
style=wx.OPEN)
if loadDialog.ShowModal() == wx.ID_OK:
if not os.path.isfile(loadDialog.GetPath()):
print 'Error: File does not exist'
return
try:
self.instConfigFile = InstrumentConfiguration(loadDialog.GetPath())
except ParseError as pe:
print pe
loadDialog.Destroy()
# Reset all filters and read in an HDF file
def readFile(self, event):
'''Read the HDF file self.filterFile, building the
scan list self.scanItems to place into the filter list.
'''
if self.filterFile is None:
print 'Error: no file selected'
return
# If a file is being reread, make sure it tries
# to open the filename, not the closed file
self.filterFile = self.filterFileName
try:
print 'Attempting to lock file...'
# while wx.GetApp().Pending():
# wx.GetApp().Dispatch()
# wx.GetApp().Yield(True)
self.filterLock.acquire()
print 'Lock acquired'
# while wx.GetApp().Pending():
# wx.GetApp().Dispatch()
# wx.GetApp().Yield(True)
except file_locker.FileLockException as e:
print 'Error: ' + str(e)
return
try:
self.filterFile = h5py.File(self.filterFile, 'r')
#self.set_data('filter_file', self.filterFile)
except IOError:
print 'Error opening file'
self.filterLock.release()
print 'Lock released'
return
# Reset all the hdf-related variables
self.scanItems = []
self.allSpecs = {}
self.allHK = {}
self.LMin, self.LMax = (float('inf'), float('-inf'))
self.allTypes = {}
self.possibleYears = []
self.dateMin, self.dateMax = (float('inf'), float('-inf'))
self.allInfo = {}
#self.resetFilters(None)
# Iterate over the items in the HDF file, building the
# list that will be used to populate the filter table
filterItems = self.filterFile.items()
filterItems.sort()
for spec, group in filterItems:
for number, scan in group.items():
scanAttrs = scan.attrs
sAbort = scanAttrs.get('aborted', '?')
if sAbort == 0:
sAbort = ''
elif sAbort == 1:
sAbort = 'True'
toShow = 'Command: ' + scanAttrs.get('cmd', 'N/A') + \
'\n\n' + \
'Attenuators: ' + scanAttrs.get('atten', 'N/A') + \
'\n\n' + \
'Energy: ' + str(scanAttrs.get('energy', 'N/A')) + \
'\n\n' + \
'Data points: ' + str(scanAttrs.get('nl_dat', 'N/A'))
self.scanItems.append([scanAttrs.get('spec_name', 'N/A'),
str(scanAttrs.get('index', '0')),
str(scanAttrs.get('h_val', '--')),
str(scanAttrs.get('k_val', '--')),
str(scanAttrs.get('real_L_start', '--')),
str(scanAttrs.get('real_L_stop', '--')),
scanAttrs.get('s_type', 'N/A'),
sAbort,
scanAttrs.get('date', 'N/A'),
scanAttrs.get('hk_dist', '--'),
scan.name,
toShow])
# Some list formatting and specialized group formation
for scan in self.scanItems:
# Make a dictionary of {scan type: frequency} pairs
if scan[6] not in self.allTypes:
self.allTypes[scan[6]] = 1
else:
self.allTypes[scan[6]] += 1
# Unless it's a rodscan, don't bother cluttering
# the display with the L start and stop values
# If it is a rodscan, populate the dictionary:
# {HK Pair: {Specfile : [HK Distance, count]}}
if scan[6] not in ['rodscan', 'Escan', 'hklscan']:
scan[4] = '--'
scan[5] = '--'
else:
specVal = scan[0]
hVal = scan[2]
kVal = scan[3]
if (hVal, kVal) not in self.allHK:
self.allHK[(hVal, kVal)] = {specVal: [scan[9], 1]}
elif specVal not in self.allHK[(hVal, kVal)]:
self.allHK[(hVal, kVal)][specVal] = [scan[9], 1]
else:
self.allHK[(hVal, kVal)][specVal][1] += 1
# Make sure the specfile names are saved
if scan[0] not in self.allSpecs:
self.allSpecs[scan[0]] = [int(scan[1])]
else:
self.allSpecs[scan[0]].append(int(scan[1]))
# Establish the min and max L values:
try:
#if float(scan[4]) < self.LMin: self.LMin = float(scan[4])
self.LMin = min(float(scan[4]), self.LMin)
except:
pass
try:
#if float(scan[5]) > self.LMax: self.LMax = float(scan[5])
self.LMax = max(float(scan[5]), self.LMax)
except:
pass
# Make a list of all the years involved in the scans
if scan[8].split()[-1] not in self.possibleYears:
self.possibleYears.append(scan[8].split()[-1])
# Establish the min and max date epochs:
try:
self.dateMin = min(time.mktime(time.strptime(scan[8])),
self.dateMin)
except:
pass
try:
self.dateMax = max(time.mktime(time.strptime(scan[8])),
self.dateMax)
except:
pass
# Make a dictionary of {(Specname, scan number): information
# to be displayed when the scan is selected
self.allInfo[(scan[0], scan[1])] = scan[11]
# Sort the scans by index first
self.scanItems.sort(key=lambda scan : int(scan[1]))
# Then sort the scans by specfile name, resulting in
# scans ordered by specfile first, then scan number
self.scanItems.sort(key=lambda scan : scan[0])
# Update the data table with the new scan information
self.updateTable()
# Close the file and release the lock
try:
self.filterFile.close()
self.filterLock.release()
print 'Lock released'
except:
print 'Error closing file'
# Delete everything in the table, then add the appropriate scans
def updateTable(self):
'''Delete all the scans from the filter list,
then repopulate it with the scans that pass
all of the active filters.
'''
self.dataTable.DeleteAllItems()
self.activeFilters = []
for filter in [self.specCases, self.hkCases,
self.LCases, self.typeCases, self.dateCases]:
if filter is not None:
self.activeFilters.append(filter)
if self.activeFilters != []:
self.activeFilters = ft.list_intersect(*self.activeFilters)
for entry in self.scanItems:
if entry[10] in self.activeFilters:
self.dataTable.Append(entry)
try:
if self.projectDict[entry[0]][entry[1]] is not None:
item = self.dataTable.GetItemCount()-1
self.dataTable.SetItemTextColour(item,
wx.Colour(128,
128,
128))
except:
pass
else:
for entry in self.scanItems:
self.dataTable.Append(entry[0:9])
try:
if self.projectDict[entry[0]][entry[1]] is not None:
item = self.dataTable.GetItemCount()-1
self.dataTable.SetItemTextColour(item,
wx.Colour(128,
128,
128))
except:
pass
return
# Update the 'More Info:' panel when a selection is made
def tableClick(self, event):
'''When a selection is made in the scan list,
update the 'More Info:' panel with relevant information.
'''
tableSelection = event.GetItem()
specName = self.dataTable.GetItem(tableSelection.m_itemId, 0).Text
scanNumber = self.dataTable.GetItem(tableSelection.m_itemId, 1).Text
toShow = self.allInfo.get((specName, scanNumber), '')
self.moreBox.SetValue(toShow)
# Add an attribute both to the attribute dictionary and the on-screen list
def addAttribute(self, event):
'''When the '+' button is clicked, add the corresponding
attribute and value to the list (if the attribute isn't
already present).
'''
attrText = self.attrSelect.GetStringSelection()
if attrText == '' or attrText in self.attrDict:
return
attrValue = str(self.attrSpecify.GetValue())
if attrValue == '':
return
self.attrDict[attrText] = attrValue
self.attrList.Append([attrText, attrValue, ''])
self.attrList.SetItemData(self.attrList.GetItemCount()-1, attrText)
thisButton = wx.Button(self.attrList, label='X', size=(32, 15),
name=attrText)
thisButton.Bind(wx.EVT_BUTTON, self.deleteMe)
self.attrList.SetItemWindow(self.attrList.GetItemCount()-1, col=2,
wnd=thisButton)
self.attrList.SortItems(cmp)
# Delete an attribute both from the dictionary and the on-screen list
def deleteMe(self, event):
deleteThis = event.GetEventObject().GetName()
del self.attrDict[deleteThis]
deleteThis = self.attrList.FindItemData(-1, deleteThis)
self.attrList.DeleteItem(deleteThis)
# Load a tab-delimited file of attributes
def loadAttributes(self, event):
'''Load in a file with attribute / value pairs, separated by
a tab.
'''
loadDialog = wx.FileDialog(self, message='Load file...',
defaultDir=os.getcwd(), defaultFile='',
wildcard='txt files (*.txt)|*.txt|'+\
'All files (*.*)|*',
style=wx.OPEN)
if loadDialog.ShowModal() == wx.ID_OK:
print 'Loading attribute file ' + loadDialog.GetPath()
try:
attributeFile = open(loadDialog.GetPath())
except:
print 'Error opening attribute file'
loadDialog.Destroy()
raise
try:
for line in attributeFile:
line = line.strip().split('\t')
if len(line) != 2 or \
line[0] not in POSSIBLE_ATTRIBUTES or \
line[0] in self.attrDict.keys() or \
line[1] is '':
continue
self.attrDict[line[0]] = line[1]
self.attrList.Append([line[0], line[1], ''])
self.attrList.SetItemData(self.attrList.GetItemCount()-1,
line[0])
thisButton = wx.Button(self.attrList, label='X',
size=(32, 15), name=line[0])
thisButton.Bind(wx.EVT_BUTTON, self.deleteMe)
self.attrList.SetItemWindow(self.attrList.GetItemCount()-1,
col=2, wnd=thisButton)
attributeFile.close()
self.attrList.SortItems(cmp)
except:
print 'Error reading attribute file'
loadDialog.Destroy()
raise
loadDialog.Destroy()
# Save the current attribute table into a tab-delimited file
def saveAttributes(self, event):
'''Save a file with attribute / value pairs, separated by
a tab.
'''
saveDialog = wx.FileDialog(self, message='Save file...',
defaultDir=os.getcwd(), defaultFile='',
wildcard='txt files (*.txt)|*.txt|'+\
'All files (*.*)|*',
style=wx.SAVE)
if saveDialog.ShowModal() == wx.ID_OK:
print 'Saving attribute file ' + saveDialog.GetPath()
try:
attributeFile = open(saveDialog.GetPath(), 'w')
except:
print 'Error opening attribute file'
saveDialog.Destroy()
raise
try:
for key, value in self.attrDict.iteritems():
attributeFile.write(key + '\t' + value + '\n')
except:
print 'Error writing to file'
attributeFile.close()
saveDialog.Destroy()
raise
attributeFile.close()
saveDialog.Destroy()
# Convert a dictionary to a tree
def dictToTree(self, thisDict, thisTree, thisRoot):
for key, value in thisDict.items():
if type(value) == dict:
parentItem = thisTree.AppendItem(thisRoot, key)
self.dictToTree(value, thisTree, parentItem)
else:
thisTree.AppendItem(thisRoot, str(key) + ': ' + str(value))
thisTree.SortChildren(thisRoot)
# Update the file name in the project tree
def newName(self, event):
if not self.projectNameBox.GetValue().endswith('.ph5'):
self.projectNameBox.SetValue(self.projectNameBox.GetValue()+'.ph5')
try:
self.newProjectTree.SetItemText(self.newProjectTree.GetRootItem(),
self.projectNameBox.GetValue())
except:
pass
# Move the selected scans to the project tree
def moveOneRight(self, event):
item = self.dataTable.GetFirstSelected()
if item == -1:
return
while item != -1:
specName = self.dataTable.GetItem(item, 0).Text
scanNumber = self.dataTable.GetItem(item, 1).Text
if specName in self.projectDict:
if scanNumber not in self.projectDict[specName]:
self.projectDict[specName][scanNumber] = \
self.attrDict.copy()
else:
print 'Specfile ' + specName + ', scan ' + \
scanNumber + ' is already in the tree.'
else:
self.projectDict[specName] = {}
self.projectDict[specName][scanNumber] = self.attrDict.copy()
self.dataTable.SetItemTextColour(item, wx.Colour(128, 128, 128))
item = self.dataTable.GetNextSelected(item)
self.newProjectTree.DeleteAllItems()
projectRoot = \
self.newProjectTree.AddRoot(self.projectNameBox.GetValue())
self.dictToTree(self.projectDict, self.newProjectTree, projectRoot)
self.newProjectTree.Expand(projectRoot)
# Move all the scans to the project tree
def moveAllRight(self, event):
item = self.dataTable.GetNextItem(-1)
if item == -1:
return
while item != -1:
specName = self.dataTable.GetItem(item, 0).Text
scanNumber = self.dataTable.GetItem(item, 1).Text
if specName in self.projectDict:
if scanNumber not in self.projectDict[specName]:
self.projectDict[specName][scanNumber] = \
self.attrDict.copy()
else:
print 'Specfile ' + specName + ', scan ' + \
scanNumber + ' is already in the tree.'
else:
self.projectDict[specName] = {}
self.projectDict[specName][scanNumber] = self.attrDict.copy()
self.dataTable.SetItemTextColour(item, wx.Colour(128, 128, 128))
item = self.dataTable.GetNextItem(item)
self.newProjectTree.DeleteAllItems()
projectRoot = \
self.newProjectTree.AddRoot(self.projectNameBox.GetValue())
self.dictToTree(self.projectDict, self.newProjectTree, projectRoot)
self.newProjectTree.Expand(projectRoot)
# Move the selected scans out of the project tree
def moveOneLeft(self, event):
allSelected = self.newProjectTree.GetSelections()
allSelected.sort(key = lambda selection: \
self.newProjectTree.getLevel(selection))
'''for item in allSelected:
print self.newProjectTree.GetItemText(item)
'''
for selection in allSelected:
try:
selectionLevel = self.newProjectTree.getLevel(selection)
except:
selectionLevel = -1
if selectionLevel == 0:
self.moveAllLeft(event)
return
elif selectionLevel == 1:
specName = self.newProjectTree.GetItemText(selection)
item = self.dataTable.GetNextItem(-1)
while item != -1:
if self.dataTable.GetItem(item, 0).Text == specName:
self.dataTable.SetItemTextColour(item, wx.BLACK)
item = self.dataTable.GetNextItem(item)
self.projectDict.pop(specName)
self.newProjectTree.Delete(selection)
elif selectionLevel == 2:
scanParent = self.newProjectTree.GetItemParent(selection)
scanNumber = self.newProjectTree.GetItemText(selection)
specName = self.newProjectTree.GetItemText(scanParent)
item = self.dataTable.GetNextItem(-1)
while item != -1:
if self.dataTable.GetItem(item, 0).Text == specName and \
self.dataTable.GetItem(item, 1).Text == scanNumber:
self.dataTable.SetItemTextColour(item, wx.BLACK)
break
item = self.dataTable.GetNextItem(item)
self.projectDict[specName].pop(scanNumber)
self.newProjectTree.Delete(selection)
else:
pass
popUs = []
for key in self.projectDict:
if self.projectDict[key] == {}:
popUs.append(key)
for key in popUs:
self.projectDict.pop(key)