-
Notifications
You must be signed in to change notification settings - Fork 122
/
TimeSlice.py
277 lines (193 loc) · 9.33 KB
/
TimeSlice.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
from mantid.kernel import *
from mantid.api import *
from mantid.simpleapi import *
import os
def _count_monitors(raw_file):
"""
Returns the number of monitors and if they're at the start or end of the file
"""
raw_file = mtd[raw_file]
num_hist = raw_file.getNumberHistograms()
detector = raw_file.getDetector(0)
mon_count = 1
if detector.isMonitor():
# Monitors are at the start
for i in range(1, num_hist):
detector = raw_file.getDetector(i)
if detector.isMonitor():
mon_count += 1
else:
break
return mon_count, True
else:
# Monitors are at the end
detector = raw_file.getDetector(num_hist)
if not detector.isMonitor():
#if it's not, we don't have any monitors!
return 0, True
for i in range(num_hist, 0, -1):
detector = raw_file.getDetector(i)
if detector.isMonitor():
mon_count += 1
else:
break
return mon_count, False
class TimeSlice(PythonAlgorithm):
def category(self):
return 'PythonAlgorithms;Inelastic'
def summary(self):
return 'Performa an integration on a raw file over a specified time of flight range'
def PyInit(self):
self.declareProperty(StringArrayProperty(name='InputFiles'),
doc='Comma separated list of input files')
self.declareProperty(WorkspaceProperty(name='CalibrationWorkspace', defaultValue='',
direction=Direction.Input, optional=PropertyMode.Optional),
doc='Calibration workspace')
self.declareProperty(IntArrayProperty(name='SpectraRange'),
doc='Range of spectra to use')
self.declareProperty(FloatArrayProperty(name='PeakRange'),
doc='Peak range in time of flight')
self.declareProperty(FloatArrayProperty(name='BackgroundRange'),
doc='Background range in time of flight')
self.declareProperty(name='Verbose', defaultValue=False,
doc='Output more messages to results log')
self.declareProperty(name='Plot', defaultValue=False,
doc='Plot result workspaces')
self.declareProperty(name='Save', defaultValue=False,
doc='Save result workspaces as nexus files to default save directory')
self.declareProperty(name='OutputNameSuffix', defaultValue='_slice',
doc='Suffix to append to raw file name for name of output workspace')
self.declareProperty(WorkspaceGroupProperty(name='OutputWorkspaceGroup', defaultValue='',
optional=PropertyMode.Optional, direction=Direction.Output),
doc='Name of workspace group to group result workspaces into')
def _validate_range(self, name):
"""
Validates a range property
@param name Name of the property
"""
range_prop = self.getProperty(name).value
if len(range_prop) != 2:
return 'Range must have two values'
if range_prop[0] > range_prop[1]:
return 'Range must be in format "low,high"'
return ''
def validateInput(self):
issues = dict()
issues['SpectraRange'] = self._validate_range('SpectraRange')
issues['PeakRange'] = self._validate_range('PeakRange')
if self.getPropertyValue('BackgroundRange') != '':
issues['BackgroundRange'] = self._validate_range('BackgroundRange')
return issues
def PyExec(self):
from IndirectCommon import CheckXrange
self._setup()
# CheckXrange(xRange, 'Time')
out_ws_list = []
for index, filename in enumerate(self._raw_files):
raw_file = self._read_raw_file(filename)
# Only need to process the calib file once
if index == 0 and self._calib_ws is not None:
self._process_calib(raw_file)
slice_file = self._process_raw_file(raw_file)
Transpose(InputWorkspace=slice_file, OutputWorkspace=slice_file)
unit = mtd[slice_file].getAxis(0).setUnit("Label")
unit.setLabel("Spectrum Number", "")
out_ws_list.append(slice_file)
DeleteWorkspace(raw_file)
if self._save:
work_dir = config['defaultsave.directory']
save_path = os.path.join(work_dir, slice_file + '.nxs')
SaveNexusProcessed(InputWorkspace=slice_file, Filename=save_path)
if self._verbose:
logger.notice('Output file :' + save_path)
if self._out_ws_group is not None:
all_workspaces = ','.join(out_ws_list)
GroupWorkspaces(InputWorkspaces=all_workspaces, OutputWorkspace=self._out_ws_group)
if self._plot:
try:
from IndirectImport import import_mantidplot
mp = import_mantidplot()
mp.plotSpectrum(slice_file, 0)
except RuntimeError, e:
# User clicked cancel on plot so don't do anything
pass
def _setup(self):
"""
Gets properties.
"""
self._raw_files = self.getProperty('InputFiles').value
self._spectra_range = self.getProperty('SpectraRange').value
self._peak_range = self.getProperty('PeakRange').value
self._output_ws_name_suffix = self.getPropertyValue('OutputNameSuffix')
self._background_range = self.getProperty('BackgroundRange').value
if len(self._background_range) == 0:
self._background_range = None
self._calib_ws = self.getPropertyValue('CalibrationWorkspace')
if self._calib_ws == '':
self._calib_ws = None
self._out_ws_group = self.getPropertyValue('OutputWorkspaceGroup')
if self._out_ws_group == '':
self._out_ws_group = None
self._verbose = self.getProperty('Verbose').value
self._plot = self.getProperty('Plot').value
self._save = self.getProperty('Save').value
def _read_raw_file(self, filename):
"""
Loads a raw run file.
@param filename Data file name
@returns Name of workspace loaded into
"""
if self._verbose:
logger.notice('Reading file :' + filename)
# Load the raw file
f_name = os.path.split(filename)[1]
workspace_name = os.path.splitext(f_name)[0]
Load(Filename=filename, OutputWorkspace=workspace_name, LoadLogFiles=False)
return workspace_name
def _process_calib(self, raw_file):
"""
Run the calibration file with the raw file workspace.
@param raw_file Name of calibration file
"""
calib_spec_min, calib_spec_max = self._spectra_range
if calib_spec_max - calib_spec_min > mtd[self._calib_ws].getNumberHistograms():
raise IndexError('Number of spectra used is greater than the number of spectra in the calibration file.')
# Offset cropping range to account for monitors
(mon_count, at_start) = _count_monitors(raw_file)
if at_start:
calib_spec_min -= mon_count + 1
calib_spec_max -= mon_count + 1
# Crop the calibration workspace, excluding the monitors
CropWorkspace(InputWorkspace=self._calib_ws, OutputWorkspace=self._calib_ws,
StartWorkspaceIndex=calib_spec_min, EndWorkspaceIndex=calib_spec_max)
def _process_raw_file(self, raw_file):
"""
Process a raw sample file.
@param raw_file Name of file to process
"""
from IndirectCommon import CheckHistZero
# Crop the raw file to use the desired number of spectra
# less one because CropWorkspace is zero based
CropWorkspace(InputWorkspace=raw_file, OutputWorkspace=raw_file,
StartWorkspaceIndex=self._spectra_range[0] - 1,
EndWorkspaceIndex=self._spectra_range[1] - 1)
num_hist = CheckHistZero(raw_file)[0]
# Use calibration file if desired
if self._calib_ws is not None:
Divide(LHSWorkspace=raw_file, RHSWorkspace=self._calib_ws, OutputWorkspace=raw_file)
# Construct output workspace name
run = mtd[raw_file].getRun().getLogData('run_number').value
slice_file = raw_file[:3].lower() + run + self._output_ws_name_suffix
if self._background_range is None:
Integration(InputWorkspace=raw_file, OutputWorkspace=slice_file,
RangeLower=self._peak_range[0], RangeUpper=self._peak_range[1],
StartWorkspaceIndex=0, EndWorkspaceIndex=num_hist - 1)
else:
CalculateFlatBackground(InputWorkspace=raw_file, OutputWorkspace=slice_file,
StartX=self._background_range[0], EndX=self._background_range[1],
Mode='Mean')
Integration(InputWorkspace=slice_file, OutputWorkspace=slice_file,
RangeLower=self._peak_range[0], RangeUpper=self._peak_range[1],
StartWorkspaceIndex=0, EndWorkspaceIndex=num_hist - 1)
return slice_file
AlgorithmFactory.subscribe(TimeSlice)