-
Notifications
You must be signed in to change notification settings - Fork 122
/
IndirectILLReduction.py
404 lines (321 loc) · 16.5 KB
/
IndirectILLReduction.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
#pylint: disable=no-init,invalid-name
from __future__ import (absolute_import, division, print_function)
from mantid.simpleapi import *
from mantid.kernel import StringListValidator, Direction
from mantid.api import DataProcessorAlgorithm, PropertyMode, AlgorithmFactory, \
FileProperty, FileAction, MatrixWorkspaceProperty
from mantid import config, logger, mtd
import numpy as np
import os.path
#pylint: disable=too-many-instance-attributes
class IndirectILLReduction(DataProcessorAlgorithm):
_raw_workspace = None
_red_workspace = None
_red_left_workspace = None
_red_right_workspace = None
_map_file = None
_use_mirror_mode = None
_save = None
_plot = None
_instrument_name = None
_run_number = None
_analyser = None
_reflection = None
_run_name = None
_calibration_workspace = None
def category(self):
return "Workflow\\MIDAS;Inelastic\\Reduction"
def summary(self):
return 'Performs an energy transfer reduction for ILL indirect inelastic data.' \
'This algorithm is deprecated (20-Nov-2016). Use IndirectILLReductionQENS instead.'
def PyInit(self):
# Input options
self.declareProperty(FileProperty('Run', '',
action=FileAction.Load,
extensions=["nxs"]),
doc='File path of run.')
self.declareProperty(MatrixWorkspaceProperty("CalibrationWorkspace", "",
optional=PropertyMode.Optional,
direction=Direction.Input),
doc="Workspace containing calibration intensities.")
self.declareProperty(name='Analyser', defaultValue='silicon',
validator=StringListValidator(['silicon']),
doc='Analyser crystal.')
self.declareProperty(name='Reflection', defaultValue='111',
validator=StringListValidator(['111']),
doc='Analyser reflection.')
self.declareProperty(FileProperty('MapFile', '',
action=FileAction.OptionalLoad,
extensions=["xml"]),
doc='Filename of the map file to use. If left blank the default will be used.')
self.declareProperty(name='MirrorMode', defaultValue=False,
doc='Whether to use mirror mode.')
# Output workspace properties
self.declareProperty(MatrixWorkspaceProperty("RawWorkspace", "",
direction=Direction.Output),
doc="Name for the output raw workspace created.")
self.declareProperty(MatrixWorkspaceProperty("ReducedWorkspace", "",
direction=Direction.Output),
doc="Name for the output reduced workspace created. If mirror mode is used this will be the sum of both "
"the left and right hand workspaces.")
self.declareProperty(MatrixWorkspaceProperty("LeftWorkspace", "",
optional=PropertyMode.Optional,
direction=Direction.Output),
doc="Name for the left workspace if mirror mode is used.")
self.declareProperty(MatrixWorkspaceProperty("RightWorkspace", "",
optional=PropertyMode.Optional,
direction=Direction.Output),
doc="Name for the right workspace if mirror mode is used.")
# Output options
self.declareProperty(name='Save', defaultValue=False,
doc='Switch Save result to nxs file Off/On.')
self.declareProperty(name='Plot', defaultValue=False,
doc='Whether to plot the output workspace.')
def validateInputs(self):
issues = dict()
red_left_workspace = self.getPropertyValue('LeftWorkspace')
red_right_workspace = self.getPropertyValue('RightWorkspace')
use_mirror_mode = self.getProperty('MirrorMode').value
# Need the right and left workspaces for mirror mode
if use_mirror_mode:
if red_left_workspace == '':
issues['LeftWorkspace'] = 'Mirror Mode requires this workspace to be set'
if red_right_workspace == '':
issues['RightWorkspace'] = 'Mirror Mode requires this workspace to be set'
return issues
def PyExec(self):
self.log().error('This algorithm is deprecated (20-Nov-2016). '
'Use IndirectILLReductionQENS instead.')
self.log().information('IndirectILLreduction')
run_path = self.getPropertyValue('Run')
self._calibration_workspace = self.getPropertyValue('CalibrationWorkspace')
self._raw_workspace = self.getPropertyValue('RawWorkspace')
self._red_workspace = self.getPropertyValue('ReducedWorkspace')
self._red_left_workspace = self.getPropertyValue('LeftWorkspace')
self._red_right_workspace = self.getPropertyValue('RightWorkspace')
self._map_file = self.getProperty('MapFile').value
self._use_mirror_mode = self.getProperty('MirrorMode').value
self._save = self.getProperty('Save').value
self._plot = self.getProperty('Plot').value
LoadILLIndirect(FileName=run_path, OutputWorkspace=self._raw_workspace, Version=1)
instrument = mtd[self._raw_workspace].getInstrument()
self._instrument_name = instrument.getName()
self._run_number = mtd[self._raw_workspace].getRunNumber()
self._analyser = self.getPropertyValue('Analyser')
self._reflection = self.getPropertyValue('Reflection')
self._run_name = self._instrument_name + '_' + str(self._run_number)
AddSampleLog(Workspace=self._raw_workspace, LogName="mirror_sense",
LogType="String", LogText=str(self._use_mirror_mode))
logger.information('Nxs file : %s' % run_path)
output_workspaces = self._reduction()
if self._save:
workdir = config['defaultsave.directory']
for ws in output_workspaces:
file_path = os.path.join(workdir, ws + '.nxs')
SaveNexusProcessed(InputWorkspace=ws, Filename=file_path)
logger.information('Output file : ' + file_path)
if self._plot:
from IndirectImport import import_mantidplot
mtd_plot = import_mantidplot()
graph = mtd_plot.newGraph()
for ws in output_workspaces:
mtd_plot.plotSpectrum(ws, 0, window=graph)
layer = graph.activeLayer()
layer.setAxisTitle(mtd_plot.Layer.Bottom, 'Energy Transfer (meV)')
layer.setAxisTitle(mtd_plot.Layer.Left, '')
layer.setTitle('')
self.setPropertyValue('RawWorkspace', self._raw_workspace)
self.setPropertyValue('ReducedWorkspace', self._red_workspace)
if self._use_mirror_mode:
self.setPropertyValue('LeftWorkspace', self._red_left_workspace)
self.setPropertyValue('RightWorkspace', self._red_right_workspace)
def _reduction(self):
"""
Run energy conversion for IN16B
"""
logger.information('Input workspace : %s' % self._raw_workspace)
idf_directory = config['instrumentDefinition.directory']
ipf_name = self._instrument_name + '_' + self._analyser + '_' + self._reflection + '_Parameters.xml'
ipf_path = os.path.join(idf_directory, ipf_name)
LoadParameterFile(Workspace=self._raw_workspace, Filename=ipf_path)
AddSampleLog(Workspace=self._raw_workspace,
LogName="facility",
LogType="String",
LogText="ILL")
if self._map_file == '':
# path name for default map file
instrument = mtd[self._raw_workspace].getInstrument()
if instrument.hasParameter('Workflow.GroupingFile'):
grouping_filename = instrument.getStringParameter('Workflow.GroupingFile')[0]
self._map_file = os.path.join(config['groupingFiles.directory'], grouping_filename)
else:
raise ValueError("Failed to find default map file. Contact development team.")
logger.information('Map file : %s' % self._map_file)
grouped_ws = self._run_name + '_group'
GroupDetectors(InputWorkspace=self._raw_workspace,
OutputWorkspace=grouped_ws,
MapFile=self._map_file,
Behaviour='Average')
monitor_ws = self._run_name + '_mon'
ExtractSingleSpectrum(InputWorkspace=self._raw_workspace,
OutputWorkspace=monitor_ws,
WorkspaceIndex=0)
if self._use_mirror_mode:
output_workspaces = self._run_mirror_mode(monitor_ws, grouped_ws)
else:
logger.information('Mirror sense is OFF')
self._calculate_energy(monitor_ws, grouped_ws, self._red_workspace)
output_workspaces = [self._red_workspace]
return output_workspaces
def _run_mirror_mode(self, monitor_ws, grouped_ws):
"""
Runs energy reduction with mirror mode.
@param monitor_ws :: name of the monitor workspace
@param grouped_ws :: name of workspace with the detectors grouped
"""
logger.information('Mirror sense is ON')
x = mtd[grouped_ws].readX(0) # energy array
mid_point = int((len(x) - 1) / 2)
#left half
left_ws = self._run_name + '_left'
left_mon_ws = left_ws + '_left_mon'
CropWorkspace(InputWorkspace=grouped_ws,
OutputWorkspace=left_ws,
XMax=x[mid_point - 1])
CropWorkspace(InputWorkspace=monitor_ws,
OutputWorkspace=left_mon_ws,
XMax=x[mid_point - 1])
self._calculate_energy(left_mon_ws, left_ws, self._red_left_workspace)
xl = mtd[self._red_left_workspace].readX(0)
logger.information('Energy range, left : %f to %f' % (xl[0], xl[-1]))
#right half
right_ws = self._run_name + '_right'
right_mon_ws = right_ws + '_mon'
CropWorkspace(InputWorkspace=grouped_ws,
OutputWorkspace=right_ws,
Xmin=x[mid_point])
CropWorkspace(InputWorkspace=monitor_ws,
OutputWorkspace=right_mon_ws,
Xmin=x[mid_point])
self._calculate_energy(right_mon_ws, right_ws, self._red_right_workspace)
xr = mtd[self._red_right_workspace].readX(0)
logger.information('Energy range, right : %f to %f' % (xr[0], xr[-1]))
xl = mtd[self._red_left_workspace].readX(0)
yl = mtd[self._red_left_workspace].readY(0)
nlmax = np.argmax(np.array(yl))
xlmax = xl[nlmax]
xr = mtd[self._red_right_workspace].readX(0)
yr = mtd[self._red_right_workspace].readY(0)
nrmax = np.argmax(np.array(yr))
xrmax = xr[nrmax]
xshift = xlmax - xrmax
ScaleX(InputWorkspace=self._red_right_workspace,
OutputWorkspace=self._red_right_workspace,
Factor=xshift,
Operation='Add')
RebinToWorkspace(WorkspaceToRebin=self._red_right_workspace,
WorkspaceToMatch=self._red_left_workspace,
OutputWorkspace=self._red_right_workspace)
#sum both workspaces together
Plus(LHSWorkspace=self._red_left_workspace,
RHSWorkspace=self._red_right_workspace,
OutputWorkspace=self._red_workspace)
Scale(InputWorkspace=self._red_workspace,
OutputWorkspace=self._red_workspace,
Factor=0.5, Operation='Multiply')
DeleteWorkspace(monitor_ws)
DeleteWorkspace(grouped_ws)
return [self._red_left_workspace, self._red_right_workspace, self._red_workspace]
def _calculate_energy(self, monitor_ws, grouped_ws, red_ws):
"""
Convert the input run to energy transfer
@param monitor_ws :: name of the monitor workspace to divide by
@param grouped_ws :: name of workspace with the detectors grouped
@param red_ws :: name to call the reduced workspace
"""
x_range = self._monitor_range(monitor_ws)
Scale(InputWorkspace=monitor_ws,
OutputWorkspace=monitor_ws,
Factor=0.001,
Operation='Multiply')
CropWorkspace(InputWorkspace=monitor_ws,
OutputWorkspace=monitor_ws,
Xmin=x_range[0],
XMax=x_range[1])
ScaleX(InputWorkspace=monitor_ws,
OutputWorkspace=monitor_ws,
Factor=-x_range[0],
Operation='Add')
CropWorkspace(InputWorkspace=grouped_ws,
OutputWorkspace=grouped_ws,
Xmin=x_range[0],
XMax=x_range[1])
ScaleX(InputWorkspace=grouped_ws,
OutputWorkspace=grouped_ws,
Factor=-x_range[0],
Operation='Add')
# Apply the detector intensity calibration
if self._calibration_workspace != '':
Divide(LHSWorkspace=grouped_ws,
RHSWorkspace=self._calibration_workspace,
OutputWorkspace=grouped_ws)
Divide(LHSWorkspace=grouped_ws,
RHSWorkspace=monitor_ws,
OutputWorkspace=grouped_ws)
formula = self._energy_range(grouped_ws)
ConvertAxisByFormula(InputWorkspace=grouped_ws,
OutputWorkspace=red_ws,
Axis='X',
Formula=formula)
red_ws_p = mtd[red_ws]
red_ws_p.getAxis(0).setUnit('DeltaE')
xnew = red_ws_p.readX(0) # energy array
logger.information('Energy range : %f to %f' % (xnew[0], xnew[-1]))
DeleteWorkspace(grouped_ws)
DeleteWorkspace(monitor_ws)
def _monitor_range(self, monitor_ws):
"""
Get sensible values for the min and max cropping range
@param monitor_ws :: name of the monitor workspace
@return tuple containing the min and max x values in the range
"""
x = mtd[monitor_ws].readX(0) # energy array
y = mtd[monitor_ws].readY(0) # energy array
imin = np.argmax(np.array(y[0:20]))
nch = len(y)
im = np.argmax(np.array(y[nch - 21:nch - 1]))
imax = nch - 21 + im
logger.information('Cropping range %f to %f' % (x[imin], x[imax]))
return x[imin], x[imax]
def _energy_range(self, ws):
"""
Calculate the energy range for the workspace
@param ws :: name of the workspace
@return formula for convert axis by formula to convert to energy transfer
"""
x = mtd[ws].readX(0)
npt = len(x)
imid = float(npt / 2 + 1)
gRun = mtd[ws].getRun()
wave = gRun.getLogData('wavelength').value
logger.information('Wavelength : %s' % wave)
if gRun.hasProperty('Doppler.maximum_delta_energy'):
energy = gRun.getLogData('Doppler.maximum_delta_energy').value
logger.information('Doppler max energy : %s' % energy)
elif gRun.hasProperty('Doppler.doppler_speed'):
speed = gRun.getLogData('Doppler.doppler_speed').value
amp = gRun.getLogData('Doppler.doppler_amplitude').value
logger.information('Doppler speed : %s' % speed)
logger.information('Doppler amplitude : %s' % amp)
energy = 1.2992581918414711e-4 * speed * amp * 2.0 / wave # max energy
elif gRun.hasProperty('Doppler.doppler_freq'):
speed = gRun.getLogData('Doppler.doppler_freq').value
amp = gRun.getLogData('Doppler.doppler_amplitude').value
logger.information('Doppler freq : %s' % freq)
logger.information('Doppler amplitude : %s' % amp)
energy = 1.2992581918414711e-4 * freq * amp * 2.0 / wave # max energy
dele = 2.0 * energy / npt
formula = '(x-%f)*%f' % (imid, dele)
return formula
# Register algorithm with Mantid
AlgorithmFactory.subscribe(IndirectILLReduction)