-
Notifications
You must be signed in to change notification settings - Fork 122
/
LoadPreNexusMonitors.cpp
266 lines (218 loc) · 9.26 KB
/
LoadPreNexusMonitors.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
// NScD Oak Ridge National Laboratory, European Spallation Source,
// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
// SPDX - License - Identifier: GPL - 3.0 +
#include "MantidDataHandling/LoadPreNexusMonitors.h"
#include "MantidAPI/Axis.h"
#include "MantidAPI/FileProperty.h"
#include "MantidAPI/MatrixWorkspace.h"
#include "MantidAPI/WorkspaceFactory.h"
#include "MantidKernel/BinaryFile.h"
#include "MantidKernel/ConfigService.h"
#include "MantidKernel/UnitFactory.h"
#include <boost/lexical_cast.hpp>
#include <memory>
#include <Poco/DOM/AutoPtr.h>
#include <Poco/DOM/DOMParser.h>
#include <Poco/DOM/Document.h>
#include <Poco/DOM/Element.h>
#include <Poco/DOM/NodeFilter.h>
#include <Poco/DOM/NodeIterator.h>
#include <Poco/DOM/NodeList.h>
#include <Poco/Path.h>
#include <Poco/SAX/InputSource.h>
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iterator>
using Mantid::HistogramData::BinEdges;
using Mantid::HistogramData::Counts;
namespace Mantid {
namespace DataHandling {
// Register the algorithm into the AlgorithmFactory
DECLARE_ALGORITHM(LoadPreNexusMonitors)
using namespace Mantid::Kernel;
using namespace Mantid::API;
// Some constants for property names
static const std::string RUNINFO_FILENAME("RunInfoFilename");
static const std::string WORKSPACE_OUT("OutputWorkspace");
// A reference to the logger is provided by the base class, it is called g_log.
// It is used to print out information, warning and error messages
LoadPreNexusMonitors::LoadPreNexusMonitors()
: Mantid::API::Algorithm(), nMonitors(0),
instrument_loaded_correctly(false) {}
void LoadPreNexusMonitors::init() {
// Filename for the runinfo file.
declareProperty(std::make_unique<FileProperty>(
RUNINFO_FILENAME, "", FileProperty::Load, "_runinfo.xml"),
"The filename of the runinfo file for a particular run. "
"Allowed Values are: _runinfo.xml");
// The output workspace
declareProperty(std::make_unique<WorkspaceProperty<MatrixWorkspace>>(
WORKSPACE_OUT, "", Direction::Output),
"The workspace to load the monitors into.");
// Make sure things are initialised.
nMonitors = 0;
}
void LoadPreNexusMonitors::exec() {
// time of flight channel parameters
double tmin = 0.0;
double tstep = 0.0;
int tchannels = 0;
std::string instrumentName;
// Vectors to store monitor parameters
std::vector<std::string> monitorFilenames;
std::vector<int> monitorIDs;
// Get the Runinfo filename from the property
std::string runinfo_filename = this->getPropertyValue(RUNINFO_FILENAME);
// TODO: Extract the directory that the runinfo file is in.
// Create a Poco Path object for runinfo filename
Poco::Path runinfoPath(runinfo_filename, Poco::Path::PATH_GUESS);
// Now lets get the directory
Poco::Path dirPath(runinfoPath.parent());
this->g_log.information("Monitor File Dir: " + dirPath.toString());
// Some XML parsing magic...
std::ifstream in(runinfo_filename.c_str());
Poco::XML::InputSource src(in);
Poco::XML::DOMParser parser;
Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parse(&src);
Poco::XML::NodeIterator it(pDoc, Poco::XML::NodeFilter::SHOW_ELEMENT);
Poco::XML::Node *pNode = it.nextNode();
while (pNode) {
// Get the beamline name.
if (pNode->nodeName() == "RunInfo") {
auto *pRunInfoElement = static_cast<Poco::XML::Element *>(pNode);
instrumentName = pRunInfoElement->getAttribute("instrument");
}
// Look for the section that contains the binning parameters.
// This will end up with using the binning for the last monitor that is
// found
// TODO: Modify to store (and use) the TCBs for each monitor separately.
if (pNode->nodeName() == "BeamMonitorInfo") {
// Increment the number of monitors we've found
++nMonitors;
auto *pE = static_cast<Poco::XML::Element *>(pNode);
g_log.debug() << "Beam Monitor " << pE->getAttribute("id") << '\n';
g_log.debug() << "\tname: " << pE->getAttribute("name") << '\n';
g_log.debug() << "\tdescription: " << pE->getAttribute("description")
<< '\n';
// Now lets get the tof binning settings
Poco::XML::Element *pTimeChannels =
pE->getChildElement("NumTimeChannels");
tmin =
boost::lexical_cast<double>(pTimeChannels->getAttribute("startbin"));
tstep = boost::lexical_cast<double>(pTimeChannels->getAttribute("width"));
}
// Look for the 'DataList' node to get the monitor dims.
// TODO: Again we will only use the mast monitor value.
if (pNode->nodeName() == "DataList") {
// Get a list of the child elements
Poco::AutoPtr<Poco::XML::NodeList> pDataListChildren =
pNode->childNodes();
for (unsigned long i = 0; i < pDataListChildren->length(); ++i) {
// We only care about monitors
if (pDataListChildren->item(i)->nodeName() == "monitor") {
auto *element =
static_cast<Poco::XML::Element *>(pDataListChildren->item(i));
monitorIDs.emplace_back(
boost::lexical_cast<int>(element->getAttribute("id")));
monitorFilenames.emplace_back(element->getAttribute("name"));
}
}
}
// Get the size of the files
if (pNode->nodeName() == "FileFormats") {
// Get a list of the child elements
Poco::AutoPtr<Poco::XML::NodeList> pDataListChildren =
pNode->childNodes();
for (unsigned long i = 0; i < pDataListChildren->length(); ++i) {
// We only care about monitors
if (pDataListChildren->item(i)->nodeName() == "monitor") {
std::string dims =
static_cast<Poco::XML::Element *>(pDataListChildren->item(i))
->getAttribute("dims");
tchannels = boost::lexical_cast<int>(dims);
}
}
}
pNode = it.nextNode();
}
g_log.information() << "Found " << nMonitors << " beam monitors.\n";
g_log.information() << "Number of Time Channels = " << tchannels << '\n';
// Now lets create the time of flight array.
const int numberTimeBins = tchannels + 1;
MantidVec time_bins(numberTimeBins);
for (int i = 0; i < numberTimeBins; ++i) {
time_bins[i] = tmin + (i)*tstep;
}
// Create the new workspace
MatrixWorkspace_sptr localWorkspace = WorkspaceFactory::Instance().create(
"Workspace2D", nMonitors, numberTimeBins, tchannels);
BinEdges edges(time_bins);
for (int i = 0; i < nMonitors; i++) {
// Now lets actually read the monitor files..
Poco::Path pMonitorFilename(dirPath, monitorFilenames[i]);
g_log.debug() << "Loading monitor file :" << pMonitorFilename.toString()
<< '\n';
Kernel::BinaryFile<uint32_t> monitorFile(pMonitorFilename.toString());
// temp buffer for file reading
std::vector<uint32_t> buffer = monitorFile.loadAllIntoVector();
localWorkspace->setHistogram(i, edges,
Counts(buffer.begin(), buffer.end()));
// Just have spectrum number be the same as the monitor number but -ve.
auto &spectrum = localWorkspace->getSpectrum(i);
spectrum.setSpectrumNo(monitorIDs[i]);
spectrum.setDetectorID(-monitorIDs[i]);
}
g_log.debug() << "Setting axis zero to TOF\n";
// Set the units
localWorkspace->getAxis(0)->unit() = UnitFactory::Instance().create("TOF");
localWorkspace->setYUnit("Counts");
// TODO localWorkspace->setTitle(title);
// Actually load the instrument
this->runLoadInstrument(instrumentName, localWorkspace);
// Set the property
setProperty("OutputWorkspace", localWorkspace);
}
//-----------------------------------------------------------------------------
/** Load the instrument geometry File
* @param instrument :: instrument name.
* @param localWorkspace :: MatrixWorkspace in which to put the instrument
* geometry
*/
void LoadPreNexusMonitors::runLoadInstrument(
const std::string &instrument, const MatrixWorkspace_sptr &localWorkspace) {
IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument");
// Now execute the Child Algorithm. Catch and log any error, but don't stop.
bool executionSuccessful(true);
try {
loadInst->setPropertyValue("InstrumentName", instrument);
loadInst->setProperty<MatrixWorkspace_sptr>("Workspace", localWorkspace);
loadInst->setProperty("RewriteSpectraMap",
false); // We have a custom mapping
loadInst->execute();
// Populate the instrument parameters in this workspace - this works around
// a bug
localWorkspace->populateInstrumentParameters();
} catch (std::invalid_argument &e) {
g_log.information()
<< "Invalid argument to LoadInstrument Child Algorithm : " << e.what()
<< '\n';
executionSuccessful = false;
} catch (std::runtime_error &e) {
g_log.information()
<< "Unable to successfully run LoadInstrument Child Algorithm : "
<< e.what() << '\n';
executionSuccessful = false;
}
// If loading instrument definition file fails
if (!executionSuccessful) {
g_log.error() << "Error loading Instrument definition file\n";
} else {
this->instrument_loaded_correctly = true;
}
}
} // namespace DataHandling
} // namespace Mantid