-
Notifications
You must be signed in to change notification settings - Fork 122
/
ReflectometryILLConvertToQ.py
231 lines (202 loc) · 10.1 KB
/
ReflectometryILLConvertToQ.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
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from mantid.api import (AlgorithmFactory, DataProcessorAlgorithm, MatrixWorkspaceProperty, WorkspaceUnitValidator)
from mantid.kernel import (Direction, FloatBoundedValidator, Property, StringListValidator)
from mantid.simpleapi import (ConvertToPointData, CreateWorkspace, ReflectometryMomentumTransfer)
import numpy
import ReflectometryILL_common as common
class Prop:
CLEANUP = 'Cleanup'
DIRECT_WS = 'DirectBeamWorkspace'
GROUPING_FRACTION = 'GroupingQFraction'
INPUT_WS = 'InputWorkspace'
OUTPUT_WS = 'OutputWorkspace'
REFLECTED_WS = 'ReflectedBeamWorkspace'
POLARIZED = 'Polarized'
SUBALG_LOGGING = 'SubalgorithmLogging'
class SubalgLogging:
OFF = 'Logging OFF'
ON = 'Logging ON'
class ReflectometryILLConvertToQ(DataProcessorAlgorithm):
def category(self):
"""Return algorithm's categories."""
return 'ILL\\Reflectometry;Workflow\\Reflectometry'
def name(self):
"""Return the name of the algorithm."""
return 'ReflectometryILLConvertToQ'
def summary(self):
"""Return a summary of the algorithm."""
return 'Converts a reflectivity workspace from wavelength to momentum transfer.'
def seeAlso(self):
"""Return a list of related algorithm names."""
return ['ReflectometryILLPolarizationCor', 'ReflectometryILLPreprocess', 'ReflectometryILLSumForeground']
def version(self):
"""Return the version of the algorithm."""
return 1
def PyExec(self):
"""Execute the algorithm."""
self._subalgLogging = self.getProperty(Prop.SUBALG_LOGGING).value == SubalgLogging.ON
cleanupMode = self.getProperty(Prop.CLEANUP).value
self._cleanup = common.WSCleanup(cleanupMode, self._subalgLogging)
wsPrefix = self.getPropertyValue(Prop.OUTPUT_WS)
self._names = common.WSNameSource(wsPrefix, cleanupMode)
ws = self._inputWS()
ws = self._convertToMomentumTransfer(ws)
ws = self._toPointData(ws)
ws = self._groupPoints(ws)
self._finalize(ws)
def PyInit(self):
"""Initialize the input and output properties of the algorithm."""
positiveFloat = FloatBoundedValidator(lower=0., exclusive=True)
self.declareProperty(MatrixWorkspaceProperty(Prop.INPUT_WS,
defaultValue='',
direction=Direction.Input,
validator=WorkspaceUnitValidator('Wavelength')),
doc='A reflectivity workspace in wavelength to be converted to Q.')
self.declareProperty(MatrixWorkspaceProperty(Prop.OUTPUT_WS,
defaultValue='',
direction=Direction.Output),
doc='The input workspace in momentum transfer.')
self.declareProperty(Prop.SUBALG_LOGGING,
defaultValue=SubalgLogging.OFF,
validator=StringListValidator([SubalgLogging.OFF, SubalgLogging.ON]),
doc='Enable or disable child algorithm logging.')
self.declareProperty(Prop.CLEANUP,
defaultValue=common.WSCleanup.ON,
validator=StringListValidator([common.WSCleanup.ON, common.WSCleanup.OFF]),
doc='Enable or disable intermediate workspace cleanup.')
self.declareProperty(MatrixWorkspaceProperty(Prop.REFLECTED_WS,
defaultValue='',
direction=Direction.Input,
validator=WorkspaceUnitValidator('Wavelength')),
doc='A non-summed reflected beam workspace, needed for Q resolution calculation.')
self.declareProperty(MatrixWorkspaceProperty(Prop.DIRECT_WS,
defaultValue='',
direction=Direction.Input,
validator=WorkspaceUnitValidator('Wavelength')),
doc='A non-summed direct beam workspace, needed for Q resolution calculation.')
self.declareProperty(Prop.POLARIZED,
defaultValue=False,
doc='True if input workspace has been corrected for polarization efficiencies.')
self.declareProperty(Prop.GROUPING_FRACTION,
defaultValue=Property.EMPTY_DBL,
validator=positiveFloat,
doc='If set, group the output by steps of this fraction multiplied by Q resolution')
def _convertToMomentumTransfer(self, ws):
"""Convert the X units of ws to momentum transfer."""
reflectedWS = self.getProperty(Prop.REFLECTED_WS).value
reflectedForeground = self._foreground(reflectedWS.run())
directWS = self.getProperty(Prop.DIRECT_WS).value
directForeground = self._foreground(directWS.run())
logs = ws.run()
instrumentName = ws.getInstrument().getName()
if instrumentName != 'D17' and instrumentName != 'FIGARO':
raise RuntimeError('Unrecognized instrument {}. Only D17 and FIGARO are supported.'.format(instrumentName))
sumType = logs.getProperty(common.SampleLogs.SUM_TYPE).value
polarized = self.getProperty(Prop.POLARIZED).value
pixelSize = 0.001195 if instrumentName == 'D17' else 0.0012
detResolution = common.detectorResolution()
chopperSpeed = common.chopperSpeed(logs, instrumentName)
chopperOpening = common.chopperOpeningAngle(logs, instrumentName)
chopperRadius = 0.36 if instrumentName == 'D17' else 0.305
chopperPairDist = common.chopperPairDistance(logs, instrumentName)
slit1SizeLog = common.slitSizeLogEntry(instrumentName, 1)
slit2SizeLog = common.slitSizeLogEntry(instrumentName, 2)
tofBinWidth = self._TOFChannelWidth(logs, instrumentName)
qWSName = self._names.withSuffix('in_momentum_transfer')
qWS = ReflectometryMomentumTransfer(
InputWorkspace=ws,
OutputWorkspace=qWSName,
ReflectedBeamWorkspace=reflectedWS,
ReflectedForeground=reflectedForeground,
DirectBeamWorkspace=directWS,
DirectForeground=directForeground,
SummationType=sumType,
Polarized=polarized,
PixelSize=pixelSize,
DetectorResolution=detResolution,
ChopperSpeed=chopperSpeed,
ChopperOpening=chopperOpening,
ChopperRadius=chopperRadius,
ChopperPairDistance=chopperPairDist,
Slit1Name='slit2',
Slit1SizeSampleLog=slit1SizeLog,
Slit2Name='slit3',
Slit2SizeSampleLog=slit2SizeLog,
TOFChannelWidth=tofBinWidth,
EnableLogging=self._subalgLogging)
self._cleanup.cleanup(ws)
return qWS
def _finalize(self, ws):
"""Set OutputWorkspace to ws and clean up."""
self.setProperty(Prop.OUTPUT_WS, ws)
self._cleanup.cleanup(ws)
self._cleanup.finalCleanup()
def _foreground(self, sampleLogs):
"""Return a [start, end] list defining the foreground workspace indices."""
start = sampleLogs.getProperty(common.SampleLogs.FOREGROUND_START).value
end = sampleLogs.getProperty(common.SampleLogs.FOREGROUND_END).value
return [start, end]
def _groupPoints(self, ws):
"""Group bins by Q resolution."""
if self.getProperty(Prop.GROUPING_FRACTION).isDefault:
return ws
qFraction = self.getProperty(Prop.GROUPING_FRACTION).value
xs = ws.readX(0)
ys = ws.readY(0)
es = ws.readE(0)
dxs = ws.readDx(0)
if numpy.any(dxs <= 0.):
raise RuntimeError('Cannot proceed: the momentum transfer workspace contains nonpositive Q resolutions.')
index = 0
start = xs[index]
groupedXs = list()
groupedYs = list()
groupedEs = list()
groupedDxs = list()
while True:
width = qFraction * dxs[index]
end = xs[index] + width
pick = numpy.logical_and(xs >= start, xs < end)
pickedXs = xs[pick]
if len(pickedXs) > 0:
groupedXs.append(numpy.mean(pickedXs))
groupedYs.append(numpy.mean(ys[pick]))
groupedEs.append(numpy.mean(es[pick]))
groupWidth = pickedXs[-1] - pickedXs[0]
groupedDxs.append(numpy.sqrt(dxs[index]**2 + (0.68 * groupWidth)**2))
start = end
if start > xs[-1]:
break
index = numpy.nonzero(xs > start)[0][0]
groupedWSName = self._names.withSuffix('grouped')
groupedWS = CreateWorkspace(
OutputWorkspace=groupedWSName,
DataX=groupedXs,
DataY=groupedYs,
DataE=groupedEs,
UnitX=ws.getAxis(0).getUnit().unitID(),
ParentWorkspace=ws,
EnableLogging=self._subalgLogging)
groupedWS.setDx(0, groupedDxs)
self._cleanup.cleanup(ws)
return groupedWS
def _inputWS(self):
"Return the input workspace."
ws = self.getProperty(Prop.INPUT_WS).value
self._cleanup.protect(ws)
return ws
def _TOFChannelWidth(self, sampleLogs, instrumentName):
"""Return the time of flight bin width."""
return sampleLogs.getProperty('PSD.time_of_flight_0').value
def _toPointData(self, ws):
"""Convert ws from binned to point data."""
pointWSName = self._names.withSuffix('as_points')
pointWS = ConvertToPointData(
InputWorkspace=ws,
OutputWorkspace=pointWSName,
EnableLogging=self._subalgLogging)
pointWS.setDx(0, ws.readDx(0))
self._cleanup.cleanup(ws)
return pointWS
AlgorithmFactory.subscribe(ReflectometryILLConvertToQ)