-
Notifications
You must be signed in to change notification settings - Fork 122
/
SANSAbsoluteScale.py
234 lines (196 loc) · 10.6 KB
/
SANSAbsoluteScale.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
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
#pylint: disable=no-init,invalid-name
import os
from mantid.api import *
from mantid.kernel import *
from reduction_workflow.find_data import find_data
class SANSAbsoluteScale(PythonAlgorithm):
"""
Normalise detector counts by the sample thickness
"""
instrument = None
def category(self):
return "Workflow\\SANS\\UsesPropertyManager"
def name(self):
return "SANSAbsoluteScale"
def summary(self):
return "Calculate and apply absolute scale correction for SANS data"
def PyInit(self):
self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "",
direction=Direction.Input))
self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "",
direction = Direction.Output))
methods = [ "Value", "ReferenceData"]
self.declareProperty("Method", "Value",
StringListValidator(methods),
"Scaling method - either a simple scaling by value or using a reference data set")
self.declareProperty("ScalingFactor", 1.0, "Scaling factor to use with the Value method")
self.declareProperty(FileProperty("ReferenceDataFilename", "",
action=FileAction.OptionalLoad,
extensions=['xml', 'nxs', 'nxs.h5']),
"Reference data file to compute the scaling factor")
self.declareProperty("BeamstopDiameter", 0.0, "Diameter of the beam on the detector, in mm")
self.declareProperty("AttenuatorTransmission", 1.0,
"Attenuator transmission used in the measurement")
self.declareProperty("ApplySensitivity", False,
"If True, the sensitivity correction will be applied to the reference data set")
self.declareProperty("ReductionProperties", "__sans_reduction_properties",
validator=StringMandatoryValidator(),
doc="Property manager name for the reduction")
self.declareProperty("OutputMessage", "",
direction=Direction.Output, doc = "Output message")
def PyExec(self):
property_manager_name = self.getProperty("ReductionProperties").value
property_manager = PropertyManagerDataService.retrieve(property_manager_name)
# Get instrument to use with FileFinder
self.instrument = ''
if property_manager.existsProperty("InstrumentName"):
self.instrument = property_manager.getProperty("InstrumentName").value
method = self.getPropertyValue("Method")
if method=="Value":
input_ws = self.getProperty("InputWorkspace").value
output_ws_name = self.getPropertyValue("OutputWorkspace")
scaling_factor = self.getProperty("ScalingFactor").value
alg = AlgorithmManager.create("Scale")
alg.initialize()
alg.setChild(True)
alg.setProperty("InputWorkspace", input_ws)
alg.setProperty("OutputWorkspace", output_ws_name)
alg.setProperty("Factor", scaling_factor)
alg.setPropertyValue("Operation", "Multiply")
alg.execute()
output_ws = alg.getProperty("OutputWorkspace").value
self.setProperty("OutputWorkspace", output_ws)
self.setProperty("OutputMessage", "Applied scaling factor %g" % scaling_factor)
elif self.instrument.lower() in ['biosans', 'gpsans', 'hfirsans']:
self._hfir_scaling(property_manager)
else:
msg = "Absolute scale calculation with a reference is only available for HFIR"
Logger("SANSAbsoluteScale").error(msg)
self.setProperty("OutputMessage", msg)
return
#pylint: disable=too-many-locals,too-many-branches
def _hfir_scaling(self, property_manager):
property_manager_name = self.getProperty("ReductionProperties").value
input_ws = self.getProperty("InputWorkspace").value
output_ws_name = self.getPropertyValue("OutputWorkspace")
output_msg = ""
# Load data file
data_file = self.getProperty("ReferenceDataFilename").value
filepath = find_data(data_file, instrument=self.instrument)
ref_basename = os.path.basename(filepath)
ref_ws_name = "__abs_scale_%s" % ref_basename
def _load_data(filename, output_ws):
if not property_manager.existsProperty("LoadAlgorithm"):
Logger("SANSDirectBeamTransmission").error("SANS reduction not set up properly: missing load algorithm")
raise RuntimeError("SANS reduction not set up properly: missing load algorithm")
p=property_manager.getProperty("LoadAlgorithm")
alg=Algorithm.fromString(p.valueAsStr)
alg.setChild(True)
alg.setProperty("Filename", filename)
alg.setProperty("OutputWorkspace", output_ws)
if alg.existsProperty("ReductionProperties"):
alg.setProperty("ReductionProperties", property_manager_name)
alg.execute()
msg = ''
if alg.existsProperty("OutputMessage"):
msg = alg.getProperty("OutputMessage").value
ws = alg.getProperty("OutputWorkspace").value
return ws, msg
ref_ws, msg = _load_data(filepath, ref_ws_name)
output_msg += msg+'\n'
# Get monitor value:
# This call is left unprotected because it should fail if that property
# doesn't exist. It's the responsibility of the parent algorithm to
# catch that error.
monitor_prop = property_manager.getProperty("NormaliseAlgorithm")
alg=Algorithm.fromString(monitor_prop.valueAsStr)
monitor_id = alg.getPropertyValue("NormalisationType").lower()
monitor_value = ref_ws.getRun().getProperty(monitor_id.lower()).value
# HFIR-specific: If we count for monitor we need to multiply by 1e8
# Need to be consistent with the Normalization step
if monitor_id == "monitor":
monitor_value /= 1.0e8
# Get sample-detector distance
sdd = ref_ws.getRun().getProperty("sample_detector_distance").value
# Get the beamstop diameter
beam_diameter = self.getProperty("BeamstopDiameter").value
if beam_diameter <= 0:
if ref_ws.getRun().hasProperty("beam-diameter"):
beam_diameter = ref_ws.getRun().getProperty("beam-diameter").value
Logger("SANSAbsoluteScale").debug("Found beamstop diameter: %g" % beam_diameter)
else:
raise RuntimeError("AbsoluteScale could not read the beam radius and none was provided")
# Apply sensitivity correction
apply_sensitivity = self.getProperty("ApplySensitivity").value
if apply_sensitivity and property_manager.existsProperty("SensitivityAlgorithm"):
p=property_manager.getProperty("SensitivityAlgorithm")
alg=Algorithm.fromString(p.valueAsStr)
alg.setChild(True)
alg.setProperty("InputWorkspace", ref_ws)
alg.setProperty("OutputWorkspace", ref_ws)
if alg.existsProperty("ReductionProperties"):
alg.setProperty("ReductionProperties", property_manager_name)
alg.execute()
if alg.existsProperty("OutputMessage"):
output_msg += alg.getProperty("OutputMessage").value+'\n'
# Get the reference count
Logger("SANSAbsoluteScale").information("Using beamstop diameter: %g" % beam_diameter)
det_count = 1
cylXML = '<infinite-cylinder id="asbsolute_scale">' + \
'<centre x="0.0" y="0.0" z="0.0" />' + \
'<axis x="0.0" y="0.0" z="1.0" />' + \
'<radius val="%12.10f" />' % (beam_diameter/2000.0) + \
'</infinite-cylinder>\n'
alg = AlgorithmManager.create("FindDetectorsInShape")
alg.initialize()
alg.setChild(True)
alg.setProperty("Workspace", ref_ws)
alg.setPropertyValue("ShapeXML", cylXML)
alg.execute()
#det_list = alg.getProperty("DetectorList").value
det_list_str = alg.getPropertyValue("DetectorList")
det_count_ws_name = "__absolute_scale"
alg = AlgorithmManager.create("GroupDetectors")
alg.initialize()
alg.setChild(True)
alg.setProperty("InputWorkspace", ref_ws)
alg.setProperty("OutputWorkspace", det_count_ws_name)
alg.setPropertyValue("KeepUngroupedSpectra", "0")
alg.setPropertyValue("DetectorList", det_list_str)
alg.execute()
det_count_ws = alg.getProperty("OutputWorkspace").value
det_count = det_count_ws.readY(0)[0]
Logger("SANSAbsoluteScale").information("Reference detector counts: %g" % det_count)
if det_count <= 0:
Logger("SANSAbsoluteScale").error("Bad reference detector count: check your beam parameters")
# Pixel size, in mm
pixel_size_param = ref_ws.getInstrument().getNumberParameter("x-pixel-size")
if pixel_size_param is not None:
pixel_size = pixel_size_param[0]
else:
raise RuntimeError("AbsoluteScale could not read the pixel size")
attenuator_trans = self.getProperty("AttenuatorTransmission").value
# (detector count rate)/(attenuator transmission)/(monitor rate)*(pixel size/SDD)**2
scaling_factor = 1.0/(det_count/attenuator_trans/(monitor_value)*(pixel_size/sdd)*(pixel_size/sdd))
# Apply the scaling factor
alg = AlgorithmManager.create("Scale")
alg.initialize()
alg.setChild(True)
alg.setProperty("InputWorkspace", input_ws)
alg.setProperty("OutputWorkspace", output_ws_name)
alg.setProperty("Factor", scaling_factor)
alg.setPropertyValue("Operation", "Multiply")
alg.execute()
output_ws = alg.getProperty("OutputWorkspace").value
Logger("SANSAbsoluteScale").notice( "Applied scaling factor %15.15f" % scaling_factor)
output_msg = output_msg.replace('\n','\n |')
output_msg = "Applied scaling factor %g\n%s" % (scaling_factor, output_msg)
self.setProperty("OutputWorkspace", output_ws)
self.setProperty("OutputMessage", output_msg)
AlgorithmFactory.subscribe(SANSAbsoluteScale())