Mantid
Loading...
Searching...
No Matches
SaveDiffCal.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 +
13#include "MantidNexus/H5Util.h"
14
15#include <H5Cpp.h>
16#include <filesystem>
17namespace Mantid::DataHandling {
18
30
31using namespace H5;
32using namespace Nexus;
33
34// Register the algorithm into the AlgorithmFactory
35DECLARE_ALGORITHM(SaveDiffCal)
36
37//----------------------------------------------------------------------------------------------
38
39
40const std::string SaveDiffCal::name() const { return "SaveDiffCal"; }
41
43int SaveDiffCal::version() const { return 1; }
44
46const std::string SaveDiffCal::category() const { return "DataHandling\\Instrument;Diffraction\\DataHandling"; }
47
49const std::string SaveDiffCal::summary() const { return "Saves a calibration file for powder diffraction"; }
50
51//----------------------------------------------------------------------------------------------
55 declareProperty(std::make_unique<WorkspaceProperty<ITableWorkspace>>("CalibrationWorkspace", "", Direction::Input,
57 "An output workspace.");
58
59 declareProperty(std::make_unique<WorkspaceProperty<GroupingWorkspace>>("GroupingWorkspace", "", Direction::Input,
61 "Optional: A GroupingWorkspace giving the grouping info.");
62
64 std::make_unique<WorkspaceProperty<MaskWorkspace>>("MaskWorkspace", "", Direction::Input, PropertyMode::Optional),
65 "Optional: A MaskWorkspace giving which detectors are masked.");
66
67 declareProperty(std::make_unique<FileProperty>("Filename", "", FileProperty::Save, ".h5"),
68 "Path to the .h5 file that will be created.");
69}
70
71std::map<std::string, std::string> SaveDiffCal::validateInputs() {
72 std::map<std::string, std::string> result;
73
74 ITableWorkspace_const_sptr calibrationWS = getProperty("CalibrationWorkspace");
75 if (bool(calibrationWS)) {
76 size_t numRows = calibrationWS->rowCount();
77 if (numRows == 0) {
78 result["CalibrationWorkspace"] = "Cannot save empty table";
79 } else {
80 GroupingWorkspace_const_sptr groupingWS = getProperty("GroupingWorkspace");
81 if (bool(groupingWS) && numRows < groupingWS->getNumberHistograms()) {
82 result["GroupingWorkspace"] = "Must have equal or less number of spectra as the table has rows";
83 }
84 MaskWorkspace_const_sptr maskWS = getProperty("MaskWorkspace");
85 if (bool(maskWS) && numRows < maskWS->getNumberHistograms()) {
86 result["MaskWorkspace"] = "Must have equal or less number of spectra as the table has rows";
87 }
88 }
89 } else {
90 GroupingWorkspace_const_sptr groupingWS = getProperty("GroupingWorkspace");
91 MaskWorkspace_const_sptr maskWS = getProperty("MaskWorkspace");
92
93 if ((!groupingWS) && (!maskWS)) {
94 const std::string msg("Failed to supply any input workspace");
95 result["CalibrationWorkspace"] = msg;
96 result["GroupingWorkspace"] = msg;
97 result["MaskWorkspace"] = msg;
98 }
99 }
100
101 return result;
102}
103
104void SaveDiffCal::writeDoubleFieldZeros(H5::Group &group, const std::string &name) {
105 std::vector<double> zeros(m_numValues, 0.);
107}
108
116void SaveDiffCal::writeDoubleFieldFromTable(H5::Group &group, const std::string &name) {
117 auto column = m_calibrationWS->getColumn(name);
118 // Retrieve only the first m_numValues, not necessarily the whole column
119 auto data = column->numeric_fill<>(m_numValues);
120
121 // if the field is optional, check if it is all zeros
122 if (name != "difc") {
123 bool allZeros = std::all_of(data.cbegin(), data.cend(), [](const auto &value) { return value == 0; });
124 if (allZeros)
125 return; // don't write the field
126 }
127
129}
130
138void SaveDiffCal::writeIntFieldFromTable(H5::Group &group, const std::string &name) {
139 auto column = m_calibrationWS->getColumn(name);
140 // Retrieve only the first m_numValues, not necessarily the whole column
141 auto data = column->numeric_fill<int32_t>(m_numValues);
143}
144
145/*
146 * Mantid::DataObjects::WorkspaceSingleValue/SpecialWorkspace2D is a parent to both GroupingWorkspace
147 * and MaskWorkspace
148 */
149void SaveDiffCal::writeDetIdsfromSVWS(H5::Group &group, const std::string &name,
151 if (!bool(ws))
152 throw std::runtime_error("Encountered null pointer in SaveDiffCal::writeDetIdsfromSVWS which should be impossible");
153
154 std::vector<int32_t> values;
155 for (size_t i = 0; i < m_numValues; ++i) {
156 const auto &detids = ws->getSpectrum(i).getDetectorIDs();
157 std::transform(detids.cbegin(), detids.cend(), std::back_inserter(values),
158 [](const auto &detid) { return static_cast<int32_t>(detid); });
159 }
160
162}
163
175void SaveDiffCal::writeIntFieldFromSVWS(H5::Group &group, const std::string &name,
177 const bool isMask = (name == "use");
178
179 // output array defaults to all one (one group, use the pixel)
180 std::vector<int32_t> values(m_numValues, 1);
181
182 if (bool(ws)) {
183 for (size_t i = 0; i < ws->getNumberHistograms(); ++i) {
184 auto &ids = ws->getSpectrum(i).getDetectorIDs(); // set of detector ID's
185 // check if the first detector ID in the set is in the calibration table
186 auto found = m_detidToIndex.find(*(ids.begin())); // (detID, row_index)
187 if (found != m_detidToIndex.end()) {
188 auto value = static_cast<int32_t>(ws->getValue(found->first));
189 // in maskworkspace 0=use, 1=dontuse - backwards from the file
190 if (isMask) {
191 if (value == 0)
192 value = 1; // thus "use" means a calibrated detector, good for use
193 else
194 value = 0;
195 }
196 for (const auto &indexes : found->second) {
197 values[indexes] = value;
198 }
199 }
200 }
201 }
202
204}
205
207 m_detidToIndex.clear();
208
209 auto detidCol = m_calibrationWS->getColumn("detid");
210 auto detids = detidCol->numeric_fill<detid_t>();
211
212 const size_t numDets = detids.size();
213 for (size_t i = 0; i < numDets; ++i) {
214 m_detidToIndex[static_cast<detid_t>(detids[i])].push_back(i);
215 }
216}
217
219 if (!bool(ws))
220 throw std::runtime_error(
221 "Encountered null pointer in SaveDiffCal::generateDetidToIndex which should be impossible");
222
223 m_detidToIndex.clear();
224
225 std::size_t index = 0;
226 for (size_t i = 0; i < m_numValues; ++i) {
227 const auto &detids = ws->getSpectrum(i).getDetectorIDs();
228 for (const auto &detid : detids) {
229 m_detidToIndex[static_cast<detid_t>(detid)].push_back(index);
230 index++;
231 }
232 }
233}
234
235bool SaveDiffCal::tableHasColumn(const std::string &ColumnName) const {
236 if (m_calibrationWS) {
237 const std::vector<std::string> names = m_calibrationWS->getColumnNames();
238 return std::any_of(names.cbegin(), names.cend(), [&ColumnName](const auto &name) { return name == ColumnName; });
239 } else {
240 return false;
241 }
242}
243
244//----------------------------------------------------------------------------------------------
248 m_calibrationWS = getProperty("CalibrationWorkspace");
249 GroupingWorkspace_sptr groupingWS = getProperty("GroupingWorkspace");
250 MaskWorkspace_const_sptr maskWS = getProperty("MaskWorkspace");
251
252 // Get a starting number of values to work with that will be refined below
253 // THE ORDER OF THE IF/ELSE TREE MATTERS
254 if (m_calibrationWS) {
255 m_numValues = m_calibrationWS->rowCount();
256 this->generateDetidToIndex();
257 } else if (groupingWS) {
258 m_numValues = groupingWS->getNumberHistograms();
259 this->generateDetidToIndex(groupingWS);
260 } else if (maskWS) {
261 m_numValues = maskWS->getNumberHistograms();
262 this->generateDetidToIndex(maskWS);
263 }
264
265 if (groupingWS && groupingWS->isDetectorIDMappingEmpty())
266 groupingWS->buildDetectorIDMapping();
267
268 // delete the file if it already exists
269 std::string filename = getProperty("Filename");
270 if (std::filesystem::exists(filename)) {
271 std::filesystem::remove(filename);
272 }
273
274 H5File file(filename, H5F_ACC_EXCL, Nexus::H5Util::defaultFileAcc());
275
276 auto calibrationGroup = H5Util::createGroupNXS(file, "calibration", "NXentry");
277
278 // write the d-spacing to TOF conversion parameters for the selected pixels
279 // as datasets under the NXentry group
280 if (m_calibrationWS) {
281 this->writeDoubleFieldFromTable(calibrationGroup, "difc");
282 this->writeDoubleFieldFromTable(calibrationGroup, "difa");
283 this->writeDoubleFieldFromTable(calibrationGroup, "tzero");
284 } else {
285 writeDoubleFieldZeros(calibrationGroup, "difc");
286 // LoadDiffCal will set difa and tzero to zero if they are missing
287 }
288
289 // add the detid from which ever of these exists
290 if (m_calibrationWS) {
291 this->writeIntFieldFromTable(calibrationGroup, "detid");
292 } else if (groupingWS) {
293 this->writeDetIdsfromSVWS(calibrationGroup, "detid", groupingWS);
294 } else if (maskWS) {
295 this->writeDetIdsfromSVWS(calibrationGroup, "detid", maskWS);
296 }
297
298 // the dasid is a legacy column that is not used by mantid but should be written if it exists
299 if (this->tableHasColumn("dasid")) // optional field
300 this->writeIntFieldFromTable(calibrationGroup, "dasid");
301 else
302 g_log.information("Not writing out values for \"dasid\"");
303
304 this->writeIntFieldFromSVWS(calibrationGroup, "group", groupingWS);
305 this->writeIntFieldFromSVWS(calibrationGroup, "use", maskWS);
306
307 // check if the input calibration table has an "offset" field
308 if (this->tableHasColumn("offset")) // optional field
309 this->writeDoubleFieldFromTable(calibrationGroup, "offset");
310 else
311 g_log.information("Not writing out values for \"offset\"");
312
313 // get the instrument information only if a GroupingWorkspace or
314 // MaskWorkspace is supplied by the user
315 std::string instrumentName;
316 std::string instrumentSource;
317 if (bool(groupingWS)) {
318 instrumentName = groupingWS->getInstrument()->getName();
319 instrumentSource = groupingWS->instrumentMetadata().filename();
320 }
321 if (bool(maskWS)) {
322 if (instrumentName.empty()) {
323 instrumentName = maskWS->getInstrument()->getName();
324 }
325 if (instrumentSource.empty()) {
326 instrumentSource = maskWS->instrumentMetadata().filename();
327 }
328 }
329 if (!instrumentSource.empty()) {
330 instrumentSource = std::filesystem::path(instrumentSource).filename().string();
331 }
332
333 // add the instrument information
334 auto instrumentGroup = calibrationGroup.createGroup("instrument");
335 H5Util::writeStrAttribute(instrumentGroup, "NX_class", "NXinstrument");
336 if (!instrumentName.empty()) {
337 H5Util::write(instrumentGroup, "name", instrumentName);
338 }
339 if (!instrumentSource.empty()) {
340 H5Util::write(instrumentGroup, "instrument_source", instrumentSource);
341 }
342
343 file.close();
344}
345
346} // namespace Mantid::DataHandling
std::string name
Definition Run.cpp:60
#define DECLARE_ALGORITHM(classname)
Definition Algorithm.h:542
double value
The value of the point.
Definition FitMW.cpp:51
std::map< DeltaEMode::Type, std::string > index
void declareProperty(std::unique_ptr< Kernel::Property > p, const std::string &doc="") override
Add a property to the list of managed properties.
TypedValue getProperty(const std::string &name) const override
Get the value of a property.
Kernel::Logger & g_log
Definition Algorithm.h:423
A specialized class for dealing with file properties.
@ Save
to specify a file to write to, the file may or may not exist
ITableWorkspace is an implementation of Workspace in which the data are organised in columns of same ...
A property class for workspaces.
SaveDiffCal : TODO: DESCRIPTION.
Definition SaveDiffCal.h:23
const std::string summary() const override
Algorithm's summary for use in the GUI and help.
std::map< detid_t, std::vector< size_t > > m_detidToIndex
Definition SaveDiffCal.h:52
void writeIntFieldFromTable(H5::Group &group, const std::string &name)
Create a dataset under a given group with a given name Use CalibrationWorkspace to retrieve the data.
API::ITableWorkspace_sptr m_calibrationWS
Definition SaveDiffCal.h:51
const std::string category() const override
Algorithm's category for identification.
void writeDoubleFieldFromTable(H5::Group &group, const std::string &name)
Create a dataset under a given group with a given name Use CalibrationWorkspace to retrieve the data.
int version() const override
Algorithm's version for identification.
void init() override
Initialize the algorithm's properties.
void writeDetIdsfromSVWS(H5::Group &group, const std::string &name, const DataObjects::SpecialWorkspace2D_const_sptr &ws)
void writeDoubleFieldZeros(H5::Group &group, const std::string &name)
const std::string name() const override
Algorithms name for identification.
bool tableHasColumn(const std::string &ColumnName) const
std::map< std::string, std::string > validateInputs() override
Perform validation of ALL the input properties of the algorithm.
void exec() override
Execute the algorithm.
void writeIntFieldFromSVWS(H5::Group &group, const std::string &name, const DataObjects::SpecialWorkspace2D_const_sptr &ws)
Create a dataset under a given group with a given name Use GroupingWorkspace or MaskWorkspace to retr...
A GroupingWorkspace is a subclass of Workspace2D where each spectrum has a single number entry,...
void information(const std::string &msg)
Logs at information level.
Definition Logger.cpp:136
std::shared_ptr< const ITableWorkspace > ITableWorkspace_const_sptr
shared pointer to Mantid::API::ITableWorkspace (const version)
std::shared_ptr< const GroupingWorkspace > GroupingWorkspace_const_sptr
shared pointer to a const GroupingWorkspace
std::shared_ptr< const SpecialWorkspace2D > SpecialWorkspace2D_const_sptr
shared pointer to a const SpecialWorkspace2D
std::shared_ptr< GroupingWorkspace > GroupingWorkspace_sptr
shared pointer to the GroupingWorkspace class
std::shared_ptr< const MaskWorkspace > MaskWorkspace_const_sptr
shared pointer to a const MaskWorkspace
void writeArray1D(H5::Group &group, const std::string &name, const std::vector< NumT > &values)
MANTID_NEXUS_DLL void writeStrAttribute(const H5::H5Object &object, const std::string &name, const std::string &value)
Definition H5Util.cpp:208
MANTID_NEXUS_DLL H5::FileAccPropList defaultFileAcc()
Default file access is H5F_CLOSE_STRONG.
Definition H5Util.cpp:119
MANTID_NEXUS_DLL H5::Group createGroupNXS(H5::H5File &file, const std::string &name, const std::string &nxtype)
MANTID_NEXUS_DLL void write(H5::Group &group, const std::string &name, const std::string &value)
int32_t detid_t
Typedef for a detector ID.
STL namespace.
Enumeration for a mandatory/optional property.
Describes the direction (within an algorithm) of a Property.
Definition Property.h:50
@ Input
An input workspace.
Definition Property.h:53