forked from npshub/mantid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NexusClasses.cpp
640 lines (578 loc) · 19.6 KB
/
NexusClasses.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
// 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 +
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include "MantidNexus/NexusClasses.h"
#include <memory>
#include <utility>
namespace Mantid::NeXus {
std::vector<std::string> NXAttributes::names() const {
std::vector<std::string> out;
out.reserve(m_values.size());
std::transform(m_values.cbegin(), m_values.cend(), std::back_inserter(out),
[](const auto &value) { return value.first; });
return out;
}
std::vector<std::string> NXAttributes::values() const {
std::vector<std::string> out;
out.reserve(m_values.size());
std::transform(m_values.cbegin(), m_values.cend(), std::back_inserter(out),
[](const auto &value) { return value.second; });
return out;
}
/** Returns the value of an attribute
* @param name :: The name of the attribute
* @return The value of the attribute if it exists or an empty string
* otherwise
*/
std::string NXAttributes::operator()(const std::string &name) const {
auto it = m_values.find(name);
if (it == m_values.end())
return "";
return it->second;
}
/** Sets the value of the attribute.
* @param name :: The name of the attribute
* @param value :: The new value of the attribute
*/
void NXAttributes::set(const std::string &name, const std::string &value) { m_values[name] = value; }
/** Sets the value of the attribute as a double.
* @param name :: The name of the attribute
* @param value :: The new value of the attribute
*/
void NXAttributes::set(const std::string &name, double value) {
std::ostringstream ostr;
ostr << value;
m_values[name] = ostr.str();
}
//---------------------------------------------------------
// NXObject methods
//---------------------------------------------------------
/** NXObject constructor.
* @param fileID :: The Nexus file id
* @param parent :: The parent Nexus class. In terms of HDF it is the group
* containing the object.
* @param name :: The name of the object relative to its parent
*/
NXObject::NXObject(const NXhandle fileID, const NXClass *parent, const std::string &name)
: m_fileID(fileID), m_open(false) {
if (parent && !name.empty()) {
m_path = parent->path() + "/" + name;
}
}
std::string NXObject::name() const {
size_t i = m_path.find_last_of('/');
if (i == std::string::npos)
return m_path;
else
return m_path.substr(i + 1, m_path.size() - i - 1);
}
/** Reads in attributes
*/
void NXObject::getAttributes() {
NXname pName;
int iLength, iType;
#ifndef NEXUS43
int rank;
int dims[4];
#endif
std::vector<char> buff(128);
#ifdef NEXUS43
while (NXgetnextattr(m_fileID, pName, &iLength, &iType) != NX_EOD) {
#else
while (NXgetnextattra(m_fileID, pName, &rank, dims, &iType) != NX_EOD) {
#endif
#ifndef NEXUS43
if (rank > 1) { // mantid only supports single value attributes
throw std::runtime_error("Encountered attribute with multi-dimensional array value");
}
iLength = dims[0]; // to clarify things
if (iType != NX_CHAR && iLength != 1) {
throw std::runtime_error("Encountered attribute with array value");
}
#endif
switch (iType) {
case NX_CHAR: {
if (iLength >= 0 && (unsigned)iLength > buff.size()) {
buff.resize(iLength);
}
int nz = iLength + 1;
NXgetattr(m_fileID, pName, buff.data(), &nz, &iType);
attributes.set(pName, buff.data());
break;
}
case NX_INT16: {
short int value;
NXgetattr(m_fileID, pName, &value, &iLength, &iType);
sprintf(buff.data(), "%i", value);
attributes.set(pName, buff.data());
break;
}
case NX_INT32: {
int value;
NXgetattr(m_fileID, pName, &value, &iLength, &iType);
sprintf(buff.data(), "%i", value);
attributes.set(pName, buff.data());
break;
}
case NX_UINT16: {
short unsigned int value;
NXgetattr(m_fileID, pName, &value, &iLength, &iType);
sprintf(buff.data(), "%u", value);
attributes.set(pName, buff.data());
break;
}
}
};
}
//---------------------------------------------------------
// NXClass methods
//---------------------------------------------------------
NXClass::NXClass(const NXClass &parent, const std::string &name) : NXObject(parent.m_fileID, &parent, name) { clear(); }
NXClassInfo NXClass::getNextEntry() {
NXClassInfo res;
char nxname[NX_MAXNAMELEN], nxclass[NX_MAXNAMELEN];
res.stat = NXgetnextentry(m_fileID, nxname, nxclass, &res.datatype);
if (res) // Check if previous call was successful
{
res.nxname = nxname;
res.nxclass = nxclass;
}
return res;
}
void NXClass::readAllInfo() {
clear();
NXClassInfo info;
while ((info = getNextEntry())) {
if (info.nxclass == "SDS") {
NXInfo data_info;
NXopendata(m_fileID, info.nxname.c_str());
data_info.stat = NXgetinfo(m_fileID, &data_info.rank, data_info.dims, &data_info.type);
NXclosedata(m_fileID);
data_info.nxname = info.nxname;
m_datasets->emplace_back(data_info);
} else if (info.nxclass.substr(0, 2) == "NX" || info.nxclass.substr(0, 2) == "IX") {
m_groups->emplace_back(info);
}
}
reset();
}
bool NXClass::isValid(const std::string &path) const {
if (NXopengrouppath(m_fileID, path.c_str()) == NX_OK) {
NXclosegroup(m_fileID);
return true;
} else
return false;
}
void NXClass::open() {
if (NX_ERROR == NXopengrouppath(m_fileID, m_path.c_str())) {
throw std::runtime_error("Cannot open group " + name() + " of class " + NX_class() + " (trying to open path " +
m_path + ")");
}
//}
m_open = true;
readAllInfo();
}
/** It is fast, but the parent of this class must be open at
* the time of calling. openNXClass uses open() (the slow one). To open calss
* using openLocal() do:
* NXTheClass class(parent,name);
* class.openLocal();
* // work with class
* class.close();
* @param nxclass :: The NX class name. If empty NX_class() will be used
* @return true if OK
*/
bool NXClass::openLocal(const std::string &nxclass) {
std::string className = nxclass.empty() ? NX_class() : nxclass;
if (NX_ERROR == NXopengroup(m_fileID, name().c_str(), className.c_str())) {
// It would be nice if this worked
// if (NX_ERROR == NXopengrouppath(m_fileID,m_path.c_str()))
//{
// throw std::runtime_error("Cannot open group "+m_path+" of class
// "+NX_class());
//}
return false;
}
m_open = true;
readAllInfo();
return true;
}
void NXClass::close() {
if (NX_ERROR == NXclosegroup(m_fileID)) {
throw std::runtime_error("Cannot close group " + name() + " of class " + NX_class() + " (trying to close path " +
m_path + ")");
}
m_open = false;
}
void NXClass::reset() { NXinitgroupdir(m_fileID); }
void NXClass::clear() {
m_groups.reset(new std::vector<NXClassInfo>);
m_datasets.reset(new std::vector<NXInfo>);
}
std::string NXClass::getString(const std::string &name) const {
NXChar buff = openNXChar(name);
try {
buff.load();
return std::string(buff(), buff.dim0());
} catch (std::runtime_error &) {
// deals with reading uninitialized/empty data
return std::string();
}
}
double NXClass::getDouble(const std::string &name) const {
NXDouble number = openNXDouble(name);
number.load();
return *number();
}
float NXClass::getFloat(const std::string &name) const {
NXFloat number = openNXFloat(name);
number.load();
return *number();
}
int NXClass::getInt(const std::string &name) const {
NXInt number = openNXInt(name);
number.load();
return *number();
}
/** Returns whether an individual group (or group) is present
* @param query :: the class name to search for
* @return true if the name is found and false otherwise
*/
bool NXClass::containsGroup(const std::string &query) const {
std::vector<NXClassInfo>::const_iterator end = m_groups->end();
for (std::vector<NXClassInfo>::const_iterator i = m_groups->begin(); i != end; ++i) {
if (i->nxname == query) {
return true;
}
}
return false;
}
/**
* Returns NXInfo for a dataset
* @param name :: The name of the dataset
* @return NXInfo::stat is set to NX_ERROR if the dataset does not exist
*/
NXInfo NXClass::getDataSetInfo(const std::string &name) const {
NXInfo info;
for (std::vector<NXInfo>::const_iterator it = datasets().begin(); it != datasets().end(); ++it) {
if (it->nxname == name)
return *it;
}
info.stat = NX_ERROR;
return info;
}
/**
* Returns whether an individual dataset is present.
*/
bool NXClass::containsDataSet(const std::string &query) const { return getDataSetInfo(query).stat != NX_ERROR; }
//---------------------------------------------------------
// NXNote methods
//---------------------------------------------------------
std::string NXNote::author() {
if (!m_author_ok) {
NXChar aut = openNXChar("author");
aut.load();
m_author = std::string(aut(), aut.dim0());
m_author_ok = true;
}
return m_author;
}
std::vector<std::string> &NXNote::data() {
if (!m_data_ok) {
int rank;
int dims[4];
int type;
NXopendata(m_fileID, "data");
NXgetinfo(m_fileID, &rank, dims, &type);
int n = dims[0];
auto buffer = new char[n];
NXstatus stat = NXgetdata(m_fileID, buffer);
NXclosedata(m_fileID);
m_data.clear();
if (stat == NX_ERROR) {
delete[] buffer;
return m_data;
}
std::istringstream istr(std::string(buffer, n));
delete[] buffer;
std::string line;
while (getline(istr, line)) {
m_data.emplace_back(line);
}
m_data_ok = true;
}
return m_data;
}
std::string NXNote::description() {
if (!m_description_ok) {
NXChar str = openNXChar("description");
str.load();
m_description = std::string(str(), str.dim0());
m_description_ok = true;
}
return m_description;
}
std::vector<char> &NXBinary::binary() {
if (!m_data_ok) {
int rank;
int dims[4];
int type;
NXopendata(m_fileID, "data");
NXgetinfo(m_fileID, &rank, dims, &type);
int n = dims[0];
m_binary.resize(n);
NXstatus stat = NXgetdata(m_fileID, &m_binary[0]);
(void)stat; // Avoid unused variable compiler warning
NXclosedata(m_fileID);
}
return m_binary;
}
//---------------------------------------------------------
// NXRoot methods
//---------------------------------------------------------
/** Constructor. On creation opens the Nexus file for reading only.
* @param fname :: The file name to open
*/
NXRoot::NXRoot(std::string fname) : m_filename(std::move(fname)) {
// Open NeXus file
NXstatus stat = NXopen(m_filename.c_str(), NXACC_READ, &m_fileID);
if (stat == NX_ERROR) {
std::cout << "NXRoot: Error loading " << m_filename;
throw Kernel::Exception::FileError("Unable to open File:", m_filename);
}
readAllInfo();
}
/** Constructor.
* Creates a new Nexus file. The first root entry will be also created.
* @param fname :: The file name to create
* @param entry :: The name of the first entry in the new file
*/
NXRoot::NXRoot(std::string fname, const std::string &entry) : m_filename(std::move(fname)) {
(void)entry;
// Open NeXus file
NXstatus stat = NXopen(m_filename.c_str(), NXACC_CREATE5, &m_fileID);
if (stat == NX_ERROR) {
throw Kernel::Exception::FileError("Unable to open File:", m_filename);
}
}
NXRoot::~NXRoot() { NXclose(&m_fileID); }
bool NXRoot::isStandard() const { return true; }
/**
* Open the first NXentry in the file.
*/
NXEntry NXRoot::openFirstEntry() {
if (groups().empty()) {
throw std::runtime_error("NeXus file has no entries");
}
for (std::vector<NXClassInfo>::const_iterator grp = groups().begin(); grp != groups().end(); ++grp) {
if (grp->nxclass == "NXentry") {
return openEntry(grp->nxname);
}
}
throw std::runtime_error("NeXus file has no entries");
}
//---------------------------------------------------------
// NXDataSet methods
//---------------------------------------------------------
/** Constructor.
* @param parent :: The parent Nexus class. In terms of HDF it is the group
* containing the dataset.
* @param name :: The name of the dataset relative to its parent
*/
NXDataSet::NXDataSet(const NXClass &parent, const std::string &name) : NXObject(parent.m_fileID, &parent, name) {
size_t i = name.find_last_of('/');
if (i == std::string::npos)
m_info.nxname = name;
else if (name.empty() || i == name.size() - 1)
throw std::runtime_error("Improper dataset name " + name);
else
m_info.nxname = name.substr(i + 1);
}
// Opens the data set. Does not read in any data. Call load(...) to load the
// data
void NXDataSet::open() {
size_t i = m_path.find_last_of('/');
if (i == std::string::npos || i == 0)
return; // we are in the root group, assume it is open
std::string group_path = m_path.substr(0, i);
if (NX_ERROR == NXopenpath(m_fileID, group_path.c_str())) {
throw std::runtime_error("Cannot open dataset " + m_path);
}
if (NXopendata(m_fileID, name().c_str()) != NX_OK) {
throw std::runtime_error("Error opening data in group \"" + name() + "\"");
}
if (NXgetinfo(m_fileID, &m_info.rank, m_info.dims, &m_info.type) != NX_OK) {
throw std::runtime_error("Error retrieving information for " + name() + " group");
}
getAttributes();
NXclosedata(m_fileID);
}
void NXDataSet::openLocal() {
if (NXopendata(m_fileID, name().c_str()) != NX_OK) {
throw std::runtime_error("Error opening data in group \"" + name() + "\"");
}
if (NXgetinfo(m_fileID, &m_info.rank, m_info.dims, &m_info.type) != NX_OK) {
throw std::runtime_error("Error retrieving information for " + name() + " group");
}
getAttributes();
NXclosedata(m_fileID);
}
/**
* The size of the first dimension of data
* @returns An integer indicating the size of the dimension.
* @throws out_of_range error if requested on an object of rank 0
*/
int NXDataSet::dim0() const {
if (m_info.rank == 0) {
throw std::out_of_range("NXDataSet::dim0() - Requested dimension greater than rank.");
}
return m_info.dims[0];
}
/**
* The size of the second dimension of data
* @returns An integer indicating the size of the dimension
* @throws out_of_range error if requested on an object of rank < 2
*/
int NXDataSet::dim1() const {
if (m_info.rank < 2) {
throw std::out_of_range("NXDataSet::dim1() - Requested dimension greater than rank.");
}
return m_info.dims[1];
}
/**
* The size of the third dimension of data
* @returns An integer indicating the size of the dimension
* @throws out_of_range error if requested on an object of rank < 3
*/
int NXDataSet::dim2() const {
if (m_info.rank < 3) {
throw std::out_of_range("NXDataSet::dim2() - Requested dimension greater than rank.");
}
return m_info.dims[2];
}
/**
* The size of the fourth dimension of data
* @returns An integer indicating the size of the dimension
* @throws out_of_range error if requested on an object of rank < 4
*/
int NXDataSet::dim3() const {
if (m_info.rank < 4) {
throw std::out_of_range("NXDataSet::dim3() - Requested dimension greater than rank.");
}
return m_info.dims[3];
}
/** Wrapper to the NXgetdata.
* @param data :: The pointer to the buffer accepting the data from the file.
* @throw runtime_error if the operation fails.
*/
void NXDataSet::getData(void *data) {
NXopendata(m_fileID, name().c_str());
if (NXgetdata(m_fileID, data) != NX_OK)
throw std::runtime_error("Cannot read data from NeXus file");
NXclosedata(m_fileID);
}
/** Wrapper to the NXgetslab.
* @param data :: The pointer to the buffer accepting the data from the file.
* @param start :: The array of starting indeces to read in from the file. The
* size of the array must be equal to
* the rank of the data.
* @param size :: The array of numbers of data elements to read along each
* dimenstion.
* The number of dimensions (the size of the array) must be equal to
* the rank of the data.
* @throw runtime_error if the operation fails.
*/
void NXDataSet::getSlab(void *data, int start[], int size[]) {
NXopendata(m_fileID, name().c_str());
if (NXgetslab(m_fileID, data, start, size) != NX_OK)
throw std::runtime_error("Cannot read data slab from NeXus file");
NXclosedata(m_fileID);
}
//---------------------------------------------------------
// NXData methods
//---------------------------------------------------------
NXData::NXData(const NXClass &parent, const std::string &name) : NXMainClass(parent, name) {}
//---------------------------------------------------------
// NXLog methods
//---------------------------------------------------------
/** Creates a property wrapper around the log entry
* @returns A valid property pointer or NULL
*/
Kernel::Property *NXLog::createProperty() {
NXInfo vinfo = getDataSetInfo("time");
if (vinfo.stat == NX_ERROR) {
return createSingleValueProperty();
} else {
return createTimeSeries();
}
}
/** Creates a single value property of the log
* @returns A pointer to a newly created property wrapped around the log entry
*/
Kernel::Property *NXLog::createSingleValueProperty() {
const std::string valAttr("value");
NXInfo vinfo = getDataSetInfo(valAttr);
Kernel::Property *prop;
int nxType = vinfo.type;
if (nxType == NX_FLOAT64) {
prop = new Kernel::PropertyWithValue<double>(name(), getDouble(valAttr));
} else if (nxType == NX_INT32) {
prop = new Kernel::PropertyWithValue<int>(name(), getInt(valAttr));
} else if (nxType == NX_CHAR) {
prop = new Kernel::PropertyWithValue<std::string>(name(), getString(valAttr));
} else if (nxType == NX_UINT8) {
NXDataSetTyped<unsigned char> value(*this, valAttr);
value.load();
bool state = value[0] != 0;
prop = new Kernel::PropertyWithValue<bool>(name(), state);
} else {
prop = nullptr;
}
return prop;
}
/** createTimeSeries
* Create a TimeSeries property form the records of the NXLog group. Times are
* in dataset "time"
* and the values are in dataset "value"
* @param start_time :: If the "time" dataset does not have the "start"
* attribute sets the
* start time for the series.
* @param new_name :: If not empty it is used as the TimeSeries property name
* @return The property or NULL
*/
Kernel::Property *NXLog::createTimeSeries(const std::string &start_time, const std::string &new_name) {
const std::string &logName = new_name.empty() ? name() : new_name;
NXInfo vinfo = getDataSetInfo("time");
if (vinfo.type == NX_FLOAT64) {
NXDouble times(*this, "time");
times.openLocal();
times.load();
std::string units = times.attributes("units");
if (units == "minutes") {
using std::placeholders::_1;
std::transform(times(), times() + times.dim0(), times(), std::bind(std::multiplies<double>(), _1, 60));
} else if (!units.empty() && units.substr(0, 6) != "second") {
return nullptr;
}
return parseTimeSeries(logName, times, start_time);
} else if (vinfo.type == NX_FLOAT32) {
NXFloat times(*this, "time");
times.openLocal();
times.load();
std::string units = times.attributes("units");
if (units == "minutes") {
std::for_each(times(), times() + times.dim0(), [](float &val) { val *= 60.0f; });
} else if (!units.empty() && units.substr(0, 6) != "second") {
return nullptr;
}
return parseTimeSeries(logName, times, start_time);
}
return nullptr;
}
} // namespace Mantid::NeXus