Mantid
Loading...
Searching...
No Matches
LoadSampleEnvironment.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 +
10#ifdef ENABLE_LIB3MF
12#endif
18
22#include "MantidAPI/Sample.h"
23
30
31#include <filesystem>
32#include <fstream>
33
34namespace Mantid::DataHandling {
35
36namespace {
37double DegreesToRadians(double angle) { return angle * M_PI / 180; }
38} // namespace
39
40// Register the algorithm into the algorithm factory
41DECLARE_ALGORITHM(LoadSampleEnvironment)
42
43using namespace Kernel;
44using namespace API;
45using namespace Geometry;
46
48 auto wsValidator = std::make_shared<InstrumentValidator>();
49 // input workspace
50 declareProperty(std::make_unique<WorkspaceProperty<>>("InputWorkspace", "", Direction::Input, wsValidator),
51 "The name of the workspace containing the instrument to add "
52 "the Environment");
53
54 // Environment file
55 const std::vector<std::string> extensions{".stl", ".3mf"};
56 declareProperty(std::make_unique<FileProperty>("Filename", "", FileProperty::Load, extensions),
57 "The path name of the file containing the Environment");
58
59 // scale to use for stl
60 declareProperty("Scale", "cm", "The scale of the stl: m, cm, or mm");
61
62 // Output workspace
63 declareProperty(std::make_unique<WorkspaceProperty<>>("OutputWorkspace", "", Direction::Output),
64 "The name of the workspace that will contain the loaded "
65 "Environment of the sample");
66
67 // Environment Name
68 declareProperty("EnvironmentName", "Environment");
69
70 // New Can or Add
71 declareProperty("Add", false);
72
73 // Rotation angles
74 declareProperty("XDegrees", 0.0, "The degrees to rotate on the x axis by");
75 declareProperty("YDegrees", 0.0, "The degrees to rotate on the y axis by");
76 declareProperty("ZDegrees", 0.0, "The degrees to rotate on the z axis by");
77
78 // Vector to translate mesh
79 declareProperty(std::make_unique<ArrayProperty<double>>("TranslationVector", "0,0,0"),
80 "Vector by which to translate the loaded environment");
81
82 declareProperty("SetMaterial", false);
83
84 // properties for SetMaterial
85
86 declareProperty("ChemicalFormula", "", "The chemical formula, see examples in documentation");
87
88 declareProperty("AtomicNumber", 0, "The atomic number");
89 declareProperty("MassNumber", 0, "Mass number if ion (use 0 for default mass sensity)");
90 auto mustBePositive = std::make_shared<BoundedValidator<double>>();
91 mustBePositive->setLower(0.0);
92 declareProperty("SampleNumberDensity", EMPTY_DBL(), mustBePositive,
93 "This number density of the sample in number of "
94 "atoms per cubic angstrom will be used instead of "
95 "calculated");
96 declareProperty("ZParameter", EMPTY_DBL(), mustBePositive, "Number of formula units in unit cell");
97 declareProperty("UnitCellVolume", EMPTY_DBL(), mustBePositive,
98 "Unit cell volume in Angstoms^3. Will be calculated from the "
99 "OrientedLattice if not supplied.");
100 declareProperty("CoherentXSection", EMPTY_DBL(), mustBePositive,
101 "Optional: This coherent cross-section for the sample "
102 "material in barns will be used instead of tabulated");
103 declareProperty("IncoherentXSection", EMPTY_DBL(), mustBePositive,
104 "Optional: This incoherent cross-section for the sample "
105 "material in barns will be used instead of tabulated");
106 declareProperty("AttenuationXSection", EMPTY_DBL(), mustBePositive,
107 "Optional: This absorption cross-section for the sample "
108 "material in barns will be used instead of tabulated");
109 declareProperty("ScatteringXSection", EMPTY_DBL(), mustBePositive,
110 "Optional: This total scattering cross-section (coherent + "
111 "incoherent) for the sample material in barns will be used "
112 "instead of tabulated");
113 const std::vector<std::string> attExtensions{".DAT"};
114 declareProperty(std::make_unique<FileProperty>("AttenuationProfile", "", FileProperty::OptionalLoad, attExtensions),
115 "The path name of the file containing the attenuation profile");
116 declareProperty("SampleMassDensity", EMPTY_DBL(), mustBePositive,
117 "Measured mass density in g/cubic cm of the sample "
118 "to be used to calculate the number density.");
119 const std::vector<std::string> units({"Atoms", "Formula Units"});
120 declareProperty("NumberDensityUnit", units.front(), std::make_shared<StringListValidator>(units),
121 "Choose which units SampleNumberDensity referes to.");
122
123 // Perform Group Associations.
124 std::string formulaGrp("By Formula or Atomic Number");
125 setPropertyGroup("ChemicalFormula", formulaGrp);
126 setPropertyGroup("AtomicNumber", formulaGrp);
127 setPropertyGroup("MassNumber", formulaGrp);
128 setPropertySettings("ChemicalFormula", std::make_unique<EnabledWhenProperty>("SetMaterial", IS_NOT_DEFAULT));
129 setPropertySettings("AtomicNumber", std::make_unique<EnabledWhenProperty>("SetMaterial", IS_NOT_DEFAULT));
130 setPropertySettings("MassNumber", std::make_unique<EnabledWhenProperty>("SetMaterial", IS_NOT_DEFAULT));
131
132 std::string densityGrp("Sample Density");
133 setPropertyGroup("SampleNumberDensity", densityGrp);
134 setPropertyGroup("NumberDensityUnit", densityGrp);
135 setPropertyGroup("ZParameter", densityGrp);
136 setPropertyGroup("UnitCellVolume", densityGrp);
137 setPropertyGroup("SampleMassDensity", densityGrp);
138 setPropertySettings("SampleNumberDensity", std::make_unique<EnabledWhenProperty>("SetMaterial", IS_NOT_DEFAULT));
139 setPropertySettings("ZParameter", std::make_unique<EnabledWhenProperty>("SetMaterial", IS_NOT_DEFAULT));
140 setPropertySettings("UnitCellVolume", std::make_unique<EnabledWhenProperty>("SetMaterial", IS_NOT_DEFAULT));
141 setPropertySettings("SampleMassDensity", std::make_unique<EnabledWhenProperty>("SetMaterial", IS_NOT_DEFAULT));
142 setPropertySettings("NumberDensityUnit",
143 std::make_unique<EnabledWhenProperty>("SampleNumberDensity", IS_NOT_DEFAULT));
144
145 std::string specificValuesGrp("Override Cross Section Values");
146 setPropertyGroup("CoherentXSection", specificValuesGrp);
147 setPropertyGroup("IncoherentXSection", specificValuesGrp);
148 setPropertyGroup("AttenuationXSection", specificValuesGrp);
149 setPropertyGroup("ScatteringXSection", specificValuesGrp);
150 setPropertyGroup("AttenuationProfile", specificValuesGrp);
151 setPropertySettings("CoherentXSection", std::make_unique<EnabledWhenProperty>("SetMaterial", IS_NOT_DEFAULT));
152 setPropertySettings("IncoherentXSection", std::make_unique<EnabledWhenProperty>("SetMaterial", IS_NOT_DEFAULT));
153 setPropertySettings("AttenuationXSection", std::make_unique<EnabledWhenProperty>("SetMaterial", IS_NOT_DEFAULT));
154 setPropertySettings("ScatteringXSection", std::make_unique<EnabledWhenProperty>("SetMaterial", IS_NOT_DEFAULT));
155 setPropertySettings("AttenuationProfile", std::make_unique<EnabledWhenProperty>("SetMaterial", IS_NOT_DEFAULT));
156}
157
158std::map<std::string, std::string> LoadSampleEnvironment::validateInputs() {
159 std::map<std::string, std::string> result;
160 if (getProperty("SetMaterial")) {
162 params.chemicalSymbol = getPropertyValue("ChemicalFormula");
163 params.atomicNumber = getProperty("AtomicNumber");
164 params.massNumber = getProperty("MassNumber");
165 params.numberDensity = getProperty("SampleNumberDensity");
166 params.zParameter = getProperty("ZParameter");
167 params.unitCellVolume = getProperty("UnitCellVolume");
168 params.massDensity = getProperty("SampleMassDensity");
169 result = ReadMaterial::validateInputs(params);
170 }
171 return result;
172}
173
183void LoadSampleEnvironment::loadEnvironmentFromSTL(const std::string &filename, Sample &sample, const bool add,
184 std::string debugString) {
185 std::unique_ptr<SampleEnvironment> environment = nullptr;
186 std::shared_ptr<MeshObject> environmentMesh = nullptr;
187
188 std::unique_ptr<LoadAsciiStl> asciiStlReader = nullptr;
189 std::unique_ptr<LoadBinaryStl> binaryStlReader = nullptr;
190 const std::string scaleProperty = getPropertyValue("Scale");
191 const ScaleUnits scaleType = getScaleTypeFromStr(scaleProperty);
192
193 bool isBinary;
194 if (LoadBinaryStl::isBinarySTL(filename)) {
195 isBinary = true;
196 } else if (LoadAsciiStl::isAsciiSTL(filename)) {
197 isBinary = false;
198 } else {
199 throw Exception::ParseError("Could not read file, did not match either STL Format", filename, 0);
200 }
201 std::unique_ptr<LoadStl> reader = nullptr;
202
203 if (getProperty("SetMaterial")) {
205 params.chemicalSymbol = getPropertyValue("ChemicalFormula");
206 params.atomicNumber = getProperty("AtomicNumber");
207 params.massNumber = getProperty("MassNumber");
208 params.numberDensity = getProperty("SampleNumberDensity");
209 params.zParameter = getProperty("ZParameter");
210 params.unitCellVolume = getProperty("UnitCellVolume");
211 params.massDensity = getProperty("SampleMassDensity");
212 params.coherentXSection = getProperty("CoherentXSection");
213 params.incoherentXSection = getProperty("IncoherentXSection");
214 params.attenuationXSection = getProperty("AttenuationXSection");
215 params.scatteringXSection = getProperty("ScatteringXSection");
216 params.attenuationProfileFileName = getPropertyValue("AttenuationProfile");
217 const std::string numberDensityUnit = getProperty("NumberDensityUnit");
218 if (numberDensityUnit == "Atoms") {
220 } else {
222 }
223 if (isBinary) {
224 reader = std::make_unique<LoadBinaryStl>(filename, scaleType, params);
225 } else {
226 reader = std::make_unique<LoadAsciiStl>(filename, scaleType, params);
227 }
228 } else {
229 if (isBinary) {
230 reader = std::make_unique<LoadBinaryStl>(filename, scaleType);
231 } else {
232 reader = std::make_unique<LoadAsciiStl>(filename, scaleType);
233 }
234 }
235
236 environmentMesh = reader->readShape();
237
238 const double xRotation = DegreesToRadians(getProperty("xDegrees"));
239 const double yRotation = DegreesToRadians(getProperty("yDegrees"));
240 const double zRotation = DegreesToRadians(getProperty("zDegrees"));
241 environmentMesh = reader->rotate(environmentMesh, xRotation, yRotation, zRotation);
242 const std::vector<double> translationVector = getProperty("TranslationVector");
243 environmentMesh = reader->translate(environmentMesh, translationVector);
244
245 if (add) {
246 environment = std::make_unique<SampleEnvironment>(sample.getEnvironment());
247 environment->add(environmentMesh);
248 } else {
249 auto can = std::make_shared<Container>(environmentMesh);
250 std::string environmentName = getProperty("EnvironmentName");
251 environment = std::make_unique<SampleEnvironment>(environmentName, can);
252 }
253
254 debugString += "Environment has: " + std::to_string(environment->nelements()) + " elements.";
255 g_log.debug() << debugString;
256
257 // Put Environment into sample.
258 sample.setEnvironment(std::move(environment));
259
260 auto translatedVertices = environmentMesh->getVertices();
261 if (g_log.is(Logger::Priority::PRIO_DEBUG)) {
262 int i = 0;
263 for (double vertex : translatedVertices) {
264 i++;
265 g_log.debug(std::to_string(vertex));
266 if (i % 3 == 0) {
267 g_log.debug("\n");
268 }
269 }
270 }
271}
272
284 [[maybe_unused]] const std::string &filename,
285 [[maybe_unused]] Sample &sample, [[maybe_unused]] const bool add,
286 [[maybe_unused]] std::string &debugString) {
287#ifdef ENABLE_LIB3MF
288 std::unique_ptr<Geometry::SampleEnvironment> environment = nullptr;
289 Mantid3MFFileIO MeshLoader;
290 MeshLoader.LoadFile(filename);
291 std::shared_ptr<MeshObject> environmentMesh = nullptr;
292 std::string name = getProperty("EnvironmentName");
293 std::vector<std::shared_ptr<Geometry::MeshObject>> environmentMeshes;
294 std::shared_ptr<Geometry::MeshObject> sampleMesh;
295
296 MeshLoader.readMeshObjects(environmentMeshes, sampleMesh);
297
298 if (sampleMesh) {
299 // Baking the goniometer in moves the sample into the lab frame, so it is recorded - unlike the
300 // definition-frame rotation applied to the environment meshes below.
301 sampleMesh->bakeGoniometerRotation(inputWS->run().getGoniometer().getR());
302 sample.setShape(sampleMesh);
303 }
304
305 for (auto environmentMesh : environmentMeshes) {
306 if (!environment) {
307 if (add) {
308 environment = std::make_unique<SampleEnvironment>(sample.getEnvironment());
309 environment->add(environmentMesh);
310 } else {
311 auto can = std::make_shared<Container>(environmentMesh);
312 environment = std::make_unique<SampleEnvironment>(name, can);
313 }
314 } else {
315 environment->add(environmentMesh);
316 }
317
318 debugString += "Environment has: " + std::to_string(environment->nelements()) + " elements.";
319 }
320
321 // Put Environment into sample.
322 sample.setEnvironment(std::move(environment));
323#else
324 throw std::runtime_error("3MF format not supported on this platform");
325#endif
326}
327
329
330 MatrixWorkspace_const_sptr inputWS = getProperty("InputWorkspace");
331 MatrixWorkspace_sptr outputWS = getProperty("OutputWorkspace");
332
333 if (inputWS != outputWS) {
334 outputWS = inputWS->clone();
335 }
336
337 const std::string filename = getProperty("Filename");
338 const std::ifstream file(filename.c_str());
339 if (!file) {
340 g_log.error("Unable to open file: " + filename);
341 throw Exception::FileError("Unable to open file: ", filename);
342 }
343
344 const bool add = getProperty("Add");
345 std::string debugString;
346 Sample &sample = outputWS->mutableSample();
347
348 std::string fileExt = std::filesystem::path(filename).extension().string().substr(1); // remove the '.'
349
350 std::transform(fileExt.begin(), fileExt.end(), fileExt.begin(), toupper);
351
352 if (fileExt == "STL") {
353 loadEnvironmentFromSTL(filename, sample, add, debugString);
354 } else if (fileExt == "3MF") {
355 loadEnvironmentFrom3MF(inputWS, filename, sample, add, debugString);
356 } else {
357 throw "Invalid file extension";
358 }
359
360 // get the material name and number density for debug
361 const auto outMaterial = outputWS->sample().getEnvironment().getContainer().material();
362 debugString += "\n"
363 "Environment Material: " +
364 outMaterial.name();
365 debugString += "\n"
366 "Environment Material Number Density: " +
367 std::to_string(outMaterial.numberDensity());
368 // Set output workspace
369 setProperty("OutputWorkspace", outputWS);
370 g_log.debug(debugString);
371}
372
373} // namespace Mantid::DataHandling
#define DECLARE_ALGORITHM(classname)
Definition Algorithm.h:547
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.
Kernel::Logger & g_log
Definition Algorithm.h:426
@ OptionalLoad
to specify a file to read but the file doesn't have to exist
@ Load
allowed here which will be passed to the algorithm
This class stores information about the sample used in particular run.
Definition Sample.h:35
void setEnvironment(std::shared_ptr< Geometry::SampleEnvironment > env)
Set the environment used to contain the sample.
Definition Sample.cpp:192
const Geometry::SampleEnvironment & getEnvironment() const
Get a reference to the sample's environment.
Definition Sample.cpp:180
A property class for workspaces.
static bool isAsciiSTL(const std::string &filename)
static bool isBinarySTL(const std::string &filename)
void exec() override
Virtual method - must be overridden by concrete algorithm.
void loadEnvironmentFrom3MF(const API::MatrixWorkspace_const_sptr &inputWS, const std::string &filename, API::Sample &sample, const bool add, std::string &debugString)
Load a sample environment definition from a .3mf file.
void init() override
Virtual method - must be overridden by concrete algorithm.
const std::string name() const override
Algorithm's name for identification overriding a virtual method.
std::map< std::string, std::string > validateInputs() override
Perform validation of ALL the input properties of the algorithm.
void loadEnvironmentFromSTL(const std::string &filename, API::Sample &sample, const bool add, std::string debugString)
Load a sample environment definition from a .stl file.
Class to load and save .3mf files .3mf format is a 3D manufacturing format for storing mesh descripti...
void readMeshObjects(std::vector< MeshObject_sptr > &meshObjects, MeshObject_sptr &sample)
Read a set of mesh objects from the in memory lib3mf model object.
void LoadFile(std::string filename)
Load 3MF format file.
static ValidationErrors validateInputs(const MaterialParameters &params)
Validate the parameters to build the material from, this returns any errors in the inputs.
Support for a property that holds an array of values.
Records the filename and the description of failure.
Definition Exception.h:98
Records the filename, the description of failure and the line on which it happened.
Definition Exception.h:115
IPropertyManager * setProperty(const std::string &name, const T &value)
Templated method to set the value of a PropertyWithValue.
void setPropertySettings(const std::string &name, std::unique_ptr< IPropertySettings const > settings)
Add a PropertySettings instance to the chain of settings for a given property.
void setPropertyGroup(const std::string &name, const std::string &group)
Set the group for a given property.
void debug(const std::string &msg)
Logs at debug level.
Definition Logger.cpp:145
void error(const std::string &msg)
Logs at error level.
Definition Logger.cpp:108
bool is(int level) const
Returns true if at least the given log level is set.
Definition Logger.cpp:177
std::shared_ptr< const MatrixWorkspace > MatrixWorkspace_const_sptr
shared pointer to the matrix workspace base class (const version)
std::shared_ptr< MatrixWorkspace > MatrixWorkspace_sptr
shared pointer to the matrix workspace base class
ScaleUnits getScaleTypeFromStr(const std::string &scaleProperty)
Definition MeshFileIO.h:73
constexpr double EMPTY_DBL() noexcept
Returns what we consider an "empty" double within a property.
Definition EmptyValues.h:42
std::string to_string(const wide_integer< Bits, Signed > &n)
This struct contains the parameters for constructing a material, and gives them a default value for e...
double numberDensity
The sample number density to set, defaults to EMPTY_DBL()
double coherentXSection
The coherent scattering cross section to set, defaults to EMPTY_DBL()
int massNumber
The mass number to set, defaults to 0.
double attenuationXSection
The absorption cross section to set, defaults to EMPTY_DBL()
Kernel::MaterialBuilder::NumberDensityUnit numberDensityUnit
A flag indicating the unit of sampleNumberDensity.
double massDensity
The sample mass density to set, defaults to EMPTY_DBL()
double scatteringXSection
The total scattering cross section to set, defaults to EMPTY_DBL()
double incoherentXSection
The incoherent scattering cross section to set, defaults to EMPTY_DBL()
double zParameter
The zParameter to set, defaults to EMPTY_DBL()
std::string chemicalSymbol
The chemical formula to set, defaults to the empty string.
double unitCellVolume
The unit cell volume to set, defaults to EMPTY_DBL()
int atomicNumber
The atomic number to set, defaults to 0.
std::string attenuationProfileFileName
The name or path of a file containing an attenuation profile.
@ Input
An input workspace.
Definition Property.h:54
@ Output
An output workspace.
Definition Property.h:55