Mantid
Loading...
Searching...
No Matches
LoadDaveGrp.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#include "MantidAPI/Progress.h"
12#include "MantidAPI/Run.h"
18
19#include <algorithm>
20#include <vector>
21
22namespace Mantid::DataHandling {
24
25LoadDaveGrp::LoadDaveGrp() : ifile(), line(), nGroups(0), xLength(0) {}
26
34 const std::string &extn = descriptor.extension();
35 if (extn != ".grp" && extn != ".sqe" && extn != ".txt" && extn != ".dat")
36 return 0;
37
38 if (!descriptor.isAscii())
39 return 0;
40
41 bool daveGrp(false);
42 std::string curline;
43
44 // First line is a comment: #
45 std::getline(descriptor.data(), curline);
46 if (curline.substr(0, 1) == "#") {
47 daveGrp = true;
48 } else
49 return 0;
50
51 // Second line is an integer
52 std::getline(descriptor.data(), curline);
53 unsigned int value;
54 std::istringstream is(curline);
55 is >> value;
56 daveGrp = daveGrp && !is.fail();
57
58 // Third line is a comment: #
59 std::getline(descriptor.data(), curline);
60 if (curline.substr(0, 1) != "#")
61 return 0;
62
63 // Fourth line is an integer
64 std::getline(descriptor.data(), curline);
65 // Clear all stream bits regardless of what happened before
66 is.clear();
67 is.str(curline);
68 is >> value;
69 daveGrp = daveGrp && !is.fail();
70
71 if (daveGrp)
72 return 80;
73 else
74 return 0;
75}
76
78 std::vector<std::string> exts{".grp", ".sqe", ".txt", ".dat"};
79
80 declareProperty(std::make_unique<API::FileProperty>("Filename", "", API::FileProperty::Load, exts),
81 "A DAVE grouped ASCII file");
82 declareProperty(std::make_unique<API::WorkspaceProperty<>>("OutputWorkspace", "", Kernel::Direction::Output),
83 "The name of the workspace that will be created.");
84
85 // Extract the current contents of the UnitFactory to be the allowed values
86 // of the X-Axis property
87 auto allowedUnits = std::make_shared<Kernel::StringListValidator>(Kernel::UnitFactory::Instance().getKeys());
88 declareProperty("XAxisUnits", "DeltaE", allowedUnits,
89 "The name of the units for the X-Axis (must be one of "
90 "those registered in "
91 "the Unit Factory)");
92 // Extract the current contents of the UnitFactory to be the allowed values
93 // of the Y-Axis property
94 declareProperty("YAxisUnits", "MomentumTransfer", allowedUnits,
95 "The name of the units for the Y-Axis (must be one of "
96 "those registered in "
97 "the Unit Factory)");
99 "Original file is in units of micro-eV for DeltaE");
101 std::make_unique<Kernel::PropertyWithValue<bool>>("ConvertToHistogram", false, Kernel::Direction::Input),
102 "Convert output workspace to histogram data.");
103}
104
106 const std::string filename = getProperty("Filename");
107 std::vector<double> xAxis;
108 std::vector<double> yAxis;
109 API::MatrixWorkspace_sptr outputWorkspace;
110
111 ifile.open(filename.c_str());
112 if (ifile.is_open()) {
113 try {
114 // Size of x axis
116 // Size of y axis
118 } catch (boost::bad_lexical_cast &) {
119 throw std::runtime_error("LoadDaveGrp: Failed to parse axis length from file.");
120 }
121
122 outputWorkspace = setupWorkspace();
123 // Read in the x axis values
124 getAxisValues(xAxis, xLength);
125 // Read in the y axis values
126 getAxisValues(yAxis, nGroups);
127 // Read in the data
128 getData(outputWorkspace);
129
130 ifile.close();
131 } else {
132 throw std::runtime_error("LoadDaveGrp: Failed to open file.");
133 }
134
135 // Scale the x-axis if it is in micro-eV to get it to meV
136 const bool isUeV = getProperty("IsMicroEV");
137 if (isUeV)
138 std::transform(xAxis.cbegin(), xAxis.cend(), xAxis.begin(), [](const auto &value) { return value / 1000.0; });
139
140 setWorkspaceAxes(outputWorkspace, xAxis, yAxis);
141
142 // convert output workspace to histogram data
143 const bool convertToHistogram = getProperty("ConvertToHistogram");
144 if (convertToHistogram)
145 outputWorkspace = convertWorkspaceToHistogram(outputWorkspace);
146
147 outputWorkspace->mutableRun().addProperty("Filename", filename);
148 setProperty("OutputWorkspace", outputWorkspace);
149}
150
152 // Create workspace
153 API::MatrixWorkspace_sptr outputWorkspace = std::dynamic_pointer_cast<API::MatrixWorkspace>(
155 // Force the workspace to be a distribution
156 outputWorkspace->setDistribution(true);
157 // Set the x-axis units
158 outputWorkspace->getAxis(0)->unit() = Kernel::UnitFactory::Instance().create(getProperty("XAxisUnits"));
159
160 auto verticalAxis = std::make_unique<API::NumericAxis>(nGroups);
161 // Set the y-axis units
162 verticalAxis->unit() = Kernel::UnitFactory::Instance().create(getProperty("YAxisUnits"));
163
164 outputWorkspace->replaceAxis(1, std::move(verticalAxis));
165 return outputWorkspace;
166}
167
168void LoadDaveGrp::setWorkspaceAxes(const API::MatrixWorkspace_sptr &workspace, const std::vector<double> &xAxis,
169 const std::vector<double> &yAxis) const {
170
171 auto verticalAxis = workspace->getAxis(1);
172 auto sharedX = Kernel::make_cow<HistogramData::HistogramX>(xAxis);
173 for (size_t i = 0; i < nGroups; i++) {
174 workspace->setSharedX(i, sharedX);
175 verticalAxis->setValue(i, yAxis.at(i));
176 }
177}
178
180 auto convert2HistAlg = createChildAlgorithm("ConvertToHistogram");
181 convert2HistAlg->setProperty("InputWorkspace", workspace);
182 convert2HistAlg->setProperty("OutputWorkspace", workspace);
183 convert2HistAlg->execute();
184 workspace = convert2HistAlg->getProperty("OutputWorkspace");
185
186 auto convertFromDistAlg = createChildAlgorithm("ConvertFromDistribution");
187 convertFromDistAlg->setProperty("Workspace", workspace);
188 convertFromDistAlg->execute();
189
190 return workspace;
191}
192
193void LoadDaveGrp::readLine() { std::getline(ifile, line); }
194
195void LoadDaveGrp::getAxisLength(size_t &length) {
196 // Skip a comment line
197 readLine();
198 // Get the axis length from the file
199 readLine();
200 std::istringstream is(line);
201 std::string strLength;
202 is >> strLength;
203
204 length = boost::lexical_cast<size_t>(strLength);
205}
206
207void LoadDaveGrp::getAxisValues(std::vector<double> &axis, const std::size_t length) {
208 // Skip a comment line
209 readLine();
210 // Get the axis values from the file
211 double value;
212 for (std::size_t i = 0; i < length; i++) {
213 readLine();
214 std::istringstream is(line);
215 is >> value;
216 axis.emplace_back(value);
217 }
218}
219
221 double data_val = 0.0;
222 double err_val = 0.0;
223
224 API::Progress progress(this, 0.0, 1.0, nGroups);
225
226 for (size_t j = 0; j < nGroups; j++) {
227 // Skip the group comment line
228 readLine();
229 // Read the data block
230 auto &dataY = workspace->mutableY(j);
231 auto &dataE = workspace->mutableE(j);
232
233 for (std::size_t k = 0; k < xLength; k++) {
234 readLine();
235 std::istringstream is(line);
236 is >> data_val >> err_val;
237 dataY[k] = data_val;
238 dataE[k] = err_val;
239 }
240
241 progress.report();
242 }
243}
244
245} // namespace Mantid::DataHandling
double value
The value of the point.
Definition: FitMW.cpp:51
IPeaksWorkspace_sptr workspace
Definition: IndexPeaks.cpp:114
#define DECLARE_FILELOADER_ALGORITHM(classname)
DECLARE_FILELOADER_ALGORITHM should be used in place of the standard DECLARE_ALGORITHM macro when wri...
void declareProperty(std::unique_ptr< Kernel::Property > p, const std::string &doc="") override
Add a property to the list of managed properties.
Definition: Algorithm.cpp:1913
TypedValue getProperty(const std::string &name) const override
Get the value of a property.
Definition: Algorithm.cpp:2076
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.
Definition: Algorithm.cpp:842
void progress(double p, const std::string &msg="", double estimatedTime=0.0, int progressPrecision=0)
Sends ProgressNotification.
Definition: Algorithm.cpp:231
@ Load
allowed here which will be passed to the algorithm
Definition: FileProperty.h:52
Helper class for reporting progress from algorithms.
Definition: Progress.h:25
A property class for workspaces.
Reads the DAVE grouped ASCII format into a workspace.
Definition: LoadDaveGrp.h:54
void getData(const API::MatrixWorkspace_sptr &workspace)
Function to parse and store the signal and errors from the data file.
void getAxisLength(size_t &length)
Function to retrieve the lengths of the x and y axes.
API::MatrixWorkspace_sptr setupWorkspace() const
Function to setup the workspace ready for data to be loaded into it.
void exec() override
Execution code.
void readLine()
Function to read a line from the data file.
void setWorkspaceAxes(const API::MatrixWorkspace_sptr &workspace, const std::vector< double > &xAxis, const std::vector< double > &yAxis) const
Function to set the workspace axes.
std::string line
Placeholder for file lines.
Definition: LoadDaveGrp.h:138
void getAxisValues(std::vector< double > &axis, const std::size_t length)
Function to parse and store the actual axis values.
std::ifstream ifile
Handle for input data file.
Definition: LoadDaveGrp.h:136
API::MatrixWorkspace_sptr convertWorkspaceToHistogram(API::MatrixWorkspace_sptr workspace)
Convert a workspace to a histogram.
int confidence(Kernel::FileDescriptor &descriptor) const override
Returns a confidence value that this algorithm can load a file.
Definition: LoadDaveGrp.cpp:33
std::size_t nGroups
The number of groups present in the data file.
Definition: LoadDaveGrp.h:140
std::size_t xLength
The size of the x-axis in the data file.
Definition: LoadDaveGrp.h:142
void init() override
Initialization code.
Definition: LoadDaveGrp.cpp:77
Defines a wrapper around an open file.
static bool isAscii(const std::string &filename, const size_t nbytes=256)
Returns true if the file is considered ascii.
std::istream & data()
Access the open file stream.
const std::string & extension() const
Access the file extension.
IPropertyManager * setProperty(const std::string &name, const T &value)
Templated method to set the value of a PropertyWithValue.
The concrete, templated class for properties.
static T & Instance()
Return a reference to the Singleton instance, creating it if it does not already exist Creation is do...
std::shared_ptr< MatrixWorkspace > MatrixWorkspace_sptr
shared pointer to the matrix workspace base class
std::unique_ptr< T > create(const P &parent, const IndexArg &indexArg, const HistArg &histArg)
This is the create() method that all the other create() methods call.
@ Input
An input workspace.
Definition: Property.h:53
@ Output
An output workspace.
Definition: Property.h:54