Mantid
Loading...
Searching...
No Matches
EQSANSDarkCurrentSubtraction2.cpp
Go to the documentation of this file.
1// Mantid Repository : https://github.com/mantidproject/mantid
2//
3// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
4// NScD Oak Ridge National Laboratory, European Spallation Source,
5// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6// SPDX - License - Identifier: GPL - 3.0 +
11#include "MantidAPI/Run.h"
19
20#include "Poco/String.h"
21
22#include <filesystem>
23
25
26// Register the algorithm into the AlgorithmFactory
27DECLARE_ALGORITHM(EQSANSDarkCurrentSubtraction2)
28
29using namespace Kernel;
30using namespace API;
31using namespace Geometry;
32using namespace DataObjects;
33
35 auto wsValidator = std::make_shared<WorkspaceUnitValidator>("Wavelength");
36 declareProperty(std::make_unique<WorkspaceProperty<>>("InputWorkspace", "", Direction::Input, wsValidator));
37
38 declareProperty(std::make_unique<API::FileProperty>("Filename", "", API::FileProperty::Load, "_event.nxs"),
39 "The name of the input event Nexus file to load as dark current.");
40
41 declareProperty(std::make_unique<WorkspaceProperty<>>("OutputWorkspace", "", Direction::Output));
42 declareProperty("PersistentCorrection", true,
43 "If true, the algorithm will be persistent and re-used when "
44 "other data sets are processed");
45 declareProperty("ReductionProperties", "__sans_reduction_properties", Direction::Input);
46 declareProperty(std::make_unique<WorkspaceProperty<MatrixWorkspace>>("OutputDarkCurrentWorkspace", "",
48 declareProperty("OutputMessage", "", Direction::Output);
49}
50
52 std::string output_message;
53 // Reduction property manager
54 const std::string reductionManagerName = getProperty("ReductionProperties");
55 std::shared_ptr<PropertyManager> reductionManager;
56 if (PropertyManagerDataService::Instance().doesExist(reductionManagerName)) {
57 reductionManager = PropertyManagerDataService::Instance().retrieve(reductionManagerName);
58 } else {
59 reductionManager = std::make_shared<PropertyManager>();
60 PropertyManagerDataService::Instance().addOrReplace(reductionManagerName, reductionManager);
61 }
62
63 // If the load algorithm isn't in the reduction properties, add it
64 const bool persistent = getProperty("PersistentCorrection");
65 if (!reductionManager->existsProperty("DarkCurrentAlgorithm") && persistent) {
66 auto algProp = std::make_unique<AlgorithmProperty>("DarkCurrentAlgorithm");
67 algProp->setValue(toString());
68 reductionManager->declareProperty(std::move(algProp));
69 }
70
71 Progress progress(this, 0.0, 1.0, 10);
72
73 MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
74
75 // This version of dark current subtraction only works on histograms.
76 // Users need to either make sure the EQSANSLoad algorithm produces
77 // histograms, or turn off the dark current subtraction.
78 EventWorkspace_const_sptr inputEventWS = std::dynamic_pointer_cast<const EventWorkspace>(inputWS);
79 if (inputEventWS) {
80 g_log.error() << "To use this version of EQSANSDarkCurrentSubtraction, "
81 << "you need to make sure EQSANSLoad produces histograms. "
82 << "You can also turn the dark current subtraction off.\n";
83 throw std::invalid_argument("EQSANSDarkCurrentSubtraction-v2 only works on histograms.");
84 }
85
86 const std::string fileName = getPropertyValue("Filename");
88
89 progress.report("Subtracting dark current");
90
91 // Look for an entry for the dark current in the reduction table
92 std::filesystem::path path(fileName);
93 const std::string entryName = "DarkCurrent" + path.stem().string();
94 std::string darkWSName = "__dark_current_" + path.stem().string();
95
96 if (reductionManager->existsProperty(entryName)) {
97 darkWS = reductionManager->getProperty(entryName);
98 darkWSName = reductionManager->getPropertyValue(entryName);
99 output_message += darkWSName + '\n';
100 } else {
101 // Load the dark current if we don't have it already
102 IAlgorithm_sptr loadAlg;
103 if (!reductionManager->existsProperty("LoadAlgorithm")) {
104 loadAlg = createChildAlgorithm("EQSANSLoad", 0.1, 0.3);
105 loadAlg->setProperty("Filename", fileName);
106 if (loadAlg->existsProperty("LoadMonitors"))
107 loadAlg->setProperty("LoadMonitors", false);
108 loadAlg->executeAsChildAlg();
109 darkWS = loadAlg->getProperty("OutputWorkspace");
110 } else {
111 // Get load algorithm as a string so that we can create a completely
112 // new proxy and ensure that we don't overwrite existing properties
113 IAlgorithm_sptr loadAlg0 = reductionManager->getProperty("LoadAlgorithm");
114 const std::string loadString = loadAlg0->toString();
115 loadAlg = Algorithm::fromString(loadString);
116 loadAlg->setChild(true);
117 loadAlg->setProperty("Filename", fileName);
118 if (loadAlg->existsProperty("LoadMonitors"))
119 loadAlg->setProperty("LoadMonitors", false);
120 loadAlg->setPropertyValue("OutputWorkspace", darkWSName);
121 loadAlg->execute();
122 darkWS = loadAlg->getProperty("OutputWorkspace");
123 }
124
125 output_message += "\n Loaded " + fileName + "\n";
126 if (loadAlg->existsProperty("OutputMessage")) {
127 std::string msg = loadAlg->getPropertyValue("OutputMessage");
128 output_message += " |" + Poco::replace(msg, "\n", "\n |") + "\n";
129 }
130
131 std::string darkWSOutputName = getPropertyValue("OutputDarkCurrentWorkspace");
132 if (!darkWSOutputName.empty())
133 setProperty("OutputDarkCurrentWorkspace", darkWS);
134 AnalysisDataService::Instance().addOrReplace(darkWSName, darkWS);
135 reductionManager->declareProperty(std::make_unique<WorkspaceProperty<>>(entryName, "", Direction::Output));
136 reductionManager->setPropertyValue(entryName, darkWSName);
137 reductionManager->setProperty(entryName, darkWS);
138 }
139 progress.report(3, "Loaded dark current");
140
141 // Normalize the dark current and data to counting time
142 double scaling_factor = 1.0;
143 if (inputWS->run().hasProperty("duration")) {
144 auto duration = inputWS->run().getPropertyValueAsType<double>("duration");
145 auto dark_duration = darkWS->run().getPropertyValueAsType<double>("duration");
146 ;
147 scaling_factor = duration / dark_duration;
148 } else if (inputWS->run().hasProperty("proton_charge")) {
149 auto dp = inputWS->run().getTimeSeriesProperty<double>("proton_charge");
150 double duration = dp->getStatistics().duration;
151
152 dp = darkWS->run().getTimeSeriesProperty<double>("proton_charge");
153 double dark_duration = dp->getStatistics().duration;
154 scaling_factor = duration / dark_duration;
155 } else if (inputWS->run().hasProperty("timer")) {
156 auto duration = inputWS->run().getPropertyValueAsType<double>("timer");
157 auto dark_duration = darkWS->run().getPropertyValueAsType<double>("timer");
158 ;
159 scaling_factor = duration / dark_duration;
160 } else {
161 output_message += "\n Could not find proton charge or duration in sample logs";
162 g_log.error() << "ERROR: Could not find proton charge or duration in sample logs\n";
163 };
164 // The scaling factor should account for the TOF cuts on each side of a frame
165 // The EQSANSLoad algorithm cuts the beginning and end of the TOF distribution
166 // so we don't need to correct the scaling factor here. When using
167 // LoadEventNexus
168 // we have to scale by (t_frame-t_low_cut-t_high_cut)/t_frame.
169
170 progress.report("Scaling dark current");
171
172 // Get the dark current counts per pixel
173 auto rebinAlg = createChildAlgorithm("Integration", 0.4, 0.5);
174 rebinAlg->setProperty("InputWorkspace", darkWS);
175 rebinAlg->setProperty("OutputWorkspace", darkWS);
176 rebinAlg->executeAsChildAlg();
177 MatrixWorkspace_sptr scaledDarkWS = rebinAlg->getProperty("OutputWorkspace");
178
179 // Scale the dark current
180 auto scaleAlg = createChildAlgorithm("Scale", 0.5, 0.6);
181 scaleAlg->setProperty("InputWorkspace", scaledDarkWS);
182 scaleAlg->setProperty("Factor", scaling_factor);
183 scaleAlg->setProperty("OutputWorkspace", scaledDarkWS);
184 scaleAlg->setProperty("Operation", "Multiply");
185 scaleAlg->executeAsChildAlg();
186 scaledDarkWS = rebinAlg->getProperty("OutputWorkspace");
187
188 // Scale the dark counts to the bin width and perform subtraction
189 const auto numberOfSpectra = static_cast<int>(inputWS->getNumberHistograms());
190 const auto numberOfDarkSpectra = static_cast<int>(scaledDarkWS->getNumberHistograms());
191 if (numberOfSpectra != numberOfDarkSpectra) {
192 g_log.error() << "Incompatible number of pixels between sample run and "
193 "dark current\n";
194 }
195 const auto nBins = static_cast<int>(inputWS->readY(0).size());
196 const auto xLength = static_cast<int>(inputWS->readX(0).size());
197 if (xLength != nBins + 1) {
198 g_log.error() << "The input workspaces are expected to be histograms\n";
199 }
200
201 progress.report("Subtracting dark current");
202 const auto &spectrumInfo = inputWS->spectrumInfo();
203 // Loop over all tubes and patch as necessary
204 for (int i = 0; i < numberOfSpectra; i++) {
205 // If this detector is a monitor, skip to the next one
206 if (spectrumInfo.isMasked(i))
207 continue;
208
209 const MantidVec &YDarkValues = scaledDarkWS->readY(i);
210 const MantidVec &YDarkErrors = scaledDarkWS->readE(i);
211 const MantidVec &XValues = inputWS->readX(i);
212 MantidVec &YValues = inputWS->dataY(i);
213 MantidVec &YErrors = inputWS->dataE(i);
214 for (int j = 0; j < nBins; j++) {
215 double bin_scale = (XValues[j + 1] - XValues[j]) / (XValues[nBins] - XValues[0]);
216 YValues[j] -= YDarkValues[0] * bin_scale;
217 YErrors[j] = sqrt(YErrors[j] * YErrors[j] + YDarkErrors[0] * YDarkErrors[0] * bin_scale * bin_scale);
218 }
219 }
220 setProperty("OutputWorkspace", inputWS);
221 setProperty("OutputMessage", "Dark current subtracted: " + output_message);
222
223 progress.report("Subtracted dark current");
224}
225
226} // namespace Mantid::WorkflowAlgorithms
#define DECLARE_ALGORITHM(classname)
Definition Algorithm.h:538
void declareProperty(std::unique_ptr< Kernel::Property > p, const std::string &doc="") override
Add a property to the list of managed properties.
std::string getPropertyValue(const std::string &name) const override
Get the value of a property as a string.
TypedValue getProperty(const std::string &name) const override
Get the value of a property.
std::string toString() const override
Serialize an object to a string.
virtual std::shared_ptr< Algorithm > createChildAlgorithm(const std::string &name, const double startProgress=-1., const double endProgress=-1., const bool enableLogging=true, const int &version=-1)
Create a Child Algorithm.
static IAlgorithm_sptr fromString(const std::string &input)
De-serialize an object from a string.
Kernel::Logger & g_log
Definition Algorithm.h:422
void progress(double p, const std::string &msg="", double estimatedTime=0.0, int progressPrecision=0)
Sends ProgressNotification.
@ Load
allowed here which will be passed to the algorithm
Helper class for reporting progress from algorithms.
Definition Progress.h:25
A property class for workspaces.
IPropertyManager * setProperty(const std::string &name, const T &value)
Templated method to set the value of a PropertyWithValue.
void error(const std::string &msg)
Logs at error level.
Definition Logger.cpp:108
std::shared_ptr< IAlgorithm > IAlgorithm_sptr
shared pointer to Mantid::API::IAlgorithm
std::shared_ptr< MatrixWorkspace > MatrixWorkspace_sptr
shared pointer to the matrix workspace base class
std::shared_ptr< const EventWorkspace > EventWorkspace_const_sptr
shared pointer to a const Workspace2D
std::vector< double > MantidVec
typedef for the data storage used in Mantid matrix workspaces
Definition cow_ptr.h:172
@ Input
An input workspace.
Definition Property.h:53
@ Output
An output workspace.
Definition Property.h:54