Mantid
Loading...
Searching...
No Matches
EQSANSLoad.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 +
9#include "MantidAPI/Axis.h"
11#include "MantidAPI/Run.h"
19
20#include <boost/algorithm/string/trim.hpp>
21#include <boost/regex.hpp>
22
23#include "Poco/DirectoryIterator.h"
24#include "Poco/NumberFormatter.h"
25#include "Poco/NumberParser.h"
26#include "Poco/String.h"
27
28#include <fstream>
29
31
32// Register the algorithm into the AlgorithmFactory
33DECLARE_ALGORITHM(EQSANSLoad)
34
35using namespace Kernel;
36using namespace API;
37using namespace Geometry;
38using namespace DataObjects;
39
41 declareProperty(std::make_unique<API::FileProperty>("Filename", "", API::FileProperty::OptionalLoad, "_event.nxs"),
42 "The name of the input event Nexus file to load");
43
44 auto wsValidator = std::make_shared<WorkspaceUnitValidator>("TOF");
45 declareProperty(std::make_unique<WorkspaceProperty<EventWorkspace>>("InputWorkspace", "", Direction::Input,
46 PropertyMode::Optional, wsValidator),
47 "Input event workspace. Assumed to be unmodified events "
48 "straight from LoadEventNexus");
49
50 declareProperty(std::make_unique<WorkspaceProperty<>>("OutputWorkspace", "", Direction::Output),
51 "Then name of the output EventWorkspace");
52 declareProperty("NoBeamCenter", false, "If true, the detector will not be moved according to the beam center");
53 declareProperty("UseConfigBeam", false,
54 "If true, the beam center defined in "
55 "the configuration file will be "
56 "used");
57 declareProperty("BeamCenterX", EMPTY_DBL(),
58 "Beam position in X pixel "
59 "coordinates (used only if "
60 "UseConfigBeam is false)");
61 declareProperty("BeamCenterY", EMPTY_DBL(),
62 "Beam position in Y pixel "
63 "coordinates (used only if "
64 "UseConfigBeam is false)");
65 declareProperty("UseConfigTOFCuts", false,
66 "If true, the edges of the TOF distribution will be cut "
67 "according to the configuration file");
68 declareProperty("LowTOFCut", 0.0,
69 "TOF value below which events will not be "
70 "loaded into the workspace at load-time");
71 declareProperty("HighTOFCut", 0.0,
72 "TOF value above which events will not be "
73 "loaded into the workspace at load-time");
74 declareProperty("SkipTOFCorrection", false, "IF true, the EQSANS TOF correction will be skipped");
75 declareProperty("WavelengthStep", 0.1,
76 "Wavelength steps to be used when "
77 "rebinning the data before performing "
78 "the reduction");
79 declareProperty("UseConfigMask", false,
80 "If true, the masking information "
81 "found in the configuration file "
82 "will be used");
83 declareProperty("UseConfig", true, "If true, the best configuration file found will be used");
84 declareProperty("CorrectForFlightPath", false,
85 "If true, the TOF will be modified for the true flight path "
86 "from the sample to the detector pixel");
87 declareProperty("PreserveEvents", true, "If true, the output workspace will be an event workspace");
88 declareProperty("SampleDetectorDistance", EMPTY_DBL(),
89 "Sample to detector distance to use (overrides meta data), in mm");
90 declareProperty("SampleDetectorDistanceOffset", EMPTY_DBL(),
91 "Offset to the sample to detector distance (use only when "
92 "using the distance found in the meta data), in mm");
93 declareProperty("SampleOffset", EMPTY_DBL(),
94 "Offset to be applied to the sample position (use only when "
95 "using the detector distance found in the meta data), in mm");
96 declareProperty("DetectorOffset", EMPTY_DBL(),
97 "Offset to be applied to the detector position (use only when "
98 "using the distance found in the meta data), in mm");
99 declareProperty("LoadMonitors", true, "If true, the monitor workspace will be loaded");
100 declareProperty("LoadNexusInstrumentXML", true,
101 "Reads the embedded Instrument XML from the NeXus file "
102 "(optional, default True). ");
103 declareProperty("OutputMessage", "", Direction::Output);
104 declareProperty("ReductionProperties", "__sans_reduction_properties", Direction::Input);
105}
106
110double getRunPropertyDbl(const MatrixWorkspace_sptr &inputWS, const std::string &pname) {
111 Mantid::Kernel::Property *prop = inputWS->run().getProperty(pname);
112 const auto *dp = dynamic_cast<Mantid::Kernel::PropertyWithValue<double> *>(prop);
113 if (!dp)
114 throw std::runtime_error("Could not cast (interpret) the property " + pname +
115 " as a floating point numeric value.");
116 return *dp;
117}
118
121std::string EQSANSLoad::findConfigFile(const int &run) {
122 // Append the standard location of EQSANS config file to the data search
123 // directory list
124 std::string sns_folder = "/SNS/EQSANS/shared/instrument_configuration";
125 if (Poco::File(sns_folder).exists())
126 Kernel::ConfigService::Instance().appendDataSearchDir(sns_folder);
127
128 const std::vector<std::string> &searchPaths = Kernel::ConfigService::Instance().getDataSearchDirs();
129
130 int max_run_number = 0;
131 std::string config_file;
132 static boost::regex re1("eqsans_configuration\\.([0-9]+)$");
133 boost::smatch matches;
134 for (const auto &searchPath : searchPaths) {
135 if (Poco::File(searchPath).exists()) {
136 Poco::DirectoryIterator file_it(searchPath);
137 Poco::DirectoryIterator end;
138 for (; file_it != end; ++file_it) {
139 if (boost::regex_search(file_it.name(), matches, re1)) {
140 std::string s = matches[1];
141 int run_number = 0;
142 Poco::NumberParser::tryParse(s, run_number);
143 if (run_number > max_run_number && run_number <= run) {
144 max_run_number = run_number;
145 config_file = file_it.path().toString();
146 }
147 }
148 }
149 }
150 }
151 return config_file;
152}
153
156void EQSANSLoad::readRectangularMasks(const std::string &line) {
157 // Looking for rectangular mask
158 // Rectangular mask = 7, 0; 7, 255
159 boost::regex re_key("rectangular mask", boost::regex::icase);
160 boost::regex re_key_alt("elliptical mask", boost::regex::icase);
161 if (boost::regex_search(line, re_key) || boost::regex_search(line, re_key_alt)) {
162 boost::regex re_sig("=[ ]*([0-9]+)[ ]*[ ,][ ]*([0-9]+)[ ]*[ ;,][ "
163 "]*([0-9]+)[ ]*[ ,][ ]*([0-9]+)");
164 boost::smatch posVec;
165 if (boost::regex_search(line, posVec, re_sig)) {
166 if (posVec.size() == 5) {
167 for (int i = 0; i < 4; i++) {
168 std::string num_str = posVec[i + 1];
169 m_mask_as_string = m_mask_as_string + " " + num_str;
170 }
171 m_mask_as_string += ",";
172 }
173 }
174 }
175}
176
179void EQSANSLoad::readTOFcuts(const std::string &line) {
180 boost::regex re_key("tof edge discard", boost::regex::icase);
181 if (boost::regex_search(line, re_key)) {
182 boost::regex re_sig("=[ ]*([0-9]+)[ ]*[ ,][ ]*([0-9]+)");
183 boost::smatch posVec;
184 if (boost::regex_search(line, posVec, re_sig)) {
185 if (posVec.size() == 3) {
186 std::string num_str = posVec[1];
187 Poco::NumberParser::tryParseFloat(num_str, m_low_TOF_cut);
188 num_str = posVec[2];
189 Poco::NumberParser::tryParseFloat(num_str, m_high_TOF_cut);
190 }
191 }
192 }
193}
194
197void EQSANSLoad::readBeamCenter(const std::string &line) {
198 boost::regex re_key("spectrum center", boost::regex::icase);
199 if (boost::regex_search(line, re_key)) {
200 boost::regex re_sig("=[ ]*([0-9]+.[0-9]*)[ ]*[ ,][ ]*([0-9]+.[0-9]+)");
201 boost::smatch posVec;
202 if (boost::regex_search(line, posVec, re_sig)) {
203 if (posVec.size() == 3) {
204 std::string num_str = posVec[1];
205 Poco::NumberParser::tryParseFloat(num_str, m_center_x);
206 num_str = posVec[2];
207 Poco::NumberParser::tryParseFloat(num_str, m_center_y);
208 }
209 }
210 }
211}
212
215void EQSANSLoad::readModeratorPosition(const std::string &line) {
216 boost::regex re_key("sample location", boost::regex::icase);
217 if (boost::regex_search(line, re_key)) {
218 boost::regex re_sig("=[ ]*([0-9]+)");
219 boost::smatch posVec;
220 if (boost::regex_search(line, posVec, re_sig)) {
221 if (posVec.size() == 2) {
222 std::string num_str = posVec[1];
223 Poco::NumberParser::tryParseFloat(num_str, m_moderator_position);
225 }
226 }
227 }
228}
229
232void EQSANSLoad::readSourceSlitSize(const std::string &line) {
233 boost::regex re_key("wheel", boost::regex::icase);
234 if (boost::regex_search(line, re_key)) {
235 boost::regex re_sig(R"(([1-8]) wheel[ ]*([1-3])[ \t]*=[ \t]*(\w+))");
236 boost::smatch posVec;
237 if (boost::regex_search(line, posVec, re_sig)) {
238 if (posVec.size() == 4) {
239 std::string num_str = posVec[1];
240 int slit_number = 0;
241 Poco::NumberParser::tryParse(num_str, slit_number);
242 slit_number--;
243
244 num_str = posVec[2];
245 int wheel_number = 0;
246 Poco::NumberParser::tryParse(num_str, wheel_number);
247 wheel_number--;
248
249 num_str = posVec[3];
250 boost::regex re_size("\\w*?([0-9]+)mm");
251 int slit_size = 0;
252 if (boost::regex_search(num_str, posVec, re_size)) {
253 if (posVec.size() == 2) {
254 num_str = posVec[1];
255 Poco::NumberParser::tryParse(num_str, slit_size);
256 }
257 }
258 m_slit_positions[wheel_number][slit_number] = slit_size;
259 }
260 }
261 }
262}
263
266 if (!dataWS->run().hasProperty("vBeamSlit")) {
267 m_output_message += " Could not determine source aperture diameter: ";
268 m_output_message += "slit parameters were not found in the run log\n";
269 return;
270 }
271
272 const std::string slit1Name = "vBeamSlit";
273 Mantid::Kernel::Property *prop = dataWS->run().getProperty(slit1Name);
274 const auto *dp = dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(prop);
275 const auto *ip = dynamic_cast<Mantid::Kernel::TimeSeriesProperty<int> *>(prop);
276 int slit1;
277 if (dp)
278 slit1 = static_cast<int>(dp->getStatistics().mean);
279 else if (ip)
280 slit1 = static_cast<int>(ip->getStatistics().mean);
281 else
282 throw std::runtime_error("Could not cast (interpret) the property " + slit1Name +
283 " as a time series property with "
284 "int or floating point values.");
285
286 const std::string slit2Name = "vBeamSlit2";
287 prop = dataWS->run().getProperty(slit2Name);
288 dp = dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(prop);
289 ip = dynamic_cast<Mantid::Kernel::TimeSeriesProperty<int> *>(prop);
290 int slit2;
291 if (dp)
292 slit2 = static_cast<int>(dp->getStatistics().mean);
293 else if (ip)
294 slit2 = static_cast<int>(ip->getStatistics().mean);
295 else
296 throw std::runtime_error("Could not cast (interpret) the property " + slit2Name +
297 " as a time series property with "
298 "int or floating point values.");
299
300 const std::string slit3Name = "vBeamSlit3";
301 prop = dataWS->run().getProperty(slit3Name);
302 dp = dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(prop);
303 ip = dynamic_cast<Mantid::Kernel::TimeSeriesProperty<int> *>(prop);
304 int slit3;
305 if (dp)
306 slit3 = static_cast<int>(dp->getStatistics().mean);
307 else if (ip)
308 slit3 = static_cast<int>(ip->getStatistics().mean);
309 else
310 throw std::runtime_error("Could not cast (interpret) the property " + slit3Name +
311 " as a time series property with "
312 "int or floating point values.");
313
314 if (slit1 < 0 && slit2 < 0 && slit3 < 0) {
315 m_output_message += " Could not determine source aperture diameter\n";
316 return;
317 }
318
319 // Default slit size
320 double S1 = 20.0;
321 double L1 = -1.0;
322 const double ssd = fabs(dataWS->getInstrument()->getSource()->getPos().Z()) * 1000.0;
323 const int slits[3] = {slit1, slit2, slit3};
324 for (int i = 0; i < 3; i++) {
325 int m = slits[i] - 1;
326 if (m >= 0 && m < 6) {
327 double x = m_slit_positions[i][m];
328 double y = ssd - m_slit_to_source[i];
329 if (L1 < 0 || x / y < S1 / L1) {
330 L1 = y;
331 S1 = x;
332 }
333 }
334 }
335 dataWS->mutableRun().addProperty("source-aperture-diameter", S1, "mm", true);
336 m_output_message += " Source aperture diameter: ";
337 Poco::NumberFormatter::append(m_output_message, S1, 1);
338 m_output_message += " mm\n";
339}
340
343 // Check that we have a beam center defined, otherwise set the
344 // default beam center
347 g_log.information() << "Setting beam center to [" << m_center_x << ", " << m_center_y << "]\n";
348 return;
349 }
350
351 // Check that the center of the detector really is at (0,0)
352 int nx_pixels = static_cast<int>(dataWS->getInstrument()->getNumberParameter("number-of-x-pixels")[0]);
353 int ny_pixels = static_cast<int>(dataWS->getInstrument()->getNumberParameter("number-of-y-pixels")[0]);
354 const auto &detInfo = dataWS->detectorInfo();
355 const V3D pixel_first = detInfo.position(detInfo.indexOf(0));
356 int detIDx = EQSANSInstrument::getDetectorFromPixel(nx_pixels - 1, 0, dataWS);
357 int detIDy = EQSANSInstrument::getDetectorFromPixel(0, ny_pixels - 1, dataWS);
358
359 const V3D pixel_last_x = detInfo.position(detInfo.indexOf(detIDx));
360 const V3D pixel_last_y = detInfo.position(detInfo.indexOf(detIDy));
361 double x_offset = (pixel_first.X() + pixel_last_x.X()) / 2.0;
362 double y_offset = (pixel_first.Y() + pixel_last_y.Y()) / 2.0;
363 double beam_ctr_x = 0.0;
364 double beam_ctr_y = 0.0;
366
367 auto mvAlg = createChildAlgorithm("MoveInstrumentComponent", 0.5, 0.50);
368 mvAlg->setProperty<MatrixWorkspace_sptr>("Workspace", dataWS);
369 mvAlg->setProperty("ComponentName", "detector1");
370 mvAlg->setProperty("X", -x_offset - beam_ctr_x);
371 mvAlg->setProperty("Y", -y_offset - beam_ctr_y);
372 mvAlg->setProperty("RelativePosition", true);
373 mvAlg->executeAsChildAlg();
374 m_output_message += " Beam center offset: " + Poco::NumberFormatter::format(x_offset) + ", " +
375 Poco::NumberFormatter::format(y_offset) + " m\n";
376 // m_output_message += " Beam center in real-space: " +
377 // Poco::NumberFormatter::format(-x_offset-beam_ctr_x)
378 // + ", " + Poco::NumberFormatter::format(-y_offset-beam_ctr_y) + " m\n";
379 g_log.information() << "Moving beam center to " << m_center_x << " " << m_center_y << '\n';
380
381 dataWS->mutableRun().addProperty("beam_center_x", m_center_x, "pixel", true);
382 dataWS->mutableRun().addProperty("beam_center_y", m_center_y, "pixel", true);
383 m_output_message += " Beam center: " + Poco::NumberFormatter::format(m_center_x) + ", " +
384 Poco::NumberFormatter::format(m_center_y) + "\n";
385}
386
389void EQSANSLoad::readConfigFile(const std::string &filePath) {
390 // Initialize parameters
391 m_mask_as_string = "";
393
394 // The following should be properties
395 bool use_config_mask = getProperty("UseConfigMask");
396 bool use_config_cutoff = getProperty("UseConfigTOFCuts");
397 bool use_config_center = getProperty("UseConfigBeam");
398
399 std::ifstream file(filePath.c_str());
400 if (!file) {
401 g_log.error() << "Unable to open file: " << filePath << '\n';
402 throw Exception::FileError("Unable to open file: ", filePath);
403 }
404 g_log.information() << "Using config file: " << filePath << '\n';
405 m_output_message += " Using configuration file: " + filePath + "\n";
406
407 std::string line;
408 while (getline(file, line)) {
409 boost::trim(line);
410 std::string comment = line.substr(0, 1);
411 if (Poco::icompare(comment, "#") == 0)
412 continue;
413 if (use_config_mask)
415 if (use_config_cutoff)
416 readTOFcuts(line);
417 if (use_config_center)
418 readBeamCenter(line);
420 readSourceSlitSize(line);
421 }
422
423 if (use_config_mask)
424 dataWS->mutableRun().addProperty("rectangular_masks", m_mask_as_string, "pixels", true);
425
426 dataWS->mutableRun().addProperty("low_tof_cut", m_low_TOF_cut, "microsecond", true);
427 dataWS->mutableRun().addProperty("high_tof_cut", m_high_TOF_cut, "microsecond", true);
428 m_output_message += " Discarding lower " + Poco::NumberFormatter::format(m_low_TOF_cut) + " and upper " +
429 Poco::NumberFormatter::format(m_high_TOF_cut) + " microsec\n";
430
431 if (m_moderator_position != 0)
432 dataWS->mutableRun().addProperty("moderator_position", m_moderator_position, "mm", true);
433}
434
436 // Verify the validity of the inputs
437 // TODO: this should be done by the new data management algorithm used for
438 // live data reduction (when it's implemented...)
439 const std::string fileName = getPropertyValue("Filename");
440 EventWorkspace_sptr inputEventWS = getProperty("InputWorkspace");
441 if (fileName.empty() && !inputEventWS) {
442 g_log.error() << "EQSANSLoad input error: Either a valid file path or an "
443 "input workspace must be provided\n";
444 throw std::runtime_error("EQSANSLoad input error: Either a valid file path "
445 "or an input workspace must be provided");
446 } else if (!fileName.empty() && inputEventWS) {
447 g_log.error() << "EQSANSLoad input error: Either a valid file path or an "
448 "input workspace must be provided, but not both\n";
449 throw std::runtime_error("EQSANSLoad input error: Either a valid file path "
450 "or an input workspace must be provided, but not "
451 "both");
452 }
453
454 // Read in default TOF cuts
455 const bool skipTOFCorrection = getProperty("SkipTOFCorrection");
456 m_low_TOF_cut = getProperty("LowTOFCut");
457 m_high_TOF_cut = getProperty("HighTOFCut");
458
459 // Read in default beam center
460 m_center_x = getProperty("BeamCenterX");
461 m_center_y = getProperty("BeamCenterY");
462 const bool noBeamCenter = getProperty("NoBeamCenter");
463
464 // Reduction property manager
465 const std::string reductionManagerName = getProperty("ReductionProperties");
466 std::shared_ptr<PropertyManager> reductionManager;
467 if (PropertyManagerDataService::Instance().doesExist(reductionManagerName)) {
468 reductionManager = PropertyManagerDataService::Instance().retrieve(reductionManagerName);
469 } else {
470 reductionManager = std::make_shared<PropertyManager>();
471 PropertyManagerDataService::Instance().addOrReplace(reductionManagerName, reductionManager);
472 }
473
474 if (!reductionManager->existsProperty("LoadAlgorithm")) {
475 auto loadProp = std::make_unique<AlgorithmProperty>("LoadAlgorithm");
476 setPropertyValue("InputWorkspace", "");
477 setProperty("NoBeamCenter", false);
478 loadProp->setValue(toString());
479 reductionManager->declareProperty(std::move(loadProp));
480 }
481
482 if (!reductionManager->existsProperty("InstrumentName"))
483 reductionManager->declareProperty(std::make_unique<PropertyWithValue<std::string>>("InstrumentName", "EQSANS"));
484
485 // Output log
486 m_output_message = "";
487
488 // Check whether we need to load the data
489 if (!inputEventWS) {
490 const bool loadMonitors = getProperty("LoadMonitors");
491 const bool loadNexusInstrumentXML = getProperty("LoadNexusInstrumentXML");
492 auto loadAlg = createChildAlgorithm("LoadEventNexus", 0, 0.2);
493 loadAlg->setProperty("LoadMonitors", loadMonitors);
494 loadAlg->setProperty("Filename", fileName);
495 loadAlg->setProperty("LoadNexusInstrumentXML", loadNexusInstrumentXML);
496 if (skipTOFCorrection) {
497 if (m_low_TOF_cut > 0.0)
498 loadAlg->setProperty("FilterByTofMin", m_low_TOF_cut);
499 if (m_high_TOF_cut > 0.0)
500 loadAlg->setProperty("FilterByTofMax", m_high_TOF_cut);
501 }
502 loadAlg->execute();
503 Workspace_sptr dataWS_asWks = loadAlg->getProperty("OutputWorkspace");
504 dataWS = std::dynamic_pointer_cast<MatrixWorkspace>(dataWS_asWks);
505
506 // Get monitor workspace as necessary
507 std::string mon_wsname = getPropertyValue("OutputWorkspace") + "_monitors";
508 if (loadMonitors && loadAlg->existsProperty("MonitorWorkspace")) {
509 Workspace_sptr monWSOutput = loadAlg->getProperty("MonitorWorkspace");
510 MatrixWorkspace_sptr monWS = std::dynamic_pointer_cast<MatrixWorkspace>(monWSOutput);
511 if ((monWSOutput) && (!monWS))
512 // this was a group workspace - EQSansLoad does not support multi period
513 // data yet
514 throw Exception::NotImplementedError("The file contains multi period "
515 "data, support for this is not "
516 "implemented in EQSANSLoad yet");
517 declareProperty(std::make_unique<WorkspaceProperty<>>("MonitorWorkspace", mon_wsname, Direction::Output),
518 "Monitors from the Event NeXus file");
519 setProperty("MonitorWorkspace", monWS);
520 }
521 } else {
522 MatrixWorkspace_sptr outputWS = getProperty("OutputWorkspace");
523 EventWorkspace_sptr outputEventWS = std::dynamic_pointer_cast<EventWorkspace>(outputWS);
524 if (inputEventWS != outputEventWS) {
525 auto copyAlg = createChildAlgorithm("CloneWorkspace", 0, 0.2);
526 copyAlg->setProperty("InputWorkspace", inputEventWS);
527 copyAlg->executeAsChildAlg();
528 Workspace_sptr dataWS_asWks = copyAlg->getProperty("OutputWorkspace");
529 dataWS = std::dynamic_pointer_cast<MatrixWorkspace>(dataWS_asWks);
530 } else {
531 dataWS = std::dynamic_pointer_cast<MatrixWorkspace>(inputEventWS);
532 }
533 }
534
535 // Get the sample flange-to-detector distance
536 // We have to call it "SampleDetectorDistance" in the workspace
537 double sfdd = 0.0;
538 double s2d = 0.0;
539 const double sampleflange_det_dist = getProperty("SampleDetectorDistance");
540 if (!isEmpty(sampleflange_det_dist)) {
541 sfdd = sampleflange_det_dist;
542 } else {
543 if (!dataWS->run().hasProperty("detectorZ")) {
544 g_log.error() << "Could not determine Z position: the "
545 "SampleDetectorDistance property was not set "
546 "and the run logs do not contain the detectorZ property\n";
547 throw std::invalid_argument("Could not determine Z position: stopping execution");
548 }
549
550 const std::string dzName = "detectorZ";
551 Mantid::Kernel::Property *prop = dataWS->run().getProperty(dzName);
552 const auto *dp = dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(prop);
553 if (!dp)
554 throw std::runtime_error("Could not cast (interpret) the property " + dzName +
555 " as a time series property value.");
556 sfdd = dp->getStatistics().mean;
557
558 // Modify SDD according to the DetectorDistance offset if given
559 const double sampleflange_det_offset = getProperty("DetectorOffset");
560 if (!isEmpty(sampleflange_det_offset))
561 sfdd += sampleflange_det_offset;
562
563 // Modify SDD according to SampleDetectorDistanceOffset offset if given.
564 // This is here for backward compatibility.
565 const double sample_det_offset = getProperty("SampleDetectorDistanceOffset");
566 if (!isEmpty(sample_det_offset))
567 sfdd += sample_det_offset;
568 if (!isEmpty(sample_det_offset) && !isEmpty(sampleflange_det_offset))
569 g_log.error() << "Both DetectorOffset and SampleDetectorDistanceOffset "
570 "are set. Only one should be used.\n";
571
572 s2d = sfdd;
573 // Modify S2D according to the SampleDistance offset if given
574 // This assumes that a positive offset moves the sample toward the detector
575 const double sampleflange_sample_offset = getProperty("SampleOffset");
576 if (!isEmpty(sampleflange_sample_offset)) {
577 s2d -= sampleflange_sample_offset;
578
579 // Move the sample to its correct position
580 auto mvAlg = createChildAlgorithm("MoveInstrumentComponent", 0.2, 0.4);
581 mvAlg->setProperty<MatrixWorkspace_sptr>("Workspace", dataWS);
582 mvAlg->setProperty("ComponentName", "sample-position");
583 mvAlg->setProperty("Z", sampleflange_sample_offset / 1000.0);
584 mvAlg->setProperty("RelativePosition", false);
585 mvAlg->executeAsChildAlg();
586 g_log.information() << "Moving sample to " << sampleflange_sample_offset / 1000.0 << " meters\n";
588 " Sample position: " + Poco::NumberFormatter::format(sampleflange_sample_offset / 1000.0, 3) + " m\n";
589 }
590 }
591 dataWS->mutableRun().addProperty("sampleflange_detector_distance", sfdd, "mm", true);
592 dataWS->mutableRun().addProperty("sample_detector_distance", s2d, "mm", true);
593
594 // Move the detector to its correct position
595 auto mvAlg = createChildAlgorithm("MoveInstrumentComponent", 0.2, 0.4);
596 mvAlg->setProperty<MatrixWorkspace_sptr>("Workspace", dataWS);
597 mvAlg->setProperty("ComponentName", "detector1");
598 mvAlg->setProperty("Z", sfdd / 1000.0);
599 mvAlg->setProperty("RelativePosition", false);
600 mvAlg->executeAsChildAlg();
601 g_log.information() << "Moving detector to " << sfdd / 1000.0 << " meters\n";
602 m_output_message += " Detector position: " + Poco::NumberFormatter::format(sfdd / 1000.0, 3) + " m\n";
603
604 // Get the run number so we can find the proper config file
605 int run_number = 0;
606 std::string config_file;
607 if (dataWS->run().hasProperty("run_number")) {
608 const std::string run_str = dataWS->run().getPropertyValueAsType<std::string>("run_number");
609 Poco::NumberParser::tryParse(run_str, run_number);
610 // Find a proper config file
611 config_file = findConfigFile(run_number);
612 } else {
613 g_log.error() << "Could not find run number for workspace " << getPropertyValue("OutputWorkspace") << '\n';
614 m_output_message += " Could not find run number for data file\n";
615 }
616
617 // Process the config file
618 bool use_config = getProperty("UseConfig");
619 if (use_config && !config_file.empty()) {
620 // Special case to force reading the beam center from the config file
621 // We're adding this to be compatible with the original EQSANS load
622 // written in python
623 if (m_center_x == 0.0 && m_center_y == 0.0)
624 setProperty("UseConfigBeam", true);
625
626 readConfigFile(config_file);
627 } else if (use_config) {
628 use_config = false;
629 g_log.error() << "Cound not find config file for workspace " << getPropertyValue("OutputWorkspace") << '\n';
631 " Could not find configuration file for run " + Poco::NumberFormatter::format(run_number) + "\n";
632 }
633
634 // If we use the config file, move the moderator position
635 if (use_config) {
636 if (m_moderator_position > -13.0)
637 g_log.error() << "Moderator position seems close to the sample, please check\n";
638 g_log.information() << "Moving moderator to " << m_moderator_position << '\n';
639 m_output_message += " Moderator position: " + Poco::NumberFormatter::format(m_moderator_position) + " m\n";
640 mvAlg = createChildAlgorithm("MoveInstrumentComponent", 0.4, 0.45);
641 mvAlg->setProperty<MatrixWorkspace_sptr>("Workspace", dataWS);
642 mvAlg->setProperty("ComponentName", "moderator");
643 mvAlg->setProperty("Z", m_moderator_position);
644 mvAlg->setProperty("RelativePosition", false);
645 mvAlg->executeAsChildAlg();
646 }
647
648 // Get source aperture radius
650
651 // Move the beam center to its proper position
652 if (!noBeamCenter) {
654 if (reductionManager->existsProperty("LatestBeamCenterX") &&
655 reductionManager->existsProperty("LatestBeamCenterY")) {
656 m_center_x = reductionManager->getProperty("LatestBeamCenterX");
657 m_center_y = reductionManager->getProperty("LatestBeamCenterY");
658 }
659 }
661
662 // Add beam center to reduction properties, as the last beam center position
663 // that was used.
664 // This will give us our default position next time.
665 if (!reductionManager->existsProperty("LatestBeamCenterX"))
666 reductionManager->declareProperty(std::make_unique<PropertyWithValue<double>>("LatestBeamCenterX", m_center_x));
667 else
668 reductionManager->setProperty("LatestBeamCenterX", m_center_x);
669 if (!reductionManager->existsProperty("LatestBeamCenterY"))
670 reductionManager->declareProperty(std::make_unique<PropertyWithValue<double>>("LatestBeamCenterY", m_center_y));
671 else
672 reductionManager->setProperty("LatestBeamCenterY", m_center_y);
673 }
674
675 // Modify TOF
676 const bool correct_for_flight_path = getProperty("CorrectForFlightPath");
677 double wl_min = 0.0;
678 double wl_max;
679 double wl_combined_max = 0.0;
680 if (skipTOFCorrection) {
681 m_output_message += " Skipping EQSANS TOF correction: assuming a single frame\n";
682 dataWS->mutableRun().addProperty("is_frame_skipping", 0, true);
683 if (correct_for_flight_path) {
684 g_log.error() << "CorrectForFlightPath and SkipTOFCorrection can't be "
685 "set to true at the same time\n";
686 m_output_message += " Skipped flight path correction: see error log\n";
687 }
688 } else {
689 m_output_message += " Flight path correction ";
690 if (!correct_for_flight_path)
691 m_output_message += "NOT ";
692 m_output_message += "applied\n";
693 DataObjects::EventWorkspace_sptr dataWS_evt = std::dynamic_pointer_cast<EventWorkspace>(dataWS);
694 auto tofAlg = createChildAlgorithm("EQSANSTofStructure", 0.5, 0.7);
695 tofAlg->setProperty<EventWorkspace_sptr>("InputWorkspace", dataWS_evt);
696 tofAlg->setProperty("LowTOFCut", m_low_TOF_cut);
697 tofAlg->setProperty("HighTOFCut", m_high_TOF_cut);
698 tofAlg->setProperty("FlightPathCorrection", correct_for_flight_path);
699 tofAlg->executeAsChildAlg();
700 wl_min = tofAlg->getProperty("WavelengthMin");
701 wl_max = tofAlg->getProperty("WavelengthMax");
702 if (wl_min >= wl_max) {
703 g_log.error() << "Bad wavelength range\n";
704 g_log.error() << m_output_message << '\n';
705 }
706
707 const bool frame_skipping = tofAlg->getProperty("FrameSkipping");
708 dataWS->mutableRun().addProperty("wavelength_min", wl_min, "Angstrom", true);
709 dataWS->mutableRun().addProperty("wavelength_max", wl_max, "Angstrom", true);
710 dataWS->mutableRun().addProperty("is_frame_skipping", int(frame_skipping), true);
711 wl_combined_max = wl_max;
713 " Wavelength range: " + Poco::NumberFormatter::format(wl_min) + " - " + Poco::NumberFormatter::format(wl_max);
714 if (frame_skipping) {
715 const double wl_min2 = tofAlg->getProperty("WavelengthMinFrame2");
716 const double wl_max2 = tofAlg->getProperty("WavelengthMaxFrame2");
717 wl_combined_max = wl_max2;
718 dataWS->mutableRun().addProperty("wavelength_min_frame2", wl_min2, "Angstrom", true);
719 dataWS->mutableRun().addProperty("wavelength_max_frame2", wl_max2, "Angstrom", true);
720 m_output_message += " and " + Poco::NumberFormatter::format(wl_min2) + " - " +
721 Poco::NumberFormatter::format(wl_max2) + " Angstrom\n";
722 } else
723 m_output_message += " Angstrom\n";
724 }
725
726 // Convert to wavelength
727 // Checked on 8/10/17 - changed from "sdd" to "sfdd" as was done above
728 // sfdd + ssd gives total distance (corrected by offset) from the source
729 const double ssd = fabs(dataWS->getInstrument()->getSource()->getPos().Z()) * 1000.0;
730 const double conversion_factor = 3.9560346 / (sfdd + ssd);
732 " TOF to wavelength conversion factor: " + Poco::NumberFormatter::format(conversion_factor) + "\n";
733
734 if (skipTOFCorrection) {
735 DataObjects::EventWorkspace_sptr dataWS_evt = std::dynamic_pointer_cast<EventWorkspace>(dataWS);
736 if (dataWS_evt->getNumberEvents() == 0)
737 throw std::invalid_argument("No event to process: check your TOF cuts");
738 wl_min = dataWS_evt->getTofMin() * conversion_factor;
739 wl_max = dataWS_evt->getTofMax() * conversion_factor;
740 wl_combined_max = wl_max;
741 g_log.information() << "Wavelength range: " << wl_min << " to " << wl_max << '\n';
742 dataWS->mutableRun().addProperty("wavelength_min", wl_min, "Angstrom", true);
743 dataWS->mutableRun().addProperty("wavelength_max", wl_max, "Angstrom", true);
744 }
745
746 auto scAlg = createChildAlgorithm("ScaleX", 0.7, 0.71);
747 scAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", dataWS);
748 scAlg->setProperty<MatrixWorkspace_sptr>("OutputWorkspace", dataWS);
749 scAlg->setProperty("Factor", conversion_factor);
750 scAlg->executeAsChildAlg();
751 dataWS->getAxis(0)->setUnit("Wavelength");
752
753 // Rebin so all the wavelength bins are aligned
754 const bool preserveEvents = getProperty("PreserveEvents");
755 const double wl_step = getProperty("WavelengthStep");
756
757 const double wl_min_rounded = round(wl_min * 100.0) / 100.0;
758 const double wl_max_rounded = round(wl_combined_max * 100.0) / 100.0;
759 std::string params = Poco::NumberFormatter::format(wl_min_rounded, 2) + "," + Poco::NumberFormatter::format(wl_step) +
760 "," + Poco::NumberFormatter::format(wl_max_rounded, 2);
761 g_log.information() << "Rebin parameters: " << params << '\n';
762 auto rebinAlg = createChildAlgorithm("Rebin", 0.71, 0.72);
763 rebinAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", dataWS);
764 if (preserveEvents)
765 rebinAlg->setProperty<MatrixWorkspace_sptr>("OutputWorkspace", dataWS);
766 rebinAlg->setPropertyValue("Params", params);
767 rebinAlg->setProperty("PreserveEvents", preserveEvents);
768 rebinAlg->executeAsChildAlg();
769
770 if (!preserveEvents)
771 dataWS = rebinAlg->getProperty("OutputWorkspace");
772
773 dataWS->mutableRun().addProperty("event_ws", getPropertyValue("OutputWorkspace"), true);
774 setProperty<MatrixWorkspace_sptr>("OutputWorkspace", std::dynamic_pointer_cast<MatrixWorkspace>(dataWS));
775 setPropertyValue("OutputMessage", m_output_message);
776}
777
778} // namespace Mantid::WorkflowAlgorithms
#define DECLARE_ALGORITHM(classname)
Definition Algorithm.h:538
#define fabs(x)
Definition Matrix.cpp:22
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.
Kernel::Logger & g_log
Definition Algorithm.h:422
void setPropertyValue(const std::string &name, const std::string &value) override
Set the value of a property by string N.B.
static bool isEmpty(const NumT toCheck)
checks that the value was not set by users, uses the value in empty double/int.
@ OptionalLoad
to specify a file to read but the file doesn't have to exist
A property class for workspaces.
Records the filename and the description of failure.
Definition Exception.h:98
Marks code as not implemented yet.
Definition Exception.h:138
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
void information(const std::string &msg)
Logs at information level.
Definition Logger.cpp:136
The concrete, templated class for properties.
Base class for properties.
Definition Property.h:94
A specialised Property class for holding a series of time-value pairs.
TimeSeriesPropertyStatistics getStatistics(const Kernel::TimeROI *roi=nullptr) const override
Return a TimeSeriesPropertyStatistics object.
Class for 3D vectors.
Definition V3D.h:34
constexpr double X() const noexcept
Get x.
Definition V3D.h:238
constexpr double Y() const noexcept
Get y.
Definition V3D.h:239
void readBeamCenter(const std::string &line)
Read the beam center from a config file string.
void readTOFcuts(const std::string &line)
Read the TOF cuts from a config file string.
void exec() override
Execution code.
API::MatrixWorkspace_sptr dataWS
Definition EQSANSLoad.h:70
void readModeratorPosition(const std::string &line)
Read the moderator position from a config file string.
void init() override
Initialisation code.
void getSourceSlitSize()
Get the source slit size from the slit information of the run properties.
void readSourceSlitSize(const std::string &line)
Read the source slit sizes from a config file string.
void moveToBeamCenter()
Move the detector according to the beam center.
void readRectangularMasks(const std::string &line)
Read rectangular masks from a config file string.
void readConfigFile(const std::string &filePath)
Read a config file.
std::string findConfigFile(const int &run)
Find the most appropriate configuration file for a given run.
std::shared_ptr< Workspace > Workspace_sptr
shared pointer to Mantid::API::Workspace
std::shared_ptr< MatrixWorkspace > MatrixWorkspace_sptr
shared pointer to the matrix workspace base class
bool exists(Nexus::File &file, const std::string &name)
std::shared_ptr< EventWorkspace > EventWorkspace_sptr
shared pointer to the EventWorkspace class
void getDefaultBeamCenter(const API::MatrixWorkspace_sptr &dataWS, double &pixel_x, double &pixel_y)
int getDetectorFromPixel(const int &pixel_x, const int &pixel_y, const API::MatrixWorkspace_sptr &dataWS)
void getCoordinateFromPixel(const double &pixel_x, const double &pixel_y, const API::MatrixWorkspace_sptr &dataWS, double &x, double &y)
double getRunPropertyDbl(const MatrixWorkspace_sptr &inputWS, const std::string &pname)
Returns the value of a run property from a given workspace.
constexpr double EMPTY_DBL() noexcept
Returns what we consider an "empty" double within a property.
Definition EmptyValues.h:42
@ Input
An input workspace.
Definition Property.h:53
@ Output
An output workspace.
Definition Property.h:54