-
Notifications
You must be signed in to change notification settings - Fork 122
/
HfirPDReductionGUI.py
2253 lines (1795 loc) · 75.3 KB
/
HfirPDReductionGUI.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
#pylint: disable=invalid-name, relative-import, too-many-lines,too-many-instance-attributes
################################################################################
# Main class for HFIR powder reduction GUI
# Key word for future developing: FUTURE, NEXT, REFACTOR, RELEASE 2.0
################################################################################
import numpy
import os
from Ui_MainWindow import Ui_MainWindow #import line for the UI python class
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
from HfirPDReductionControl import *
#----- default configuration ---------------
DEFAULT_SERVER = 'http://neutron.ornl.gov/user_data'
DEFAULT_INSTRUMENT = 'hb2a'
DEFAULT_WAVELENGTH = 2.4100
#-------------------------------------------
class EmptyError(Exception):
""" Exception for finding empty input for integer or float
"""
def __init__(self, value):
""" Init
"""
Exception.__init__(self)
self.value = value
def __str__(self):
return repr(self.value)
#pylint: disable=too-many-public-methods,too-many-branches,too-many-locals,too-many-arguments
class MainWindow(QtGui.QMainWindow):
""" Class of Main Window (top)
"""
# Copy to ui.setupUI
# # Version 3.0 + Import for Ui_MainWindow.py
# from MplFigureCanvas import Qt4MplCanvas
# # Replace 'self.graphicsView = QtGui.QtGraphicsView' with the following
# self.graphicsView = Qt4MplCanvas(self.centralwidget)
# self.mainplot = self.graphicsView.getPlot()
def __init__(self, parent=None):
""" Intialization and set up
"""
# Base class
QtGui.QMainWindow.__init__(self,parent)
# UI Window (from Qt Designer)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# Define gui-event handling
# main
self.connect(self.ui.comboBox_wavelength, QtCore.SIGNAL('currentIndexChanged(int)'),
self.doUpdateWavelength)
self.connect(self.ui.actionQuit, QtCore.SIGNAL('triggered()'),
self.doExist)
self.connect(self.ui.pushButton_browseExcludedDetFile, QtCore.SIGNAL('clicked'),
self.doBrowseExcludedDetetorFile)
# tab 'Raw Detectors'
self.connect(self.ui.pushButton_plotRaw, QtCore.SIGNAL('clicked()'),
self.doPlotRawPtMain)
self.connect(self.ui.pushButton_ptUp, QtCore.SIGNAL('clicked()'),
self.doPlotRawPtPrev)
self.connect(self.ui.pushButton_ptDown, QtCore.SIGNAL('clicked()'),
self.doPlotRawPtNext)
self.connect(self.ui.pushButton_clearRawDets, QtCore.SIGNAL('clicked()'),
self.doClearRawDetCanvas)
# tab 'Individual Detectors'
self.connect(self.ui.pushButton_plotIndvDet, QtCore.SIGNAL('clicked()'),
self.doPlotIndvDetMain)
self.connect(self.ui.pushButton_plotPrevDet, QtCore.SIGNAL('clicked()'),
self.doPlotIndvDetPrev)
self.connect(self.ui.pushButton_plotNextDet, QtCore.SIGNAL('clicked()'),
self.doPlotIndvDetNext)
self.connect(self.ui.pushButton_clearCanvasIndDet, QtCore.SIGNAL('clicked()'),
self.doClearIndDetCanvas)
self.connect(self.ui.pushButton_plotLog , QtCore.SIGNAL('clicked()'),
self.doPlotSampleLog)
# tab 'Normalized'
self.connect(self.ui.pushButton_loadData, QtCore.SIGNAL('clicked()'),
self.doLoadData)
self.connect(self.ui.pushButton_prevScan, QtCore.SIGNAL('clicked()'),
self.doLoadReduceScanPrev)
self.connect(self.ui.pushButton_nextScan, QtCore.SIGNAL('clicked()'),
self.doLoadReduceScanNext)
self.connect(self.ui.pushButton_unit2theta, QtCore.SIGNAL('clicked()'),
self.doReduce2Theta)
self.connect(self.ui.pushButton_unitD, QtCore.SIGNAL('clicked()'),
self.doReduceDSpacing)
self.connect(self.ui.pushButton_unitQ, QtCore.SIGNAL('clicked()'),
self.doReduceQ)
self.connect(self.ui.pushButton_saveData, QtCore.SIGNAL('clicked()'),
self.doSaveData)
self.connect(self.ui.pushButton_clearTab2Canvas, QtCore.SIGNAL('clicked()'),
self.doClearCanvas)
# tab 'Multiple Scans'
self.connect(self.ui.pushButton_loadMultData, QtCore.SIGNAL('clicked()'),
self.doLoadSetData)
self.connect(self.ui.pushButton_mscanBin, QtCore.SIGNAL('clicked()'),
self.doReduceSetData)
self.connect(self.ui.pushButton_mergeScans, QtCore.SIGNAL('clicked()'),
self.doMergeScans)
self.connect(self.ui.pushButton_viewMScan1D, QtCore.SIGNAL('clicked()'),
self.doMergeScanView1D)
self.connect(self.ui.pushButton_view2D, QtCore.SIGNAL('clicked()'),
self.doMergeScanView2D)
self.connect(self.ui.pushButton_viewMerge, QtCore.SIGNAL('clicked()'),
self.doMergeScanViewMerged)
self.connect(self.ui.pushButton_clearMultCanvas, QtCore.SIGNAL('clicked()'),
self.doClearMultiRunCanvas)
self.connect(self.ui.pushButton_saveAllIndScans, QtCore.SIGNAL('clicked()'),
self.doSaveMultipleScans)
self.connect(self.ui.pushButton_saveMerge, QtCore.SIGNAL('clicked()'),
self.doSaveMergedScan)
# tab 'Vanadium'
self.connect(self.ui.pushButton_stripVanPeaks, QtCore.SIGNAL('clicked()'),
self.doStripVandiumPeaks)
self.connect(self.ui.pushButton_saveVanRun, QtCore.SIGNAL('clicked()'),
self.doSaveVanRun)
self.connect(self.ui.pushButton_rebin2Theta, QtCore.SIGNAL('clicked()'),
self.doReduceVanadium2Theta)
self.connect(self.ui.pushButton_smoothVanData, QtCore.SIGNAL('clicked()'),
self.doSmoothVanadiumData)
self.connect(self.ui.pushButton_applySmooth, QtCore.SIGNAL('clicked()'),
self.doSmoothVanadiumApply)
self.connect(self.ui.pushButton_undoSmooth, QtCore.SIGNAL('clicked()'),
self.doSmoothVanadiumUndo)
# tab 'Advanced Setup'
self.connect(self.ui.pushButton_browseCache, QtCore.SIGNAL('clicked()'),
self.doBrowseCache)
self.connect(self.ui.radioButton_useServer, QtCore.SIGNAL('clicked()'),
self.doChangeSrcLocation)
self.connect(self.ui.radioButton_useLocal, QtCore.SIGNAL('clicked()'),
self.doChangeSrcLocation)
self.connect(self.ui.pushButton_browseLocalSrc, QtCore.SIGNAL('clicked()'),
self.doBrowseLocalDataSrc)
self.connect(self.ui.pushButton_chkServer, QtCore.SIGNAL('clicked()'),
self.doCheckSrcServer)
# Define signal-event handling
# define event handlers for matplotlib canvas
self.ui.graphicsView_mergeRun.canvas.mpl_connect('button_press_event', \
self.on_mouseDownEvent)
self.ui.graphicsView_mergeRun.canvas.mpl_connect('motion_notify_event', \
self.on_mouseMotion)
# Widget type definition
validator0 = QtGui.QIntValidator(self.ui.lineEdit_expNo)
validator0.setBottom(1)
self.ui.lineEdit_expNo.setValidator(validator0)
validator1 = QtGui.QIntValidator(self.ui.lineEdit_expNo)
validator1.setBottom(1)
self.ui.lineEdit_scanNo.setValidator(validator1)
validator2 = QtGui.QDoubleValidator(self.ui.lineEdit_wavelength)
validator2.setBottom(0.)
self.ui.lineEdit_wavelength.setValidator(validator2)
validator3 = QtGui.QDoubleValidator(self.ui.lineEdit_xmin)
validator3.setBottom(0.)
self.ui.lineEdit_xmin.setValidator(validator3)
validator4 = QtGui.QDoubleValidator(self.ui.lineEdit_xmax)
validator4.setBottom(0.)
self.ui.lineEdit_xmax.setValidator(validator4)
validator5 = QtGui.QDoubleValidator(self.ui.lineEdit_binsize)
validator5.setBottom(0.)
self.ui.lineEdit_binsize.setValidator(validator5)
validator6 = QtGui.QDoubleValidator(self.ui.lineEdit_ptNo)
validator6.setBottom(0)
self.ui.lineEdit_ptNo.setValidator(validator6)
validator7 = QtGui.QDoubleValidator(self.ui.lineEdit_detID)
validator7.setBottom(0)
self.ui.lineEdit_detID.setValidator(validator7)
validator8 = QtGui.QDoubleValidator(self.ui.lineEdit_min2Theta)
validator8.setBottom(0.)
self.ui.lineEdit_min2Theta.setValidator(validator8)
validator9 = QtGui.QDoubleValidator(self.ui.lineEdit_max2Theta)
validator9.setBottom(0.)
self.ui.lineEdit_max2Theta.setValidator(validator9)
validator10 = QtGui.QDoubleValidator(self.ui.lineEdit_binsize2Theta)
validator10.setBottom(0.)
self.ui.lineEdit_binsize2Theta.setValidator(validator10)
validator11 = QtGui.QIntValidator(self.ui.lineEdit_scanStart)
validator11.setBottom(1)
self.ui.lineEdit_scanStart.setValidator(validator11)
validator12 = QtGui.QIntValidator(self.ui.lineEdit_scanEnd)
validator12.setBottom(1)
self.ui.lineEdit_scanEnd.setValidator(validator12)
validator13 = QtGui.QDoubleValidator(self.ui.lineEdit_normalizeMonitor)
validator13.setBottom(0.)
self.ui.lineEdit_normalizeMonitor.setValidator(validator13)
validator14 = QtGui.QDoubleValidator(self.ui.lineEdit_mergeMinX)
validator14.setBottom(0.)
self.ui.lineEdit_mergeMinX.setValidator(validator14)
validator15 = QtGui.QDoubleValidator(self.ui.lineEdit_mergeMaxX)
validator15.setBottom(0.)
self.ui.lineEdit_mergeMaxX.setValidator(validator15)
validator16 = QtGui.QDoubleValidator(self.ui.lineEdit_mergeBinSize)
validator16.setBottom(0.)
self.ui.lineEdit_mergeBinSize.setValidator(validator16)
# Get initial setup
# RELEASE 2.0 - This part will be implemented soon as default configuration is made
# Mantid configuration
self._instrument = str(self.ui.comboBox_instrument.currentText())
# UI widgets setup
self.ui.comboBox_outputFormat.addItems(['Fullprof']) # Supports Fullprof only now, 'GSAS', 'Fullprof+GSAS'])
# RELEASE 2.0 : Need to disable some widgets... consider to refactor the code
self.ui.radioButton_useServer.setChecked(True)
self.ui.radioButton_useLocal.setChecked(False)
self.ui.comboBox_wavelength.setCurrentIndex(0)
self.ui.lineEdit_wavelength.setText('2.41')
self.ui.pushButton_unit2theta.setText(r'$2\theta$')
# vanadium spectrum smooth parameters
self.ui.lineEdit_smoothParams.setText('20,2')
# Set up data source
self._serverAddress = DEFAULT_SERVER
self._srcFromServer = True
self._localSrcDataDir = None
self._srcAtLocal = False
self._currUnit = '2theta'
# Workspaces
self._myControl = HFIRPDRedControl()
# Interactive graphics
self._viewMerge_X = None
self._viewMerge_Y = None
# Control of plots: key = canvas, value = list of 2-integer-tuple (expno, scanno)
self._tabLineDict = {}
self._tabBinParamDict = {}
for key in [2]:
self._tabLineDict[key] = []
for key in [2, 3, 4]:
self._tabBinParamDict[key] = [None, None, None]
self._lastMergeLabel = ""
self._lastMergeIndex = -1
self._expNo = None
self._scanNo = None
self._detID = None
self._indvXLabel = None
self._rawDetExpNo = None
self._rawDetScanNo = None
self._rawDetPlotMode = None
self._rawDetPtNo = None
self._indvDetCanvasMode = 'samplelog'
return
#-- Event Handling ----------------------------------------------------
def doBrowseCache(self):
""" Pop out a dialog to let user specify the directory to
cache downloaded data
"""
# home directory
homedir = str(self.ui.lineEdit_cache.text()).strip()
if len(homedir) > 0 and os.path.exists(homedir):
home = homedir
else:
home = os.getcwd()
# pop out a dialog
dirs = str(QtGui.QFileDialog.getExistingDirectory(self,'Get Directory',home))
# set to line edit
if dirs != home:
self.ui.lineEdit_cache.setText(dirs)
return
def doBrowseExcludedDetetorFile(self):
""" Browse excluded detector's file
Return :: None
"""
# Get file name
filefilter = "Text (*.txt);;Data (*.dat);;All files (*.*)"
curDir = os.getcwd()
excldetfnames = QtGui.QFileDialog.getOpenFileNames(self, 'Open File(s)', curDir, filefilter)
try:
excldetfname = excldetfnames[0]
self.ui.lineEdit_excludedDetFileName.setText(excldetfname)
except IndexError:
# return if there is no file selected
return
# Parse det exclusion file
print "Detector exclusion file name is %s." % (excldetfname)
excludedetlist, errmsg = self._myControl.parseExcludedDetFile('HB2A', excldetfname)
if len(errmsg) > 0:
self._logError(errmsg)
textbuf = ""
for detid in excludedetlist:
textbuf += "%d," % (detid)
if len(textbuf) > 0:
textbuf = textbuf[:-1]
self.ui.lineEdit_detExcluded.setText(textbuf)
# ENDIF
return
def doBrowseLocalDataSrc(self):
""" Browse local data storage
"""
print "Browse local data storage location."
return
def doChangeSrcLocation(self):
""" Source file location is changed
"""
useserver = self.ui.radioButton_useServer.isChecked()
uselocal = self.ui.radioButton_useLocal.isChecked()
print "Use Server: ", useserver
print "Use Local : ", uselocal
if (useserver is True and uselocal is True) or \
(useserver is False and uselocal is False):
raise NotImplementedError("Impossible for radio buttons")
self._srcAtLocal = uselocal
self._srcFromServer = useserver
if uselocal is True:
self.ui.lineEdit_dataIP.setDisabled(True)
self.ui.pushButton_chkServer.setDisabled(True)
self.ui.lineEdit_localSrc.setDisabled(False)
self.ui.pushButton_browseLocalSrc.setDisabled(False)
else:
self.ui.lineEdit_dataIP.setDisabled(False)
self.ui.pushButton_chkServer.setDisabled(False)
self.ui.lineEdit_localSrc.setDisabled(True)
self.ui.pushButton_browseLocalSrc.setDisabled(True)
return
def doCheckSrcServer(self):
"""" Check source data server's availability
"""
print "Check source data server!"
return
def doClearCanvas(self):
""" Clear canvas
"""
itab = self.ui.tabWidget.currentIndex()
if itab == 2:
self.ui.graphicsView_reducedData.clearAllLines()
self._tabLineDict[itab] = []
return
def doClearIndDetCanvas(self):
""" Clear the canvas in tab 'Individual Detector' and current plotted lines
in managing dictionary
"""
self.ui.graphicsView_indvDet.clearAllLines()
if self._tabLineDict.has_key(self.ui.graphicsView_indvDet):
self._tabLineDict[self.ui.graphicsView_indvDet] = []
return
def doClearMultiRunCanvas(self):
""" Clear the canvas in tab 'Multiple Run'
This canvas is applied to both 1D and 2D image.
Clear-all-lines might be not enough to clear 2D image
"""
self.ui.graphicsView_mergeRun.clearCanvas()
return
def doClearRawDetCanvas(self):
""" Clear the canvas in tab 'Raw Detector':
only need to clear lines
"""
self.ui.graphicsView_Raw.clearAllLines()
self._tabLineDict[self.ui.graphicsView_Raw] = []
return
def doClearVanadiumCanvas(self):
""" Clear the canvas in tab 'Vanadium'
"""
self.ui.graphicsView_vanPeaks.clearAllLines()
return
def doExist(self):
""" Exist the application
"""
clearcache = self.ui.checkBox_delCache.isChecked()
if clearcache is True:
delAllFile(self._cache)
self.close()
return
def doLoadData(self, exp=None, scan=None):
""" Load and reduce data
It does not support for tab 'Multiple Scans' and 'Advanced Setup'
For tab 'Raw Detector' and 'Individual Detector', this method will load data to MDEventWorkspaces
For tab 'Normalized' and 'Vanadium', this method will load data to MDEVentWorkspaces but NOT reduce to single spectrum
"""
# Kick away unsupported tabs
itab = self.ui.tabWidget.currentIndex()
tabtext = str(self.ui.tabWidget.tabText(itab))
print "[DB] Current active tab is No. %d as %s." % (itab, tabtext)
#if itab == 3:
# # 'multiple scans'
# self._logNotice("Tab %s does not support 'Load Data'. Use 'Load All' instead." % (tabtext))
# return
if itab == 5:
# 'advanced'
self._logNotice("Tab %s does not support 'Load Data'. Request is ambiguous." % (tabtext))
return
# Get exp number and scan number
if isinstance(exp, int) is True and isinstance(scan, int) is True:
# use input
expno = exp
scanno = scan
else:
# read from GUI
try:
expno, scanno = self._uiGetExpScanNumber()
self._logDebug("Attending to load Exp %d Scan %d." % (expno, scanno))
except NotImplementedError as ne:
self._logError("Error to get Exp and Scan due to %s." % (str(ne)))
return
# ENDIF
# Form data file name and download data
status, datafilename = self._uiDownloadDataFile(exp=expno, scan=scanno)
if status is False:
self._logError("Unable to download or locate local data file for Exp %d \
Scan %d." % (expno, scanno))
# ENDIF(status)
# (Load data for tab 0, 1, 2 and 4)
if itab not in [0, 1, 2, 3, 4]:
# Unsupported Tabs: programming error!
errmsg = "%d-th tab should not get this far.\n"%(itab)
errmsg += 'GUI has been changed, but the change has not been considered! iTab = %d' % (itab)
raise NotImplementedError(errmsg)
# Load SPICE data to raw table (step 1)
try:
execstatus = self._myControl.loadSpicePDData(expno, scanno, datafilename)
if execstatus is False:
cause = "Load data failed."
else:
cause = None
except NotImplementedError as ne:
execstatus = False
cause = str(ne)
# END-TRY-EXCEPT
# Return as failed to load data
if execstatus is False:
self._logError(cause)
return
# Obtain the correction file names and wavelength from SPICE file
wavelengtherror = False
errmsg = ""
localdir = os.path.dirname(datafilename)
try:
status, returnbody = self._myControl.retrieveCorrectionData(instrument='HB2A',
exp=expno, scan=scanno,
localdatadir=localdir)
except NotImplementedError as e:
errmsg = str(e)
if errmsg.count('m1') > 0:
# error is about wavelength
status = False
wavelengtherror = True
else:
# other error
raise e
# ENDTRY
if status is True:
autowavelength = returnbody[0]
vancorrfname = returnbody[1]
excldetfname = returnbody[2]
if vancorrfname is not None:
self.ui.lineEdit_vcorrFileName.setText(vancorrfname)
if excldetfname is not None:
self.ui.lineEdit_excludedDetFileName.setText(excldetfname)
else:
autowavelength = None
vancorrfname = None
excldetfname = None
# ENDIF
# Set wavelength to GUI except 'multiple scans'
if autowavelength is None:
# unable to get wavelength from SPICE data
self.ui.comboBox_wavelength.setCurrentIndex(4)
if wavelengtherror is True:
self.ui.lineEdit_wavelength.setText(errmsg)
else:
self.ui.lineEdit_wavelength.setText(self.ui.comboBox_wavelength.currentText())
self._myControl.setWavelength(expno, scanno, wavelength=None)
else:
# get wavelength from SPICE data. set value to GUI
self.ui.lineEdit_wavelength.setText(str(autowavelength))
allowedwavelengths = [2.41, 1.54, 1.12]
numitems = self.ui.comboBox_wavelength.count()
good = False
for ic in xrange(numitems-1):
if abs(autowavelength - allowedwavelengths[ic]) < 0.01:
good = True
self.ui.comboBox_wavelength.setCurrentIndex(ic)
# ENDFOR
if good is False:
self.ui.comboBox_wavelength.setCurrentIndex(numitems-1)
# ENDIF
self._myControl.setWavelength(expno, scanno, wavelength=autowavelength)
# ENDIFELSE
# Optionally obtain and parse det effecient file
if self.ui.checkBox_useDetEffCorr.isChecked() is True:
# Apply detector efficiency correction
if vancorrfname is None:
# browse vanadium correction file
filefilter = "Text (*.txt);;Data (*.dat);;All files (*.*)"
curDir = os.getcwd()
vancorrfnames = QtGui.QFileDialog.getOpenFileNames(self, 'Open File(s)', curDir, filefilter)
if len(vancorrfnames) > 0:
vancorrfname = vancorrfnames[0]
self.ui.lineEdit_vcorrFileName.setText(str(vancorrfname))
else:
self._logError("User does not specify any vanadium correction file.")
self.ui.checkBox_useDetEffCorr.setChecked(False)
# ENDIF-len()
# ENDIF vancorrfname
# Parse if it is not None
if vancorrfname is not None:
detefftablews, errmsg = self._myControl.parseDetEffCorrFile('HB2A', vancorrfname)
if detefftablews is None:
print "Parsing detectors efficiency file error: %s." % (errmsg)
else:
detefftablews = None
# ENDIF
else:
# Not chosen to apply detector efficiency correction:w
detefftablews = None
# ENDIF
# Parse SPICE data to MDEventWorkspaces
try:
print "Det EFF Table WS: ", str(detefftablews)
execstatus = self._myControl.parseSpiceData(expno, scanno, detefftablews)
if execstatus is False:
cause = "Parse data failed."
else:
cause = None
except NotImplementedError as e:
execstatus = False
cause = str(e)
# END-TRY-EXCEPT-FINALLY
# Return if data parsing is error
if execstatus is False:
self._logError(cause)
return
# Optionally parse detector exclusion file and set to line text
if excldetfname is not None:
excludedetlist, errmsg = self._myControl.parseExcludedDetFile('HB2A', excldetfname)
textbuf = ""
for detid in excludedetlist:
textbuf += "%d," % (detid)
if len(textbuf) > 0:
textbuf = textbuf[:-1]
self.ui.lineEdit_detExcluded.setText(textbuf)
# ENDIF
# Set up some widgets for raw detector data. Won't be applied to tab 3
if itab != 3:
floatsamplelognamelist = self._myControl.getSampleLogNames(expno, scanno)
self.ui.comboBox_indvDetXLabel.clear()
self.ui.comboBox_indvDetXLabel.addItems(floatsamplelognamelist)
self.ui.comboBox_indvDetYLabel.clear()
self.ui.comboBox_indvDetYLabel.addItems(floatsamplelognamelist)
return True
def doLoadSetData(self):
""" Load a set of data
This is the first step of doing multiple scans processing
"""
# Get inputs for exp number and scans
try:
rtup = self._uiGetExpScanTabMultiScans()
expno = rtup[0]
scanlist = rtup[1]
except NotImplementedError as nie:
self._logError("Unable to load data set in multiple scans due to %s." % (str(nie)))
# Load and reduce data
loadstatus = True
for scan in sorted(scanlist):
tempstatus = self.doLoadData(expno, scan)
if tempstatus is False:
self.ui.label_mergeMessage.setText('Error to load Exp %d Scan %d.'%(expno, scan))
loadstatus = False
else:
message = 'Loaded Exp %d Scan %d.' % (expno, scan)
self.ui.label_mergeMessage.setText(message)
# ENDFOR
# Load status
if loadstatus is True:
self.ui.label_mergeMessage.setText('All data files are loaded')
else:
self.ui.label_mergeMessage.setText('Not all data files are loaded')
# Wave length
haswavelength = True
for scan in scanlist:
if self._myControl.getWavelength(expno, scan) is None:
self._logNotice("Exp %d Scan %d has no wavelength set up." % (expno, scan))
haswavelength = False
break
# ENDFOR
# Set unit box
if haswavelength is True:
self.ui.comboBox_mscanUnit.clear()
self.ui.comboBox_mscanUnit.addItems(['2theta', 'dSpacing', 'Momentum Transfer (Q)'])
else:
self.ui.comboBox_mscanUnit.clear()
self.ui.comboBox_mscanUnit.addItems(['2theta'])
return
def doLoadReduceScanPrev(self):
""" Load and reduce previous scan for tab 'Normalized'
"""
# Reduce scan number by 1
try:
scanno = int(self.ui.lineEdit_scanNo.text())
except ValueError:
self._logError("Either Exp No or Scan No is not set up right as integer.")
return
else:
scanno = scanno - 1
if scanno < 1:
self._logWarning("Scan number is 1 already. Cannot have previous scan")
return
self.ui.lineEdit_scanNo.setText(str(scanno))
# Load data
self.ui.lineEdit_scanNo.setText(str(scanno))
self.doLoadData()
# Reduce data
self._uiReducePlotNoramlized(self._currUnit)
return
def doLoadReduceScanNext(self):
""" Load and reduce next scan for tab 'Normalized'
"""
# Advance scan number by 1
try:
scanno = int(self.ui.lineEdit_scanNo.text())
except ValueError:
self._logError("Either Exp No or Scan No is not set up right as integer.")
return False
else:
scanno = scanno + 1
if scanno < 1:
self._logWarning("Scan number is 1 already. Cannot have previous scan")
return False
# Load data
self.ui.lineEdit_scanNo.setText(str(scanno))
execstatus = self.doLoadData()
print "[DB] Load data : ", execstatus
# Reduce data
self._uiReducePlotNoramlized(self._currUnit)
return
def doMergeScans(self):
""" Merge several scans for tab 'merge'
"""
# Get exp number and list of scans
try:
r = self._uiGetExpScanTabMultiScans()
expno = r[0]
scanlist = r[1]
except NotImplementedError as ne:
self._logError(str(ne))
return False
# Check whether the wavelengths are same to merge
try:
wl_list = []
for scanno in scanlist:
print "Exp %d Scan %d. Wavelength = %s." % (expno, scanno, str(self._myControl.getWavelength(expno, scanno)))
wl_list.append(float(self._myControl.getWavelength(expno, scanno)))
wl_list = sorted(wl_list)
min_wl = wl_list[0]
max_wl = wl_list[-1]
if max_wl - min_wl > 1.0:
self._logWarning("All scans do not have same wavelengths!")
except TypeError:
self._logError('Not all scans have wavelength set up. Unable to merge scans.')
return
# Check!
try:
unit = str(self.ui.comboBox_mscanUnit.currentText())
xmin, binsize, xmax = self._uiGetBinningParams(itab=3)
#wavelength = min_wl
mindex = self._myControl.mergeReduceSpiceData(expno, scanlist, unit, xmin, xmax, binsize)
except Exception as e:
raise e
label = "Exp %d, Scan %s." % (expno, str(scanlist))
self._plotMergedReducedData(mindex, label)
self._lastMergeIndex = mindex
self._lastMergeLabel = label
return
def doMergeScanView1D(self):
""" Change the multiple runs to 1D
"""
# Highlight the button's color
self.ui.pushButton_view2D.setStyleSheet('QPushButton {background-color: yellow; color: red;}')
self.ui.pushButton_view2D.setEnabled(True)
self.ui.pushButton_viewMScan1D.setStyleSheet('QPushButton {background-color: white; color: gray;}')
self.ui.pushButton_viewMScan1D.setEnabled(False)
# Process input experiment number and scan list
try:
r = self._uiGetExpScanTabMultiScans()
expno = r[0]
scanlist = r[1]
except NotImplementedError as e:
self._logError(str(e))
return False
# Clear image
canvas = self.ui.graphicsView_mergeRun
canvas.clearAllLines()
canvas.clearCanvas()
# Plot data
unit = str(self.ui.comboBox_mscanUnit.currentText())
xlabel = self._getXLabelFromUnit(unit)
for scanno in scanlist:
label = "Exp %s Scan %s"%(str(expno), str(scanno))
self._plotReducedData(expno, scanno, canvas, xlabel, label=label, clearcanvas=False)
# ENDFOR
return
def doMergeScanView2D(self):
""" Change the merged run's view to 2D plot
"""
# Highlight button color and change the color of another one
self.ui.pushButton_view2D.setStyleSheet('QPushButton {background-color: white; color: gray;}')
self.ui.pushButton_view2D.setEnabled(False)
self.ui.pushButton_viewMScan1D.setStyleSheet('QPushButton {background-color: yellow; color: red;}')
self.ui.pushButton_viewMScan1D.setEnabled(True)
# Get list of data to plot
r = self._uiGetExpScanTabMultiScans()
expno = r[0]
scanlist = r[1]
# Convert the workspaces to 2D vector
vecylist = []
yticklabels = []
xmin = None
xmax = None
for scanno in scanlist:
# put y values to list for constructing 2D array
vecx, vecy = self._myControl.getVectorToPlot(expno, scanno)
vecylist.append(vecy)
yticklabels.append('Exp %d Scan %d' % (expno, scanno))
# set up range of x
if xmin is None:
xmin = vecx[0]
xmax = vecx[-1]
# ENDIF
# ENDFOR
dim2array = numpy.array(vecylist)
print "2D vector: \n", dim2array
print "x range: %f, %f" % (xmin, xmax)
print "y labels: ", yticklabels
# Plot
holdprev=False
self.ui.graphicsView_mergeRun.clearAllLines()
self.ui.graphicsView_mergeRun.addPlot2D(dim2array, xmin=xmin, xmax=xmax, ymin=0, \
ymax=len(vecylist), holdprev=holdprev, yticklabels=yticklabels)
return
def doMergeScanViewMerged(self):
""" Change the merged run's view to 1D plot
"""
# Highlight the button's color
self.ui.pushButton_view2D.setStyleSheet('QPushButton {color: red;}')
self.ui.pushButton_view2D.setEnabled(True)
self.ui.pushButton_viewMScan1D.setStyleSheet('QPushButton {color: red;}')
self.ui.pushButton_viewMScan1D.setEnabled(True)
# Clear image
self.ui.graphicsView_mergeRun.clearCanvas()
# Plot
self._plotMergedReducedData(mkey=self._lastMergeIndex, label=self._lastMergeLabel)
return
def doPlotIndvDetMain(self):
""" Plot individual detector
"""
# Get exp and scan numbers and check whether the data has been loaded
try:
expno = self._getInteger(self.ui.lineEdit_expNo)
scanno = self._getInteger(self.ui.lineEdit_scanNo)
except EmptyError as e:
self._logError(str(e))
return
# Get detector ID and x-label option
try:
detid = self._getInteger(self.ui.lineEdit_detID)
except EmptyError:
self._logError("Detector ID must be specified for plotting individual detector.")
return
# Over plot previous or clear
overplot = self.ui.checkBox_overPlotIndvDet.isChecked()
if overplot is False:
self.doClearIndDetCanvas()
xlabel = str(self.ui.comboBox_indvDetXLabel.currentText())
if xlabel.strip() == "":
xlabel = None
# plot
try:
self._plotIndividualDetCounts(expno, scanno, detid, xlabel)
self._expNo = expno
self._scanNo = scanno
self._detID = detid
self._indvXLabel = xlabel
except NotImplementedError as e:
self._logError(str(e))
return
def doPlotIndvDetNext(self):
""" Plot next raw detector signals for tab 'Individual Detector'
"""
# Plot
try:
currdetid = self._detID + 1
# Over plot previous or clear
overplot = self.ui.checkBox_overPlotIndvDet.isChecked()
if overplot is False:
self.doClearIndDetCanvas()
self._plotIndividualDetCounts(self._expNo, self._scanNo, currdetid,
self._indvXLabel)
except KeyError as e:
self._logError(str(e))
else:
self._detID = currdetid
# Update widget
self.ui.lineEdit_detID.setText(str(self._detID))
return
def doPlotIndvDetPrev(self):
""" Plot previous individual detector's signal for tab 'Individual Detector'
"""
# Plot
try:
currdetid = self._detID - 1
# Over plot previous or clear
overplot = self.ui.checkBox_overPlotIndvDet.isChecked()
if overplot is False:
self.doClearIndDetCanvas()
self._plotIndividualDetCounts(self._expNo, self._scanNo, currdetid,
self._indvXLabel)
except KeyError as e:
self._logError(str(e))
else:
self._detID = currdetid
# Update widget
self.ui.lineEdit_detID.setText(str(self._detID))
return
def doPlotRawPtMain(self):
""" Plot current raw detector signal for a specific Pt.
"""
# Get experiment number and scan number for data file
try:
expno = self._getInteger(self.ui.lineEdit_expNo)
scanno = self._getInteger(self.ui.lineEdit_scanNo)
except EmptyError as e:
self._logError(str(e))
return