forked from AmbaPant/mantid
-
Notifications
You must be signed in to change notification settings - Fork 1
/
CalculateEfficiencyCorrection.py
258 lines (213 loc) · 11.8 KB
/
CalculateEfficiencyCorrection.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
# 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 +
import numpy as np
from mantid.simpleapi import \
CloneWorkspace, ConvertFromDistribution, ConvertToPointData, \
ConvertUnits, CreateWorkspace, Rebin, SetSampleMaterial
from mantid.api import \
AlgorithmFactory, CommonBinsValidator, PropertyMode, PythonAlgorithm, \
MatrixWorkspaceProperty
from mantid.kernel import \
Direction, FloatBoundedValidator, \
StringListValidator, StringMandatoryValidator
TABULATED_WAVELENGTH = 1.7982
class CalculateEfficiencyCorrection(PythonAlgorithm):
_input_ws = None
_output_ws = None
def category(self):
return 'CorrectionFunctions\\EfficiencyCorrections'
def name(self):
return 'CalculateEfficiencyCorrection'
def summary(self):
return 'Calculate an efficiency correction using various inputs. Can be used to determine \
an incident spectrum after correcting a measured spectrum from beam monitors \
or vanadium measurements.'
def seeAlso(self):
return ["He3TubeEfficiency", "CalculateSampleTransmission",
"DetectorEfficiencyCor", "DetectorEfficiencyCorUser",
"CalculateEfficiency", "ComputeCalibrationCoefVan"]
def PyInit(self):
self.declareProperty(
MatrixWorkspaceProperty('InputWorkspace', '',
direction=Direction.Input,
optional=PropertyMode.Optional,
validator=CommonBinsValidator()),
doc='Input workspace with wavelength range to calculate for the correction.')
self.declareProperty(name='WavelengthRange', defaultValue='',
doc='Wavelength range to calculate efficiency for.')
self.declareProperty(
MatrixWorkspaceProperty('OutputWorkspace', '',
direction=Direction.Output),
doc="Output workspace for the efficiency correction. \
This can be applied by multiplying the OutputWorkspace \
to the workspace that requires the correction.")
self.declareProperty(
name='ChemicalFormula', defaultValue='None',
validator=StringMandatoryValidator(),
doc='Sample chemical formula used to determine cross-section term.')
self.declareProperty(
name='DensityType', defaultValue='Mass Density',
validator=StringListValidator(['Mass Density', 'Number Density']),
doc='Use of Mass density (g/cm^3) or Number density (atoms/Angstrom^3)')
self.declareProperty(
name='Density',
defaultValue=0.0,
validator=FloatBoundedValidator(0.0),
doc='Mass density (g/cm^3) or Number density (atoms/Angstrom^3).')
self.declareProperty(
name='Thickness',
defaultValue=1.0,
validator=FloatBoundedValidator(0.0),
doc='Sample thickness (cm).')
self.declareProperty(
name='MeasuredEfficiency',
defaultValue=0.0,
validator=FloatBoundedValidator(0.0, 1.0),
doc="Directly input the efficiency measured at MeasuredEfficiencyWavelength. \
This is used to determine a Density*Thickness term.")
self.declareProperty(
name='MeasuredEfficiencyWavelength',
defaultValue=1.7982,
validator=FloatBoundedValidator(0.0),
doc="The wavelength at which the MeasuredEfficiency was measured.")
self.declareProperty(
name='Alpha', defaultValue=0.0,
doc="Directly input the alpha term in exponential to multiply by the wavelength. \
XSectionType has no effect if this is used.")
self.declareProperty(
name='XSectionType',
defaultValue="AttenuationXSection",
validator=StringListValidator(['AttenuationXSection', 'TotalXSection']),
doc='Use either the absorption or total cross section in exponential term. \
The absorption cross section is for monitor-type corrections and \
the total cross section is for transmission-type corrections')
def validateInputs(self):
issues = dict()
# Check the inputs for wavelength
isInWSDefault = self.getProperty('InputWorkspace').isDefault
isWlRangeDefault = self.getProperty('WavelengthRange').isDefault
if isInWSDefault and isWlRangeDefault:
issues['InputWorkspace'] = "Must select either InputWorkspace and WavelengthRange as input"
issues['WavelengthRange'] = "Must select either InputWorkspace and WavelengthRange as input"
if isInWSDefault and isWlRangeDefault:
issues['InputWorkspace'] = "Cannot select both InputWorkspace and WavelengthRange as input"
issues['WavelengthRange'] = "Cannot select both InputWorkspace and WavelengthRange as input"
# Check the different inputs for the exponential term
isDensityDefault = self.getProperty('Density').isDefault
isFormulaDefault = self.getProperty('ChemicalFormula').isDefault
isEffDefault = self.getProperty('MeasuredEfficiency').isDefault
isAlphaDefault = self.getProperty('Alpha').isDefault
if not isDensityDefault:
if isFormulaDefault:
issues['ChemicalFormula'] = "Must specify the ChemicalFormula with Density"
if not isEffDefault:
if isFormulaDefault:
issues['ChemicalFormula'] = "Must specify the ChemicalFormula with MeasuredEfficiency"
if not isEffDefault and not isDensityDefault:
issues['MeasuredEfficiency'] = "Cannot select both MeasuredEfficiency and Density as input"
issues['Density'] = "Cannot select both MeasuredEfficiency and Density as input"
if not isAlphaDefault and not isDensityDefault:
issues['Alpha'] = "Cannot select both Alpha and Density as input"
issues['Density'] = "Cannot select both Alpha and Density as input"
if not isEffDefault and not isAlphaDefault:
issues['MeasuredEfficiency'] = "Cannot select both MeasuredEfficiency and Alpha as input"
issues['Alpha'] = "Cannot select both MeasuredEfficiency and Alpha as input"
return issues
def _setup(self):
self._input_ws = self.getProperty('InputWorkspace').value
self._bin_params = self.getPropertyValue('WavelengthRange')
self._output_ws = self.getProperty('OutputWorkspace').valueAsStr
self._chemical_formula = self.getPropertyValue('ChemicalFormula')
self._density_type = self.getPropertyValue('DensityType')
self._density = self.getProperty('Density').value
self._thickness = self.getProperty('Thickness').value
self._efficiency = self.getProperty('MeasuredEfficiency').value
self._efficiency_wavelength = self.getProperty('MeasuredEfficiencyWavelength').value
self._alpha_absXS = self.getProperty('Alpha').value
self._alpha_scatXS = 0.0
self._xsection_type = self.getProperty('XSectionType').value
def PyExec(self):
self._setup()
if not self.getProperty("InputWorkspace").isDefault:
self._output_ws = CloneWorkspace(Inputworkspace=self._input_ws,
OutputWorkspace=self._output_ws,
StoreInADS=False)
else:
self._output_ws = CreateWorkspace(NSpec=1, DataX=[0], DataY=[0],
UnitX='Wavelength', Distribution=False,
StoreInADS=False)
self._output_ws = Rebin(InputWorkspace=self._output_ws,
Params=self._bin_params,
StoreInADS=False)
if self._output_ws.isDistribution():
ConvertFromDistribution(Workspace=self._output_ws,
StoreInADS=False)
self._output_ws = ConvertToPointData(InputWorkspace=self._output_ws,
StoreInADS=False)
self._output_ws = ConvertUnits(InputWorkspace=self._output_ws,
Target='Wavelength',
EMode='Elastic',
StoreInADS=False)
if self.getProperty('Alpha').isDefault:
if self._density_type == 'Mass Density':
SetSampleMaterial(
InputWorkspace=self._output_ws,
ChemicalFormula=self._chemical_formula,
SampleMassDensity=self._density,
StoreInADS=False)
self._density = self._output_ws.sample().getMaterial().numberDensityEffective
elif self._density_type == 'Number Density':
SetSampleMaterial(
InputWorkspace=self._output_ws,
ChemicalFormula=self._chemical_formula,
SampleNumberDensity=self._density,
StoreInADS=False)
else:
raise RuntimeError(f'Unknown "DensityType": {self._density_type}')
if self.getProperty('MeasuredEfficiency').isDefault:
self._calculate_area_density_from_density()
else:
self._calculate_area_density_from_efficiency()
self._calculate_alpha_absXS_term()
if self._xsection_type == "TotalXSection":
self._calculate_alpha_scatXS_term()
wavelengths = self._output_ws.readX(0)
efficiency = self._calculate_efficiency(wavelengths)
for histo in range(self._output_ws.getNumberHistograms()):
self._output_ws.setY(histo, efficiency)
self.setProperty('OutputWorkspace', self._output_ws)
def _calculate_area_density_from_efficiency(self):
"""Calculates area density (atom/cm^2) using efficiency"""
material = self._output_ws.sample().getMaterial()
ref_absXS = material.absorbXSection()
xs_term = ref_absXS * self._efficiency_wavelength / TABULATED_WAVELENGTH
if self._xsection_type == "TotalXSection":
xs_term += material.totalScatterXSection()
self._area_density = - np.log(1.0 - self._efficiency) / xs_term
def _calculate_area_density_from_density(self):
"""Calculates area density (atom/cm^2) using number density and thickness."""
self._area_density = self._density * self._thickness
def _calculate_alpha_absXS_term(self):
"""Calculates absorption XS alpha term = area_density * absXS / 1.7982"""
material = self._output_ws.sample().getMaterial()
absXS = material.absorbXSection() / TABULATED_WAVELENGTH
self._alpha_absXS = self._area_density * absXS
def _calculate_alpha_scatXS_term(self):
"""Calculates scattering XS alpha term = area_density * scatXS"""
material = self._output_ws.sample().getMaterial()
scatXS = material.totalScatterXSection()
self._alpha_scatXS = self._area_density * scatXS
def _calculate_efficiency(self, wavelength):
"""
Calculates efficiency of a detector / monitor at a given wavelength.
If using just the absorption cross section, _alpha_scatXS is == 0.
@param wavelength Wavelength at which to calculate (in Angstroms)
@return efficiency
"""
efficiency = 1. / (1.0 - np.exp(-(self._alpha_scatXS + self._alpha_absXS * wavelength)))
return efficiency
AlgorithmFactory.subscribe(CalculateEfficiencyCorrection)