-
Notifications
You must be signed in to change notification settings - Fork 122
/
IndirectDataAnalysis.py
1097 lines (884 loc) · 41.3 KB
/
IndirectDataAnalysis.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 IndirectImport import import_mantidplot
mp = import_mantidplot()
from IndirectCommon import *
import math, re, os.path, numpy as np
from mantid.simpleapi import *
from mantid.api import TextAxis
from mantid import *
##############################################################################
# Misc. Helper Functions
##############################################################################
def split(l, n):
#Yield successive n-sized chunks from l.
for i in xrange(0, len(l), n):
yield l[i:i+n]
def segment(l, fromIndex, toIndex):
for i in xrange(fromIndex, toIndex + 1):
yield l[i]
def trimData(nSpec, vals, min, max):
result = []
chunkSize = len(vals) / nSpec
assert min >= 0, 'trimData: min is less then zero'
assert max <= chunkSize - 1, 'trimData: max is greater than the number of spectra'
assert min <= max, 'trimData: min is greater than max'
chunks = split(vals,chunkSize)
for chunk in chunks:
seg = segment(chunk,min,max)
for val in seg:
result.append(val)
return result
##############################################################################
# ConvFit
##############################################################################
def calculateEISF(params_table):
#get height data from parameter table
height = search_for_fit_params('Height', params_table)[0]
height_error = search_for_fit_params('Height_Err', params_table)[0]
height_y = np.asarray(mtd[params_table].column(height))
height_e = np.asarray(mtd[params_table].column(height_error))
#get amplitude column names
amp_names = search_for_fit_params('Amplitude', params_table)
amp_error_names = search_for_fit_params('Amplitude_Err', params_table)
#for each lorentzian, calculate EISF
for amp_name, amp_error_name in zip(amp_names, amp_error_names):
#get amplitude from column in table workspace
amp_y = np.asarray(mtd[params_table].column(amp_name))
amp_e = np.asarray(mtd[params_table].column(amp_error_name))
#calculate EISF and EISF error
total = height_y+amp_y
EISF_y = height_y/total
total_error = height_e**2 + np.asarray(amp_e)**2
EISF_e = EISF_y * np.sqrt((height_e**2/height_y**2) + (total_error/total**2))
#append the calculated values to the table workspace
col_name = amp_name[:-len('Amplitude')] + 'EISF'
error_col_name = amp_error_name[:-len('Amplitude_Err')] + 'EISF_Err'
mtd[params_table].addColumn('double', col_name)
mtd[params_table].addColumn('double', error_col_name)
for i, (value, error) in enumerate(zip(EISF_y, EISF_e)):
mtd[params_table].setCell(col_name, i, value)
mtd[params_table].setCell(error_col_name, i, error)
##############################################################################
def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin=0, specMax=None, Verbose=False, Plot='None', Save=False):
StartTime('ConvFit')
bgd = bgd[:-2]
num_spectra = mtd[inputWS].getNumberHistograms()
if specMin < 0 or specMax >= num_spectra:
raise ValueError("Invalid spectrum range: %d - %d" % (specMin, specMax))
using_delta_func = ftype[:5] == 'Delta'
lorentzians = ftype[5:6] if using_delta_func else ftype[:1]
if Verbose:
logger.notice('Input files : '+str(inputWS))
logger.notice('Fit type : Delta = ' + str(using_delta_func) + ' ; Lorentzians = ' + str(lorentzians))
logger.notice('Background type : ' + bgd)
output_workspace = getWSprefix(inputWS) + 'conv_' + ftype + bgd + '_s' + str(specMin) + "_to_" + str(specMax)
#convert input workspace to get Q axis
temp_fit_workspace = "__convfit_fit_ws"
convertToElasticQ(inputWS, temp_fit_workspace)
#fit all spectra in workspace
input_params = [temp_fit_workspace+',i%d' % i
for i in xrange(specMin, specMax+1)]
PlotPeakByLogValue(Input=';'.join(input_params),
OutputWorkspace=output_workspace, Function=func,
StartX=startX, EndX=endX, FitType='Sequential',
CreateOutput=True, OutputCompositeMembers=True,
ConvolveMembers=True)
DeleteWorkspace(output_workspace + '_NormalisedCovarianceMatrices')
DeleteWorkspace(output_workspace + '_Parameters')
DeleteWorkspace(temp_fit_workspace)
wsname = output_workspace + "_Result"
parameter_names = ['Height', 'Amplitude', 'FWHM', 'EISF']
if using_delta_func:
calculateEISF(output_workspace)
convertParametersToWorkspace(output_workspace, "axis-1", parameter_names, wsname)
#set x units to be momentum transfer
axis = mtd[wsname].getAxis(0)
axis.setUnit("MomentumTransfer")
CopyLogs(InputWorkspace=inputWS, OutputWorkspace=wsname)
AddSampleLog(Workspace=wsname, LogName="fit_program", LogType="String", LogText='ConvFit')
AddSampleLog(Workspace=wsname, LogName='background', LogType='String', LogText=str(bgd))
AddSampleLog(Workspace=wsname, LogName='delta_function', LogType='String', LogText=str(using_delta_func))
AddSampleLog(Workspace=wsname, LogName='lorentzians', LogType='String', LogText=str(lorentzians))
CopyLogs(InputWorkspace=wsname, OutputWorkspace=output_workspace + "_Workspaces")
temp_correction = temperature is not None
AddSampleLog(Workspace=wsname, LogName='temperature_correction', LogType='String', LogText=str(temp_correction))
if temp_correction:
AddSampleLog(Workspace=wsname, LogName='temperature_value', LogType='String', LogText=str(temperature))
RenameWorkspace(InputWorkspace=output_workspace, OutputWorkspace=output_workspace + "_Parameters")
fit_workspaces = mtd[output_workspace + '_Workspaces'].getNames()
for i, ws in enumerate(fit_workspaces):
RenameWorkspace(ws, OutputWorkspace=output_workspace + '_' + str(i+specMin) + '_Workspace')
if Save:
# path name for nxs file
workdir = getDefaultWorkingDirectory()
o_path = os.path.join(workdir, wsname+'.nxs')
if Verbose:
logger.notice('Creating file : '+ o_path)
SaveNexusProcessed(InputWorkspace=wsname, Filename=o_path)
if Plot == 'All':
plotParameters(wsname, *parameter_names)
elif Plot != 'None':
plotParameters(wsname, Plot)
EndTime('ConvFit')
##############################################################################
# Elwin
##############################################################################
def GetTemperature(root, tempWS, log_type, Verbose):
(instr, run_number) = getInstrRun(tempWS)
facility = config.getFacility()
pad_num = facility.instrument(instr).zeroPadding(int(run_number))
zero_padding = '0' * (pad_num - len(run_number))
run_name = instr + zero_padding + run_number
log_name = run_name.upper() + '.log'
run = mtd[tempWS].getRun()
unit = ['Temperature', 'K']
if log_type in run:
# test logs in WS
tmp = run[log_type].value
temp = tmp[len(tmp)-1]
if Verbose:
mess = ' Run : '+run_name +' ; Temperature in log = '+str(temp)
logger.notice(mess)
else:
# logs not in WS
logger.warning('Log parameter not found in workspace. Searching for log file.')
log_path = FileFinder.getFullPath(log_name)
if log_path != '':
# get temperature from log file
LoadLog(Workspace=tempWS, Filename=log_path)
run_logs = mtd[tempWS].getRun()
tmp = run_logs[log_type].value
temp = tmp[len(tmp)-1]
mess = ' Run : '+run_name+' ; Temperature in file = '+str(temp)
logger.warning(mess)
else:
# can't find log file
temp = int(run_name[-3:])
unit = ['Run-number', 'last 3 digits']
mess = ' Run : '+run_name +' ; Temperature file not found'
logger.warning(mess)
return temp,unit
def elwin(inputFiles, eRange, log_type='sample', Normalise = False,
Save=False, Verbose=False, Plot=False):
StartTime('ElWin')
workdir = config['defaultsave.directory']
CheckXrange(eRange,'Energy')
tempWS = '__temp'
Range2 = ( len(eRange) == 4 )
if Verbose:
range1 = str(eRange[0])+' to '+str(eRange[1])
if ( len(eRange) == 4 ):
range2 = str(eRange[2])+' to '+str(eRange[3])
logger.notice('Using 2 energy ranges from '+range1+' & '+range2)
elif ( len(eRange) == 2 ):
logger.notice('Using 1 energy range from '+range1)
nr = 0
inputRuns = sorted(inputFiles)
for file in inputRuns:
(direct, file_name) = os.path.split(file)
(root, ext) = os.path.splitext(file_name)
LoadNexus(Filename=file, OutputWorkspace=tempWS)
nsam,ntc = CheckHistZero(tempWS)
(xval, unit) = GetTemperature(root,tempWS,log_type, Verbose)
if Verbose:
logger.notice('Reading file : '+file)
if ( len(eRange) == 4 ):
ElasticWindow(InputWorkspace=tempWS, Range1Start=eRange[0], Range1End=eRange[1],
Range2Start=eRange[2], Range2End=eRange[3],
OutputInQ='__eq1', OutputInQSquared='__eq2')
elif ( len(eRange) == 2 ):
ElasticWindow(InputWorkspace=tempWS, Range1Start=eRange[0], Range1End=eRange[1],
OutputInQ='__eq1', OutputInQSquared='__eq2')
(instr, last) = getInstrRun(tempWS)
q1 = np.array(mtd['__eq1'].readX(0))
i1 = np.array(mtd['__eq1'].readY(0))
e1 = np.array(mtd['__eq1'].readE(0))
Logarithm(InputWorkspace='__eq2', OutputWorkspace='__eq2')
q2 = np.array(mtd['__eq2'].readX(0))
i2 = np.array(mtd['__eq2'].readY(0))
e2 = np.array(mtd['__eq2'].readE(0))
if (nr == 0):
CloneWorkspace(InputWorkspace='__eq1', OutputWorkspace='__elf')
first = getWSprefix(tempWS)
datX1 = q1
datY1 = i1
datE1 = e1
datX2 = q2
datY2 = i2
datE2 = e2
Tvalue = [xval]
Terror = [0.0]
Taxis = str(xval)
else:
CloneWorkspace(InputWorkspace='__eq1', OutputWorkspace='__elftmp')
ConjoinWorkspaces(InputWorkspace1='__elf', InputWorkspace2='__elftmp', CheckOverlapping=False)
datX1 = np.append(datX1,q1)
datY1 = np.append(datY1,i1)
datE1 = np.append(datE1,e1)
datX2 = np.append(datX2,q2)
datY2 = np.append(datY2,i2)
datE2 = np.append(datE2,e2)
Tvalue.append(xval)
Terror.append(0.0)
Taxis += ','+str(xval)
nr += 1
Txa = np.array(Tvalue)
Tea = np.array(Terror)
nQ = len(q1)
for nq in range(0,nQ):
iq = []
eq = []
for nt in range(0,len(Tvalue)):
ii = mtd['__elf'].readY(nt)
iq.append(ii[nq])
ie = mtd['__elf'].readE(nt)
eq.append(ie[nq])
iqa = np.array(iq)
eqa = np.array(eq)
if (nq == 0):
datTx = Txa
datTy = iqa
datTe = eqa
else:
datTx = np.append(datTx,Txa)
datTy = np.append(datTy,iqa)
datTe = np.append(datTe,eqa)
DeleteWorkspace('__eq1')
DeleteWorkspace('__eq2')
DeleteWorkspace('__elf')
if (nr == 1):
ename = first[:-1]
else:
ename = first+'to_'+last
elfWS = ename+'_elf'
e1WS = ename+'_eq1'
e2WS = ename+'_eq2'
#elt only created if we normalise
eltWS = None
wsnames = [elfWS, e1WS, e2WS]
#x,y,e data for the elf, e1 and e2 workspaces
data = [[datTx, datTy, datTe],
[datX1, datY1, datE1],
[datX2, datY2, datE2]]
#x and vertical units for the elf, e1 and e2 workspaces
xunits = ['Energy', 'MomentumTransfer', 'QSquared']
vunits = ['MomentumTransfer', 'Energy', 'Energy']
#vertical axis values for the elf, e1 and e2 workspaces
vvalues = [q1, Taxis, Taxis]
#number of spectra in each workspace
nspecs = [nQ, nr, nr]
#x-axis units label
label = unit[0]+' / '+unit[1]
wsInfo = zip(wsnames,data, xunits, vunits, vvalues, nspecs)
#Create output workspaces and add sample logs
for wsname, wsdata, xunit, vunit, vvalue, nspec in wsInfo:
x, y, e = wsdata
CreateWorkspace(OutputWorkspace=wsname, DataX=x, DataY=y, DataE=e,
Nspec=nspec, UnitX=xunit, VerticalAxisUnit=vunit, VerticalAxisValues=vvalue)
SortXAxis(InputWorkspace=wsname, OutputWorkspace=wsname)
#add sample logs to new workspace
CopyLogs(InputWorkspace=tempWS, OutputWorkspace=wsname)
addElwinLogs(wsname, label, eRange, Range2)
# remove the temp workspace now we've copied the logs
DeleteWorkspace(tempWS)
if unit[0] == 'Temperature':
AddSampleLog(Workspace=e1WS, LogName="temp_normalise",
LogType="String", LogText=str(Normalise))
#create workspace normalized to the lowest temperature
if Normalise:
eltWS = ename+'_elt'
#create elt workspace
mtd[elfWS].clone(OutputWorkspace=eltWS)
elwinNormalizeToLowestTemp(eltWS)
#set labels and meta data
unitx = mtd[eltWS].getAxis(0).setUnit("Label")
unitx.setLabel(unit[0], unit[1])
addElwinLogs(eltWS, label, eRange, Range2)
#append workspace name to output files list
wsnames.append(eltWS)
#set labels on workspace axes
unity = mtd[e1WS].getAxis(1).setUnit("Label")
unity.setLabel(unit[0], unit[1])
unity = mtd[e2WS].getAxis(1).setUnit("Label")
unity.setLabel(unit[0], unit[1])
unitx = mtd[elfWS].getAxis(0).setUnit("Label")
unitx.setLabel(unit[0], unit[1])
if Save:
elwinSaveWorkspaces(wsnames, workdir, Verbose)
if Plot:
elwinPlot(label,e1WS,e2WS,elfWS,eltWS)
EndTime('Elwin')
return e1WS,e2WS
#normalize workspace to the lowest temperature
def elwinNormalizeToLowestTemp(eltWS):
nhist = mtd[eltWS].getNumberHistograms()
#normalize each spectrum in the workspace
for n in range(0,nhist):
y = mtd[eltWS].readY(n)
scale = 1.0/y[0]
yscaled = scale * y
mtd[eltWS].setY(n, yscaled)
# Write each of the created workspaces to file
def elwinSaveWorkspaces(flist, dir, Verbose):
for fname in flist:
fpath = os.path.join(dir, fname+'.nxs')
if Verbose:
logger.notice('Creating file : '+ fpath)
SaveNexusProcessed(InputWorkspace=fname, Filename=fpath)
# Add sample log to each of the workspaces created by Elwin
def addElwinLogs(ws, label, eRange, Range2):
AddSampleLog(Workspace=ws, LogName="vert_axis", LogType="String", LogText=label)
AddSampleLog(Workspace=ws, LogName="range1_start", LogType="Number", LogText=str(eRange[0]))
AddSampleLog(Workspace=ws, LogName="range1_end", LogType="Number", LogText=str(eRange[1]))
AddSampleLog(Workspace=ws, LogName="two_ranges", LogType="String", LogText=str(Range2))
if Range2:
AddSampleLog(Workspace=ws, LogName="range2_start", LogType="Number", LogText=str(eRange[2]))
AddSampleLog(Workspace=ws, LogName="range2_end", LogType="Number", LogText=str(eRange[3]))
#Plot each of the workspace output by elwin
def elwinPlot(label,eq1,eq2,elf,elt):
plotElwinWorkspace(eq1, yAxisTitle='Elastic Intensity', setScale=True)
plotElwinWorkspace(eq2, yAxisTitle='log(Elastic Intensity)', setScale=True)
plotElwinWorkspace(elf, xAxisTitle=label)
if elt is not None:
plotElwinWorkspace(elt, xAxisTitle=label)
#Plot a workspace generated by Elwin
def plotElwinWorkspace(ws, xAxisTitle=None, yAxisTitle=None, setScale=False):
ws = mtd[ws]
nBins = ws.blocksize()
lastX = ws.readX(0)[nBins-1]
nhist = ws.getNumberHistograms()
try:
graph = mp.plotSpectrum(ws, range(0,nhist))
except RuntimeError, e:
#User clicked cancel on plot so don't do anything
return None
layer = graph.activeLayer()
#set the x scale of the layer
if setScale:
layer.setScale(mp.Layer.Bottom, 0.0, lastX)
#set the title on the x-axis
if xAxisTitle:
layer.setAxisTitle(mp.Layer.Bottom, xAxisTitle)
#set the title on the y-axis
if yAxisTitle:
layer.setAxisTitle(mp.Layer.Left, yAxisTitle)
##############################################################################
# Fury
##############################################################################
def furyPlot(inWS, spec):
graph = mp.plotSpectrum(inWS, spec)
layer = graph.activeLayer()
layer.setScale(mp.Layer.Left, 0, 1.0)
def fury(samWorkspaces, res_workspace, rebinParam, RES=True, Save=False, Verbose=False,
Plot=False):
StartTime('Fury')
workdir = config['defaultsave.directory']
samTemp = samWorkspaces[0]
nsam,npt = CheckHistZero(samTemp)
Xin = mtd[samTemp].readX(0)
d1 = Xin[1]-Xin[0]
if d1 < 1e-8:
error = 'Data energy bin is zero'
logger.notice('ERROR *** ' + error)
sys.exit(error)
d2 = Xin[npt-1]-Xin[npt-2]
dmin = min(d1,d2)
pars = rebinParam.split(',')
if (float(pars[1]) <= dmin):
error = 'EWidth = ' + pars[1] + ' < smallest Eincr = ' + str(dmin)
logger.notice('ERROR *** ' + error)
sys.exit(error)
outWSlist = []
# Process RES Data Only Once
CheckAnalysers(samTemp, res_workspace, Verbose)
nres,nptr = CheckHistZero(res_workspace)
if nres > 1:
CheckHistSame(samTemp,'Sample', res_workspace, 'Resolution')
tmp_res_workspace = '__tmp_' + res_workspace
Rebin(InputWorkspace=res_workspace, OutputWorkspace=tmp_res_workspace, Params=rebinParam)
Integration(InputWorkspace=tmp_res_workspace, OutputWorkspace='res_int')
ConvertToPointData(InputWorkspace=tmp_res_workspace, OutputWorkspace=tmp_res_workspace)
ExtractFFTSpectrum(InputWorkspace=tmp_res_workspace, OutputWorkspace='res_fft', FFTPart=2)
Divide(LHSWorkspace='res_fft', RHSWorkspace='res_int', OutputWorkspace='res')
for samWs in samWorkspaces:
(direct, filename) = os.path.split(samWs)
(root, ext) = os.path.splitext(filename)
Rebin(InputWorkspace=samWs, OutputWorkspace='sam_data', Params=rebinParam)
Integration(InputWorkspace='sam_data', OutputWorkspace='sam_int')
ConvertToPointData(InputWorkspace='sam_data', OutputWorkspace='sam_data')
ExtractFFTSpectrum(InputWorkspace='sam_data', OutputWorkspace='sam_fft', FFTPart=2)
Divide(LHSWorkspace='sam_fft', RHSWorkspace='sam_int', OutputWorkspace='sam')
# Create save file name
savefile = getWSprefix(samWs) + 'iqt'
outWSlist.append(savefile)
Divide(LHSWorkspace='sam', RHSWorkspace='res', OutputWorkspace=savefile)
#Cleanup Sample Files
DeleteWorkspace('sam_data')
DeleteWorkspace('sam_int')
DeleteWorkspace('sam_fft')
DeleteWorkspace('sam')
# Crop nonsense values off workspace
bin = int(math.ceil(mtd[savefile].blocksize()/2.0))
binV = mtd[savefile].dataX(0)[bin]
CropWorkspace(InputWorkspace=savefile, OutputWorkspace=savefile, XMax=binV)
if Save:
opath = os.path.join(workdir, savefile+'.nxs') # path name for nxs file
SaveNexusProcessed(InputWorkspace=savefile, Filename=opath)
if Verbose:
logger.notice('Output file : '+opath)
# Clean Up RES files
DeleteWorkspace(tmp_res_workspace)
DeleteWorkspace('res_int')
DeleteWorkspace('res_fft')
DeleteWorkspace('res')
if Plot:
specrange = range(0,mtd[outWSlist[0]].getNumberHistograms())
furyPlot(outWSlist, specrange)
EndTime('Fury')
return outWSlist
##############################################################################
# FuryFit
##############################################################################
def furyfitSeq(inputWS, func, ftype, startx, endx, spec_min=0, spec_max=None, intensities_constrained=False, Save=False, Plot='None', Verbose=False):
StartTime('FuryFit')
fit_type = ftype[:-2]
if Verbose:
logger.notice('Option: ' + fit_type)
logger.notice(func)
tmp_fit_workspace = "__furyfit_fit_ws"
CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx)
num_hist = mtd[inputWS].getNumberHistograms()
if spec_max is None:
spec_max = num_hist - 1
# name stem for generated workspace
output_workspace = getWSprefix(inputWS) + 'fury_' + ftype + str(spec_min) + "_to_" + str(spec_max)
ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace)
convertToElasticQ(tmp_fit_workspace)
#build input string for PlotPeakByLogValue
input_str = [tmp_fit_workspace + ',i%d' % i for i in range(spec_min, spec_max + 1)]
input_str = ';'.join(input_str)
PlotPeakByLogValue(Input=input_str, OutputWorkspace=output_workspace, Function=func,
StartX=startx, EndX=endx, FitType='Sequential', CreateOutput=True)
#remove unsused workspaces
DeleteWorkspace(output_workspace + '_NormalisedCovarianceMatrices')
DeleteWorkspace(output_workspace + '_Parameters')
fit_group = output_workspace + '_Workspaces'
params_table = output_workspace + '_Parameters'
RenameWorkspace(output_workspace, OutputWorkspace=params_table)
#create *_Result workspace
result_workspace = output_workspace + "_Result"
parameter_names = ['A0', 'Intensity', 'Tau', 'Beta']
convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace)
#set x units to be momentum transfer
axis = mtd[result_workspace].getAxis(0)
axis.setUnit("MomentumTransfer")
#process generated workspaces
wsnames = mtd[fit_group].getNames()
params = [startx, endx, fit_type]
for i, ws in enumerate(wsnames):
output_ws = output_workspace + '_%d_Workspace' % i
RenameWorkspace(ws, OutputWorkspace=output_ws)
sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': fit_type,
'intensities_constrained': intensities_constrained, 'beta_constrained': False}
CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group)
CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace)
addSampleLogs(fit_group, sample_logs)
addSampleLogs(result_workspace, sample_logs)
if Save:
save_workspaces = [result_workspace, fit_group]
furyFitSaveWorkspaces(save_workspaces, Verbose)
if Plot != 'None' :
furyfitPlotSeq(result_workspace, Plot)
EndTime('FuryFit')
return result_workspace
def furyfitMult(inputWS, function, ftype, startx, endx, spec_min=0, spec_max=None, intensities_constrained=False, Save=False, Plot='None', Verbose=False):
StartTime('FuryFit Multi')
nHist = mtd[inputWS].getNumberHistograms()
output_workspace = getWSprefix(inputWS) + 'fury_1Smult_s0_to_' + str(nHist-1)
option = ftype[:-2]
if Verbose:
logger.notice('Option: '+option)
logger.notice('Function: '+function)
#prepare input workspace for fitting
tmp_fit_workspace = "__furyfit_fit_ws"
if spec_max is None:
CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx,
StartWorkspaceIndex=spec_min)
else:
CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx,
StartWorkspaceIndex=spec_min, EndWorkspaceIndex=spec_max)
ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace)
convertToElasticQ(tmp_fit_workspace)
#fit multi-domian functino to workspace
multi_domain_func, kwargs = createFuryMultiDomainFunction(function, tmp_fit_workspace)
Fit(Function=multi_domain_func, InputWorkspace=tmp_fit_workspace, WorkspaceIndex=0,
Output=output_workspace, CreateOutput=True, **kwargs)
params_table = output_workspace + '_Parameters'
transposeFitParametersTable(params_table)
#set first column of parameter table to be axis values
ax = mtd[tmp_fit_workspace].getAxis(1)
axis_values = ax.extractValues()
for i, value in enumerate(axis_values):
mtd[params_table].setCell('axis-1', i, value)
#convert parameters to matrix workspace
result_workspace = output_workspace + "_Result"
parameter_names = ['A0', 'Intensity', 'Tau', 'Beta']
convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace)
#set x units to be momentum transfer
axis = mtd[result_workspace].getAxis(0)
axis.setUnit("MomentumTransfer")
result_workspace = output_workspace + '_Result'
fit_group = output_workspace + '_Workspaces'
sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': ftype,
'intensities_constrained': intensities_constrained, 'beta_constrained': True}
CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace)
CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group)
addSampleLogs(result_workspace, sample_logs)
addSampleLogs(fit_group, sample_logs)
DeleteWorkspace(tmp_fit_workspace)
if Save:
save_workspaces = [result_workspace]
furyFitSaveWorkspaces(save_workspaces, Verbose)
if Plot != 'None':
furyfitPlotSeq(result_workspace, Plot)
EndTime('FuryFit Multi')
return result_workspace
def createFuryMultiDomainFunction(function, input_ws):
multi= 'composite=MultiDomainFunction,NumDeriv=1;'
comp = '(composite=CompositeFunction,$domains=i;' + function + ');'
ties = []
kwargs = {}
num_spectra = mtd[input_ws].getNumberHistograms()
for i in range(0, num_spectra):
multi += comp
kwargs['WorkspaceIndex_' + str(i)] = i
if i > 0:
kwargs['InputWorkspace_' + str(i)] = input_ws
#tie beta for every spectrum
tie = 'f%d.f1.Beta=f0.f1.Beta' % i
ties.append(tie)
ties = ','.join(ties)
multi += 'ties=(' + ties + ')'
return multi, kwargs
def furyFitSaveWorkspaces(save_workspaces, Verbose):
workdir = getDefaultWorkingDirectory()
for ws in save_workspaces:
#save workspace to default directory
fpath = os.path.join(workdir, ws+'.nxs')
SaveNexusProcessed(InputWorkspace=ws, Filename=fpath)
if Verbose:
logger.notice(ws + ' output to file : '+fpath)
def furyfitPlotSeq(ws, plot):
if plot == 'All':
param_names = ['Intensity', 'Tau', 'Beta']
else:
param_names = [plot]
plotParameters(ws, *param_names)
##############################################################################
# MSDFit
##############################################################################
def msdfitPlotSeq(inputWS, xlabel):
ws = mtd[inputWS+'_A1']
if len(ws.readX(0)) > 1:
msd_plot = mp.plotSpectrum(inputWS+'_A1',0,True)
msd_layer = msd_plot.activeLayer()
msd_layer.setAxisTitle(mp.Layer.Bottom,xlabel)
msd_layer.setAxisTitle(mp.Layer.Left,'<u2>')
def msdfit(ws, startX, endX, spec_min=0, spec_max=None, Save=False, Verbose=False, Plot=True):
StartTime('msdFit')
workdir = getDefaultWorkingDirectory()
num_spectra = mtd[ws].getNumberHistograms()
if spec_max is None:
spec_max = num_spectra - 1
if spec_min < 0 or spec_max >= num_spectra:
raise ValueError("Invalid spectrum range: %d - %d" % (spec_min, spec_max))
xlabel = ''
ws_run = mtd[ws].getRun()
if 'vert_axis' in ws_run:
xlabel = ws_run.getLogData('vert_axis').value
mname = ws[:-4]
msdWS = mname+'_msd'
#fit line to each of the spectra
function = 'name=LinearBackground, A0=0, A1=0'
input_params = [ ws+',i%d' % i for i in xrange(spec_min, spec_max+1)]
input_params = ';'.join(input_params)
PlotPeakByLogValue(Input=input_params, OutputWorkspace=msdWS, Function=function,
StartX=startX, EndX=endX, FitType='Sequential', CreateOutput=True)
DeleteWorkspace(msdWS + '_NormalisedCovarianceMatrices')
DeleteWorkspace(msdWS + '_Parameters')
msd_parameters = msdWS+'_Parameters'
RenameWorkspace(msdWS, OutputWorkspace=msd_parameters)
params_table = mtd[msd_parameters]
#msd value should be positive, but the fit output is negative
msd = params_table.column('A1')
for i, value in enumerate(msd):
params_table.setCell('A1', i, value * -1)
#create workspaces for each of the parameters
group = []
ws_name = msdWS + '_A0'
group.append(ws_name)
ConvertTableToMatrixWorkspace(msd_parameters, OutputWorkspace=ws_name,
ColumnX='axis-1', ColumnY='A0', ColumnE='A0_Err')
xunit = mtd[ws_name].getAxis(0).setUnit('Label')
xunit.setLabel('Temperature', 'K')
ws_name = msdWS + '_A1'
group.append(ws_name)
ConvertTableToMatrixWorkspace(msd_parameters, OutputWorkspace=ws_name,
ColumnX='axis-1', ColumnY='A1', ColumnE='A1_Err')
SortXAxis(ws_name, OutputWorkspace=ws_name)
xunit = mtd[ws_name].getAxis(0).setUnit('Label')
xunit.setLabel('Temperature', 'K')
GroupWorkspaces(InputWorkspaces=','.join(group),OutputWorkspace=msdWS)
#add sample logs to output workspace
fit_workspaces = msdWS + '_Workspaces'
CopyLogs(InputWorkspace=ws, OutputWorkspace=msdWS)
AddSampleLog(Workspace=msdWS, LogName="start_x", LogType="Number", LogText=str(startX))
AddSampleLog(Workspace=msdWS, LogName="end_x", LogType="Number", LogText=str(endX))
CopyLogs(InputWorkspace=msdWS + '_A0', OutputWorkspace=fit_workspaces)
if Plot:
msdfitPlotSeq(msdWS, xlabel)
if Save:
msd_path = os.path.join(workdir, msdWS+'.nxs') # path name for nxs file
SaveNexusProcessed(InputWorkspace=msdWS, Filename=msd_path, Title=msdWS)
if Verbose:
logger.notice('Output msd file : '+msd_path)
EndTime('msdFit')
return fit_workspaces
def plotInput(inputfiles,spectra=[]):
OneSpectra = False
if len(spectra) != 2:
spectra = [spectra[0], spectra[0]]
OneSpectra = True
workspaces = []
for file in inputfiles:
root = LoadNexus(Filename=file)
if not OneSpectra:
GroupDetectors(root, root, DetectorList=range(spectra[0],spectra[1]+1) )
workspaces.append(root)
if len(workspaces) > 0:
graph = mp.plotSpectrum(workspaces,0)
graph.activeLayer().setTitle(", ".join(workspaces))
##############################################################################
# Corrections
##############################################################################
def CubicFit(inputWS, spec, Verbose=False):
'''Uses the Mantid Fit Algorithm to fit a quadratic to the inputWS
parameter. Returns a list containing the fitted parameter values.'''
function = 'name=Quadratic, A0=1, A1=0, A2=0'
fit = Fit(Function=function, InputWorkspace=inputWS, WorkspaceIndex=spec,
CreateOutput=True, Output='Fit')
table = mtd['Fit_Parameters']
A0 = table.cell(0,1)
A1 = table.cell(1,1)
A2 = table.cell(2,1)
Abs = [A0, A1, A2]
if Verbose:
logger.notice('Group '+str(spec)+' of '+inputWS+' ; fit coefficients are : '+str(Abs))
return Abs
def subractCanWorkspace(sample, can, output_name, rebin_can=False):
'''Subtract the can workspace from the sample workspace.
Optionally rebin the can to match the sample.
@param sample :: sample workspace to use subract from
@param can :: can workspace to subtract
@param rebin_can :: whether to rebin the can first.
@return corrected sample workspace
'''
if rebin_can:
logger.warning("Sample and Can do not match. Rebinning Can to match Sample.")
RebinToWorkspace(WorkspaceToRebin=can, WorkspaceToMatch=sample, OutputWorkspace=can)
try:
Minus(LHSWorkspace=sample, RHSWorkspace=can, OutputWorkspace=output_name)
except ValueError:
raise ValueError("Sample and Can energy ranges do not match. \
Do they have the same binning?")
def applyCorrections(inputWS, canWS, corr, rebin_can=False, Verbose=False):
'''Through the PolynomialCorrection algorithm, makes corrections to the
input workspace based on the supplied correction values.'''
# Corrections are applied in Lambda (Wavelength)
efixed = getEfixed(inputWS) # Get efixed
sam_name = getWSprefix(inputWS)
ConvertUnits(InputWorkspace=inputWS, OutputWorkspace=inputWS, Target='Wavelength',
EMode='Indirect', EFixed=efixed)
nameStem = corr[:-4]
corrections = mtd[corr].getNames()
if mtd.doesExist(canWS):
(instr, can_run) = getInstrRun(canWS)
CorrectedWS = sam_name +'Correct_'+ can_run
ConvertUnits(InputWorkspace=canWS, OutputWorkspace=canWS, Target='Wavelength',
EMode='Indirect', EFixed=efixed)
else:
CorrectedWS = sam_name +'Corrected'
nHist = mtd[inputWS].getNumberHistograms()
# Check that number of histograms in each corrections workspace matches
# that of the input (sample) workspace
for ws in corrections:
if ( mtd[ws].getNumberHistograms() != nHist ):
raise ValueError('Mismatch: num of spectra in '+ws+' and inputWS')
# Workspaces that hold intermediate results
CorrectedSampleWS = '__csam'
CorrectedCanWS = '__ccan'
for i in range(0, nHist): # Loop through each spectra in the inputWS
ExtractSingleSpectrum(InputWorkspace=inputWS, OutputWorkspace=CorrectedSampleWS,
WorkspaceIndex=i)
logger.notice(str(i) + str(mtd[CorrectedSampleWS].readX(0)))
if ( len(corrections) == 1 ):
Ass = CubicFit(corrections[0], i, Verbose)
PolynomialCorrection(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedSampleWS,
Coefficients=Ass, Operation='Divide')
if ( i == 0 ):
CloneWorkspace(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedWS)
else:
ConjoinWorkspaces(InputWorkspace1=CorrectedWS, InputWorkspace2=CorrectedSampleWS)
else:
if mtd.doesExist(canWS):
ExtractSingleSpectrum(InputWorkspace=canWS, OutputWorkspace=CorrectedCanWS,
WorkspaceIndex=i)
Acc = CubicFit(corrections[3], i, Verbose)
PolynomialCorrection(InputWorkspace=CorrectedCanWS, OutputWorkspace=CorrectedCanWS,
Coefficients=Acc, Operation='Divide')
Acsc = CubicFit(corrections[2], i, Verbose)
PolynomialCorrection(InputWorkspace=CorrectedCanWS, OutputWorkspace=CorrectedCanWS,
Coefficients=Acsc, Operation='Multiply')
subractCanWorkspace(CorrectedSampleWS, CorrectedCanWS, CorrectedSampleWS, rebin_can=rebin_can)
Assc = CubicFit(corrections[1], i, Verbose)
PolynomialCorrection(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedSampleWS,
Coefficients=Assc, Operation='Divide')
if ( i == 0 ):
CloneWorkspace(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedWS)
else:
ConjoinWorkspaces(InputWorkspace1=CorrectedWS, InputWorkspace2=CorrectedSampleWS,
CheckOverlapping=False)
ConvertUnits(InputWorkspace=inputWS, OutputWorkspace=inputWS, Target='DeltaE',
EMode='Indirect', EFixed=efixed)
ConvertUnits(InputWorkspace=CorrectedWS, OutputWorkspace=CorrectedWS, Target='DeltaE',
EMode='Indirect', EFixed=efixed)
ConvertSpectrumAxis(InputWorkspace=CorrectedWS, OutputWorkspace=CorrectedWS+'_rqw',
Target='ElasticQ', EMode='Indirect', EFixed=efixed)
RenameWorkspace(InputWorkspace=CorrectedWS, OutputWorkspace=CorrectedWS+'_red')
if mtd.doesExist(canWS):
ConvertUnits(InputWorkspace=canWS, OutputWorkspace=canWS, Target='DeltaE',
EMode='Indirect', EFixed=efixed)
DeleteWorkspace('Fit_NormalisedCovarianceMatrix')
DeleteWorkspace('Fit_Parameters')
DeleteWorkspace('Fit_Workspace')
return CorrectedWS
def abscorFeeder(sample, container, geom, useCor, corrections, Verbose=False, RebinCan=False, ScaleOrNotToScale=False, factor=1, Save=False,
PlotResult='None', PlotContrib=False):
'''Load up the necessary files and then passes them into the main
applyCorrections routine.'''
StartTime('ApplyCorrections')
workdir = config['defaultsave.directory']
s_hist,sxlen = CheckHistZero(sample)
CloneWorkspace(sample, OutputWorkspace='__apply_corr_cloned_sample')
sample = '__apply_corr_cloned_sample'
scaled_container = "__apply_corr_scaled_container"
diffraction_run = checkUnitIs(sample, 'dSpacing')
sam_name = getWSprefix(sample)
ext = '_red'
if not diffraction_run:
efixed = getEfixed(sample)
if container != '':
CheckHistSame(sample, 'Sample', container, 'Container')
if not diffraction_run:
CheckAnalysers(sample, container, Verbose)
if diffraction_run and not checkUnitIs(container, 'dSpacing'):
raise ValueError("Sample and Can must both have the same units.")
(instr, can_run) = getInstrRun(container)
if ScaleOrNotToScale:
#use temp workspace so we don't modify original data
Scale(InputWorkspace=container, OutputWorkspace=scaled_container, Factor=factor, Operation='Multiply')
if Verbose:
logger.notice('Container scaled by %f' % factor)
else:
CloneWorkspace(InputWorkspace=container, OutputWorkspace=scaled_container)
if useCor:
if diffraction_run:
raise NotImplementedError("Applying absorption corrections is not currently supported for diffraction data.")
if Verbose:
text = 'Correcting sample ' + sample
if container != '':
text += ' with ' + container
logger.notice(text)
cor_result = applyCorrections(sample, scaled_container, corrections, RebinCan, Verbose)
rws = mtd[cor_result + ext]
outNm = cor_result + '_Result_'