-
Notifications
You must be signed in to change notification settings - Fork 122
/
IndirectILLReductionQENS.py
449 lines (349 loc) · 20.6 KB
/
IndirectILLReductionQENS.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
from __future__ import (absolute_import, division, print_function)
from mantid.simpleapi import * # noqa
from mantid.kernel import * # noqa
from mantid.api import * # noqa
from mantid import mtd
import numpy
class IndirectILLReductionQENS(PythonAlgorithm):
_sample_files = None
_alignment_files = None
_background_files = None
_calibration_files = None
_sum_all_runs = None
_unmirror_option = None
_back_scaling = None
_criteria = None
_progress = None
_red_ws = None
_common_args = {}
_peak_range = []
_runs = None
def category(self):
return "Workflow\\MIDAS;Workflow\\Inelastic;Inelastic\\Indirect;Inelastic\\Reduction"
def summary(self):
return 'Performs quasi-elastic neutron scattering (QENS) multiple file reduction ' \
'for ILL indirect geometry data, instrument IN16B.'
def name(self):
return "IndirectILLReductionQENS"
def PyInit(self):
self.declareProperty(MultipleFileProperty('Run', extensions=['nxs']),
doc='Run number(s) of sample run(s).')
self.declareProperty(MultipleFileProperty('BackgroundRun',
action=FileAction.OptionalLoad,
extensions=['nxs']),
doc='Run number(s) of background (empty can) run(s).')
self.declareProperty(MultipleFileProperty('CalibrationRun',
action=FileAction.OptionalLoad,
extensions=['nxs']),
doc='Run number(s) of vanadium calibration run(s).')
self.declareProperty(MultipleFileProperty('AlignmentRun',
action=FileAction.OptionalLoad,
extensions=['nxs']),
doc='Run number(s) of vanadium run(s) used for '
'peak alignment for UnmirrorOption=[5, 7]')
self.declareProperty(name='SumRuns',
defaultValue=False,
doc='Whether to sum all the input runs.')
self.declareProperty(name='CropDeadMonitorChannels', defaultValue=False,
doc='Whether or not to exclude the first and last few channels '
'with 0 monitor count in the energy transfer formula.')
self.declareProperty(name='UnmirrorOption', defaultValue=6,
validator=IntBoundedValidator(lower=0, upper=7),
doc='Unmirroring options : \n'
'0 no unmirroring\n'
'1 sum of left and right\n'
'2 left\n'
'3 right\n'
'4 shift right according to left and sum\n'
'5 like 4, but use alignment run for peak positions\n'
'6 center both left and right at zero and sum\n'
'7 like 6, but use alignment run for peak positions')
self.declareProperty(name='BackgroundScalingFactor', defaultValue=1.,
validator=FloatBoundedValidator(lower=0),
doc='Scaling factor for background subtraction')
self.declareProperty(name='CalibrationPeakRange', defaultValue=[-0.003,0.003],
validator=FloatArrayMandatoryValidator(),
doc='Peak range for integration over calibration file peak (in mev)')
self.declareProperty(FileProperty('MapFile', '',
action=FileAction.OptionalLoad,
extensions=['map','xml']),
doc='Filename of the detector grouping map file to use. \n'
'By default all the pixels will be summed per each tube. \n'
'Use .map or .xml file (see GroupDetectors documentation) '
'only if different range is needed for each tube.')
self.declareProperty(name='ManualPSDIntegrationRange',defaultValue=[1,128],
doc='Integration range of vertical pixels in each PSD tube. \n'
'By default all the pixels will be summed per each tube. \n'
'Use this option if the same range (other than default) '
'is needed for all the tubes.')
self.declareProperty(name='Analyser',
defaultValue='silicon',
validator=StringListValidator(['silicon']),
doc='Analyser crystal.')
self.declareProperty(name='Reflection',
defaultValue='111',
validator=StringListValidator(['111', '311']),
doc='Analyser reflection.')
self.declareProperty(WorkspaceGroupProperty('OutputWorkspace', '',
direction=Direction.Output),
doc='Group name for the reduced workspace(s).')
def validateInputs(self):
issues = dict()
uo = self.getProperty('UnmirrorOption').value
if (uo == 5 or uo == 7) and not self.getPropertyValue('AlignmentRun'):
issues['AlignmentRun'] = 'Given UnmirrorOption requires alignment run to be set'
if self.getPropertyValue('CalibrationRun'):
range = self.getProperty('CalibrationPeakRange').value
if len(range) != 2:
issues['CalibrationPeakRange'] = 'Please provide valid calibration range ' \
'(comma separated 2 energy values).'
elif range[0] >= range[1]:
issues['CalibrationPeakRange'] = 'Please provide valid calibration range. ' \
'Start energy is bigger than end energy.'
return issues
def setUp(self):
self._sample_file = self.getPropertyValue('Run')
self._alignment_file = self.getPropertyValue('AlignmentRun').replace(',', '+') # automatic summing
self._background_file = self.getPropertyValue('BackgroundRun').replace(',', '+') # automatic summing
self._calibration_file = self.getPropertyValue('CalibrationRun').replace(',', '+') # automatic summing
self._sum_all_runs = self.getProperty('SumRuns').value
self._unmirror_option = self.getProperty('UnmirrorOption').value
self._back_scaling = self.getProperty('BackgroundScalingFactor').value
self._peak_range = self.getProperty('CalibrationPeakRange').value
self._red_ws = self.getPropertyValue('OutputWorkspace') + '_red'
# arguments to pass to IndirectILLEnergyTransfer
self._common_args['MapFile'] = self.getPropertyValue('MapFile')
self._common_args['Analyser'] = self.getPropertyValue('Analyser')
self._common_args['Reflection'] = self.getPropertyValue('Reflection')
self._common_args['ManualPSDIntegrationRange'] = self.getProperty('ManualPSDIntegrationRange').value
self._common_args['CropDeadMonitorChannels'] = self.getProperty('CropDeadMonitorChannels').value
if self._sum_all_runs is True:
self.log().notice('All the sample runs will be summed')
self._sample_file = self._sample_file.replace(',', '+')
# Nexus metadata criteria for QENS type of data
self._criteria = '$/entry0/instrument/Doppler/maximum_delta_energy$ != 0. and ' \
'$/entry0/instrument/Doppler/velocity_profile$ == 0'
# empty list to store all final workspaces to group
self._ws_list = []
def _mask(self, ws, xstart, xend):
"""
Masks the first and last bins
@param ws :: input workspace name
@param xstart :: MaskBins between x[0] and x[xstart]
@param xend :: MaskBins between x[xend] and x[-1]
"""
x_values = mtd[ws].readX(0)
if xstart > 0:
self.log().debug('Mask bins smaller than {0}'.format(xstart))
MaskBins(InputWorkspace=ws, OutputWorkspace=ws, XMin=x_values[0], XMax=x_values[xstart])
if xend < len(x_values) - 1:
self.log().debug('Mask bins larger than {0}'.format(xend))
MaskBins(InputWorkspace=ws, OutputWorkspace=ws, XMin=x_values[xend + 1], XMax=x_values[-1])
def _filter_files(self, files, label):
'''
Filters the given list of files according to nexus criteria
@param files :: list of input files (i.e. , and + separated string)
@param label :: label of error message if nothing left after filtering
@throws RuntimeError :: when nothing left after filtering
@return :: the list of input files that passsed the criteria
'''
files = SelectNexusFilesByMetadata(files, self._criteria)
if not files:
raise RuntimeError('None of the {0} runs are of QENS type.'
'Check the files or reduction type.'.format(label))
else:
self.log().information('Filtered {0} runs are: {0} \\n'.format(label,files.replace(',','\\n')))
return files
def _filter_all_input_files(self):
'''
Filters all the lists of input files needed for the reduction.
'''
self._sample_file = self._filter_files(self._sample_file,'sample')
if self._background_file:
self._background_file = self._filter_files(self._background_file, 'background')
if self._calibration_file:
self._calibration_file = self._filter_files(self._calibration_file, 'calibration')
if self._alignment_file:
self._alignment_file = self._filter_files(self._alignment_file, 'alignment')
def _warn_negative_integral(self, ws, message):
'''
Raises an error if an integral of the given workspace is <= 0
@param ws :: input workspace name
@param message :: message suffix for the error
@throws RuntimeError :: on non-positive integral found
'''
tmp_int = '__tmp_int'+ws
Integration(InputWorkspace=ws,OutputWorkspace=tmp_int)
for item in mtd[tmp_int]:
for index in range(item.getNumberHistograms()):
if item.readY(index)[0] <= 0:
raise RuntimeError('Negative or 0 integral in spectrum #{0} {1}'.format(index,message))
DeleteWorkspace(tmp_int)
def PyExec(self):
self.setUp()
self._filter_all_input_files()
if self._background_file:
background = '__background_'+self._red_ws
IndirectILLEnergyTransfer(Run = self._background_file, OutputWorkspace = background, **self._common_args)
Scale(InputWorkspace=background ,Factor=self._back_scaling,OutputWorkspace=background)
if self._calibration_file:
calibration = '__calibration_'+self._red_ws
IndirectILLEnergyTransfer(Run = self._calibration_file, OutputWorkspace = calibration, **self._common_args)
MatchPeaks(InputWorkspace=calibration,OutputWorkspace=calibration,MaskBins=True)
Integration(InputWorkspace=calibration,RangeLower=self._peak_range[0],RangeUpper=self._peak_range[1],
OutputWorkspace=calibration)
self._warn_negative_integral(calibration,'in calibration run.')
if self._unmirror_option == 5 or self._unmirror_option == 7:
alignment = '__alignment_'+self._red_ws
IndirectILLEnergyTransfer(Run = self._alignment_file, OutputWorkspace = alignment, **self._common_args)
runs = self._sample_file.split(',')
self._progress = Progress(self, start=0.0, end=1.0, nreports=len(runs))
for run in runs:
self._reduce_run(run)
if self._background_file:
DeleteWorkspace(background)
if self._calibration_file:
DeleteWorkspace(calibration)
if self._unmirror_option == 5 or self._unmirror_option == 7:
DeleteWorkspace(alignment)
GroupWorkspaces(InputWorkspaces=self._ws_list,OutputWorkspace=self._red_ws)
# unhide the final workspaces, i.e. remove __ prefix
for ws in mtd[self._red_ws]:
RenameWorkspace(InputWorkspace=ws,OutputWorkspace=ws.getName()[2:])
self.setProperty('OutputWorkspace',self._red_ws)
def _reduce_run(self,run):
'''
Reduces the given (single or summed multiple) run
@param run :: run path
'''
runs_list = run.split('+')
runnumber = os.path.basename(runs_list[0]).split('.')[0]
self._progress.report("Reducing run #" + runnumber)
ws = '__' + runnumber
if (len(runs_list) > 1):
ws += '_multiple'
ws += '_' + self._red_ws
back_ws = '__background_'+self._red_ws
calib_ws = '__calibration_'+self._red_ws
IndirectILLEnergyTransfer(Run = run, OutputWorkspace = ws, **self._common_args)
wings = mtd[ws].getNumberOfEntries()
if self._background_file:
if wings == mtd[back_ws].getNumberOfEntries():
Minus(LHSWorkspace=ws, RHSWorkspace=back_ws, OutputWorkspace=ws)
self._warn_negative_integral(ws,'after background subtraction.')
else:
raise RuntimeError('Inconsistent mirror sense in background run. Unable to perform subtraction.')
if self._calibration_file:
if wings == mtd[calib_ws].getNumberOfEntries():
Divide(LHSWorkspace=ws, RHSWorkspace=calib_ws, OutputWorkspace=ws)
self._scale_calibration(ws, calib_ws)
else:
raise RuntimeError('Inconsistent mirror sense in calibration run. Unable to perform calibration.')
self._perform_unmirror(ws,runnumber)
# register to reduced runs list
self._ws_list.append(ws)
def _scale_calibration(self, ws, calib_ws):
'''
Scales the wings of calibrated sample ws with the maximum
of the integrated intensities in each wing of calib ws
@param ws :: calibrated sample workspace
@param calib_ws :: calibration workspace
'''
# number of wings are checked to be the same in ws and calib_ws here already
for wing in range(mtd[ws].getNumberOfEntries()):
sample = mtd[ws].getItem(wing).getName()
integral = mtd[calib_ws].getItem(wing).getName()
scale = numpy.max(mtd[integral].extractY()[:,0])
self.log().information("Wing {0} will be scaled up with {1} after calibration"
.format(wing,scale))
Scale(InputWorkspace=sample,Factor=scale,OutputWorkspace=sample,Operation='Multiply')
def _perform_unmirror(self, ws, run):
'''
Performs unmirroring, i.e. summing of left and right wings
for two-wing data or centering the one wing data
@param ws :: workspace
@param run :: runnumber
'''
outname = ws + '_tmp'
wings = mtd[ws].getNumberOfEntries()
self.log().information('Unmirroring workspace {0} with option {1}'
.format(ws,self._unmirror_option))
alignment = '__alignment_'+self._red_ws
# make sure the sample and alignment runs have the same mirror sense for unmirror 5,7
if self._unmirror_option == 5 or self._unmirror_option == 7:
if wings != mtd[alignment].getNumberOfEntries():
raise RuntimeError('Inconsistent mirror sense in alignment run. Unable to perform unmirror.')
if wings == 1: # one wing
name = mtd[ws].getItem(0).getName()
if self._unmirror_option < 6: # do unmirror 0, i.e. nothing
CloneWorkspace(InputWorkspace = name, OutputWorkspace = outname)
elif self._unmirror_option == 6:
MatchPeaks(InputWorkspace = name, OutputWorkspace = outname, MaskBins = True)
elif self._unmirror_option == 7:
MatchPeaks(InputWorkspace = name, InputWorkspace2 = mtd[alignment].getItem(0).getName(),
MatchInput2ToCenter = True, OutputWorkspace = outname, MaskBins = True)
elif wings == 2: # two wing
left = mtd[ws].getItem(0).getName()
right = mtd[ws].getItem(1).getName()
mask_min = 0
mask_max = mtd[left].blocksize()
if self._unmirror_option == 0:
left_out = '__'+run+'_'+self._red_ws+'_left'
right_out = '__'+run+'_'+self._red_ws+'_right'
CloneWorkspace(InputWorkspace=left, OutputWorkspace=left_out)
CloneWorkspace(InputWorkspace=right, OutputWorkspace=right_out)
GroupWorkspaces(InputWorkspaces=[left_out,right_out],OutputWorkspace=outname)
elif self._unmirror_option == 1:
Plus(LHSWorkspace=left, RHSWorkspace=right, OutputWorkspace=outname)
Scale(InputWorkspace=outname, OutputWorkspace=outname, Factor=0.5)
elif self._unmirror_option == 2:
CloneWorkspace(InputWorkspace=left, OutputWorkspace=outname)
elif self._unmirror_option == 3:
CloneWorkspace(InputWorkspace=right, OutputWorkspace=outname)
elif self._unmirror_option == 4:
bin_range_table = '__um4_'+right
MatchPeaks(InputWorkspace=right, InputWorkspace2=left, OutputWorkspace=right,
MaskBins = True, BinRangeTable = bin_range_table)
mask_min = mtd[bin_range_table].row(0)['MinBin']
mask_max = mtd[bin_range_table].row(0)['MaxBin']
DeleteWorkspace(bin_range_table)
elif self._unmirror_option == 5:
bin_range_table = '__um5_' + right
MatchPeaks(InputWorkspace=right, InputWorkspace2=mtd[alignment].getItem(0).getName(),
InputWorkspace3=mtd[alignment].getItem(1).getName(), OutputWorkspace=right,
MaskBins = True, BinRangeTable = bin_range_table)
mask_min = mtd[bin_range_table].row(0)['MinBin']
mask_max = mtd[bin_range_table].row(0)['MaxBin']
DeleteWorkspace(bin_range_table)
elif self._unmirror_option == 6:
bin_range_table_left = '__um6_' + left
bin_range_table_right = '__um6_' + right
MatchPeaks(InputWorkspace=left, OutputWorkspace=left, MaskBins = True,
BinRangeTable = bin_range_table_left)
MatchPeaks(InputWorkspace=right, OutputWorkspace=right, MaskBins = True,
BinRangeTable=bin_range_table_right)
mask_min = max(mtd[bin_range_table_left].row(0)['MinBin'],mtd[bin_range_table_right].row(0)['MinBin'])
mask_max = min(mtd[bin_range_table_left].row(0)['MaxBin'],mtd[bin_range_table_right].row(0)['MaxBin'])
DeleteWorkspace(bin_range_table_left)
DeleteWorkspace(bin_range_table_right)
elif self._unmirror_option == 7:
bin_range_table_left = '__um7_' + left
bin_range_table_right = '__um7_' + right
MatchPeaks(InputWorkspace=left, InputWorkspace2=mtd[alignment].getItem(0).getName(),
OutputWorkspace=left,MatchInput2ToCenter=True,
MaskBins = True, BinRangeTable=bin_range_table_left)
MatchPeaks(InputWorkspace=right, InputWorkspace2=mtd[alignment].getItem(1).getName(),
OutputWorkspace=right, MatchInput2ToCenter=True,
MaskBins = True, BinRangeTable=bin_range_table_right)
mask_min = max(mtd[bin_range_table_left].row(0)['MinBin'], mtd[bin_range_table_right].row(0)['MinBin'])
mask_max = min(mtd[bin_range_table_left].row(0)['MaxBin'], mtd[bin_range_table_right].row(0)['MaxBin'])
DeleteWorkspace(bin_range_table_left)
DeleteWorkspace(bin_range_table_right)
if self._unmirror_option > 3:
Plus(LHSWorkspace=left, RHSWorkspace=right, OutputWorkspace=outname)
Scale(InputWorkspace=outname, OutputWorkspace=outname, Factor=0.5)
self._mask(outname, mask_min, mask_max)
DeleteWorkspace(ws)
RenameWorkspace(InputWorkspace=outname,OutputWorkspace=ws)
# Register algorithm with Mantid
AlgorithmFactory.subscribe(IndirectILLReductionQENS)