LoadMuonNexus2.cpp 18.3 KB
Newer Older
1
2
3
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
4
5
//   NScD Oak Ridge National Laboratory, European Spallation Source,
//   Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6
// SPDX - License - Identifier: GPL - 3.0 +
7
#include "MantidDataHandling/LoadMuonNexus2.h"
8
#include "MantidAPI/Axis.h"
9
#include "MantidAPI/FileProperty.h"
10
#include "MantidAPI/Progress.h"
11
#include "MantidAPI/RegisterFileLoader.h"
12
#include "MantidAPI/Run.h"
13
#include "MantidAPI/WorkspaceFactory.h"
14
#include "MantidAPI/WorkspaceGroup.h"
15
#include "MantidDataHandling/LoadMuonNexus1.h"
Stephen's avatar
Stephen committed
16
#include "MantidDataHandling/LoadMuonNexusV2.h"
17
#include "MantidDataObjects/Workspace2D.h"
18
19
#include "MantidGeometry/Instrument/Detector.h"
#include "MantidKernel/ArrayProperty.h"
20
#include "MantidKernel/ConfigService.h"
21
#include "MantidKernel/DateAndTimeHelpers.h"
22
#include "MantidKernel/TimeSeriesProperty.h"
23
#include "MantidKernel/Unit.h"
24
#include "MantidKernel/UnitFactory.h"
25
#include "MantidKernel/UnitLabelTypes.h"
26
#include "MantidNexus/NexusClasses.h"
Campbell, Stuart's avatar
Campbell, Stuart committed
27
#include <Poco/Path.h>
28
#include <memory>
29
// clang-format off
30
#include <nexus/NeXusFile.hpp>
31
#include <nexus/NeXusException.hpp>
32
// clang-format on
33
34

#include <cmath>
35
#include <numeric>
36

37
using Mantid::Types::Core::DateAndTime;
38

39
40
41
namespace Mantid {
namespace DataHandling {
// Register the algorithm into the algorithm factory
42
DECLARE_NEXUS_FILELOADER_ALGORITHM(LoadMuonNexus2)
43
44

using namespace Kernel;
45
using namespace DateAndTimeHelpers;
46
47
using namespace API;
using Geometry::Instrument;
LamarMoore's avatar
LamarMoore committed
48
using Mantid::HistogramData::BinEdges;
49
50
using Mantid::HistogramData::Counts;
using Mantid::HistogramData::Histogram;
51
using namespace Mantid::NeXus;
52
using Mantid::Types::Core::DateAndTime;
53

54
55
56
57
58
59
namespace {
inline std::string getLoadAlgName(int confidence1, int confidenceV2) {
  return confidence1 > confidenceV2 ? "LoadMuonNexus" : "LoadMuonNexusV2";
}
} // namespace

60
61
62
/// Empty default constructor
LoadMuonNexus2::LoadMuonNexus2() : LoadMuonNexus() {}

63
/** Executes the right version of the Muon nexus loader
LamarMoore's avatar
LamarMoore committed
64
65
66
67
 *  @throw Exception::FileError If the Nexus file cannot be found/opened
 *  @throw std::invalid_argument If the optional properties are set to invalid
 *values
 */
68
69
void LoadMuonNexus2::exec() {
  LoadMuonNexus1 load1;
70
  LoadMuonNexusV2 loadV2;
71
  load1.initialize();
72
  loadV2.initialize();
73

74
  std::string filePath = getPropertyValue("Filename");
75
76
77
  Kernel::NexusDescriptor descriptor(filePath);
  int confidence1 = load1.confidence(descriptor);
  int confidence2 = this->confidence(descriptor);
78
79
80
81
82
83
84
85
  int confidenceV2 = 0;
  // If the file is hdf5 then we can possibly use LoadMuonNexusV2
  // To check this we'll have to create an HDF5 descriptor for the file.
  if (Kernel::NexusDescriptor::isReadable(filePath,
                                          Kernel::NexusDescriptor::Version5)) {
    Kernel::NexusHDF5Descriptor descriptorHDF5(filePath);
    confidenceV2 = loadV2.confidence(descriptorHDF5);
  };
86
87

  // if none can load the file throw
88
  if (confidence1 < 80 && confidence2 < 80 && confidenceV2 < 80) {
89
90
    throw Kernel::Exception::FileError("Cannot open the file ", filePath);
  }
91
92
93
  // Now pick the correct alg
  if (confidence2 > std::max(confidence1, confidenceV2)) {
    // Use this loader
94
95
    doExec();
  } else {
96
97
98
99
100
101
102
103
    // Version 1 or V2
    IAlgorithm_sptr childAlg = createChildAlgorithm(
        getLoadAlgName(confidence1, confidenceV2), 0, 1, true, 1);
    auto loader = std::dynamic_pointer_cast<API::Algorithm>(childAlg);
    loader->copyPropertiesFrom(*this);
    loader->executeAsChildAlg();
    this->copyPropertiesFrom(*loader);
    API::Workspace_sptr outWS = loader->getProperty("OutputWorkspace");
104
105
106
107
108
    setProperty("OutputWorkspace", outWS);
  }
}

/** Read in a muon nexus file of the version 2.
LamarMoore's avatar
LamarMoore committed
109
110
111
112
113
 *
 *  @throw Exception::FileError If the Nexus file cannot be found/opened
 *  @throw std::invalid_argument If the optional properties are set to invalid
 *values
 */
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
void LoadMuonNexus2::doExec() {
  // Create the root Nexus class
  NXRoot root(getPropertyValue("Filename"));

  int64_t iEntry = getProperty("EntryNumber");
  if (iEntry >= static_cast<int64_t>(root.groups().size())) {
    throw std::invalid_argument("EntryNumber is out of range");
  }

  // Open the data entry
  m_entry_name = root.groups()[iEntry].nxname;
  NXEntry entry = root.openEntry(m_entry_name);

  // Read in the instrument name from the Nexus file
  m_instrument_name = entry.getString("instrument/name");

  // Read the number of periods in this file
  if (entry.containsGroup("run")) {
    try {
      m_numberOfPeriods = entry.getInt("run/number_periods");
    } catch (::NeXus::Exception &) {
      // assume 1
      m_numberOfPeriods = 1;
137
    }
138
139
140
141
142
143
144
145
  } else {
    m_numberOfPeriods = 1;
  }

  // Need to extract the user-defined output workspace name
  Property *ws = getProperty("OutputWorkspace");
  std::string localWSName = ws->value();
  // If multiperiod, will need to hold the Instrument & Sample for copying
146
147
  std::shared_ptr<Instrument> instrument;
  std::shared_ptr<Sample> sample;
148
149
150

  std::string detectorName;
  // Only the first NXdata found
Hahn, Steven's avatar
Hahn, Steven committed
151
152
  for (auto &group : entry.groups()) {
    std::string className = group.nxclass;
153
    if (className == "NXdata") {
Hahn, Steven's avatar
Hahn, Steven committed
154
      detectorName = group.nxname;
155
      break;
156
    }
157
158
159
160
161
162
163
  }
  NXData dataGroup = entry.openNXData(detectorName);

  Mantid::NeXus::NXInt spectrum_index = dataGroup.openNXInt("spectrum_index");
  spectrum_index.load();
  m_numberOfSpectra = spectrum_index.dim0();

164
165
166
  // Load detector mapping
  const auto &detMapping = loadDetectorMapping(spectrum_index);

167
168
169
170
171
172
173
174
  // Call private method to validate the optional parameters, if set
  checkOptionalProperties();

  NXFloat raw_time = dataGroup.openNXFloat("raw_time");
  raw_time.load();
  int nBins = raw_time.dim0();
  std::vector<double> timeBins;
  timeBins.assign(raw_time(), raw_time() + nBins);
175
  timeBins.emplace_back(raw_time[nBins - 1] + raw_time[1] - raw_time[0]);
176
177
178
179
180
181
182
183
184
185

  // Calculate the size of a workspace, given its number of periods & spectra to
  // read
  int total_specs;
  if (m_interval || m_list) {
    total_specs = static_cast<int>(m_spec_list.size());
    if (m_interval) {
      total_specs += static_cast<int>((m_spec_max - m_spec_min + 1));
    } else {
      m_spec_max = -1; // to stop entering the min - max loop
186
    }
187
188
189
190
191
192
193
194
195
  } else {
    total_specs = static_cast<int>(m_numberOfSpectra);
    // for nexus return all spectra
    m_spec_min = 1;
    m_spec_max = m_numberOfSpectra; // was +1?
  }

  // Create the 2D workspace for the output
  DataObjects::Workspace2D_sptr localWorkspace =
196
      std::dynamic_pointer_cast<DataObjects::Workspace2D>(
197
198
199
200
          WorkspaceFactory::Instance().create("Workspace2D", total_specs,
                                              nBins + 1, nBins));
  // Set the unit on the workspace to muon time, for now in the form of a Label
  // Unit
201
202
  std::shared_ptr<Kernel::Units::Label> lblUnit =
      std::dynamic_pointer_cast<Kernel::Units::Label>(
203
204
205
206
207
208
          UnitFactory::Instance().create("Label"));
  lblUnit->setLabel("Time", Units::Symbol::Microsecond);
  localWorkspace->getAxis(0)->unit() = lblUnit;
  // Set y axis unit
  localWorkspace->setYUnit("Counts");

209
  // g_log.error()<<" number of perioids= "<<m_numberOfPeriods<<'\n';
210
211
212
213
214
215
216
217
218
219
220
  WorkspaceGroup_sptr wsGrpSptr = WorkspaceGroup_sptr(new WorkspaceGroup);
  if (entry.containsDataSet("title")) {
    wsGrpSptr->setTitle(entry.getString("title"));
  }

  if (entry.containsDataSet("notes")) {
    wsGrpSptr->setComment(entry.getString("notes"));
  }

  if (m_numberOfPeriods > 1) {
    setProperty("OutputWorkspace",
221
                std::dynamic_pointer_cast<Workspace>(wsGrpSptr));
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
  }

  // period_index is currently unused
  // Mantid::NeXus::NXInt period_index = dataGroup.openNXInt("period_index");
  // period_index.load();

  Mantid::NeXus::NXInt counts = dataGroup.openIntData();
  counts.load();

  NXInstrument instr = entry.openNXInstrument("instrument");

  if (instr.containsGroup("detector_fb")) {
    NXDetector detector = instr.openNXDetector("detector_fb");
    if (detector.containsDataSet("time_zero")) {
      double dum = detector.getFloat("time_zero");
      setProperty("TimeZero", dum);
    }
    if (detector.containsDataSet("first_good_time")) {
      double dum = detector.getFloat("first_good_time");
      setProperty("FirstGoodData", dum);
    }
  }

245
  API::Progress progress(this, 0.0, 1.0, m_numberOfPeriods * total_specs);
246
247
248
249
250
251
252
253
254
255
  // Loop over the number of periods in the Nexus file, putting each period in a
  // separate workspace
  for (int period = 0; period < m_numberOfPeriods; ++period) {

    if (period == 0) {
      // Only run the Child Algorithms once
      loadRunDetails(localWorkspace);
      runLoadInstrument(localWorkspace);
      loadLogs(localWorkspace, entry, period);
    } else // We are working on a higher period of a multiperiod raw file
256
    {
257
      localWorkspace = std::dynamic_pointer_cast<DataObjects::Workspace2D>(
258
259
          WorkspaceFactory::Instance().create(localWorkspace));
    }
260

261
    std::string outws;
262
263
264
265
266
267
    if (m_numberOfPeriods > 1) {
      std::string outputWorkspace = "OutputWorkspace";
      std::stringstream suffix;
      suffix << (period + 1);
      outws = outputWorkspace + "_" + suffix.str();
      std::string WSName = localWSName + "_" + suffix.str();
268
      declareProperty(std::make_unique<WorkspaceProperty<Workspace>>(
269
          outws, WSName, Direction::Output));
270
271
272
      if (wsGrpSptr)
        wsGrpSptr->addWorkspace(localWorkspace);
    }
273

274
275
276
277
278
    // create spectrum -> index correspondence
    std::map<int, int> index_spectrum;
    for (int i = 0; i < m_numberOfSpectra; ++i) {
      index_spectrum[spectrum_index[i]] = i;
    }
279

280
281
    int wsIndex = 0;
    localWorkspace->mutableX(0) = timeBins;
282
    for (auto spec = static_cast<int>(m_spec_min);
283
284
         spec <= static_cast<int>(m_spec_max); ++spec) {
      int i = index_spectrum[spec]; // if spec not found i is 0
LamarMoore's avatar
LamarMoore committed
285
286
      localWorkspace->setHistogram(
          wsIndex, loadData(localWorkspace->binEdges(0), counts, period, i));
287
288
289
      localWorkspace->getSpectrum(wsIndex).setSpectrumNo(spectrum_index[i]);
      localWorkspace->getSpectrum(wsIndex).setDetectorIDs(detMapping.at(i));
      wsIndex++;
290
291
      progress.report();
    }
292

293
294
    // Read in the spectra in the optional list parameter, if set
    if (m_list) {
Hahn, Steven's avatar
Hahn, Steven committed
295
      for (auto spec : m_spec_list) {
296
        int k = index_spectrum[spec]; // if spec not found k is 0
LamarMoore's avatar
LamarMoore committed
297
298
        localWorkspace->setHistogram(
            wsIndex, loadData(localWorkspace->binEdges(0), counts, period, k));
299
300
301
        localWorkspace->getSpectrum(wsIndex).setSpectrumNo(spectrum_index[k]);
        localWorkspace->getSpectrum(wsIndex).setDetectorIDs(detMapping.at(k));
        wsIndex++;
302
        progress.report();
303
      }
304
    }
305
    // Just a sanity check
LamarMoore's avatar
LamarMoore committed
306
    assert(wsIndex == total_specs);
307

308
    bool autogroup = getProperty("AutoGroup");
309

310
311
312
313
    if (autogroup) {
      g_log.warning(
          "Autogrouping is not implemented for muon NeXus version 2 files");
    }
Karl Palmen's avatar
Karl Palmen committed
314

315
316
    // Assign the result to the output workspace property
    if (m_numberOfPeriods > 1)
317
      setProperty(outws, std::static_pointer_cast<Workspace>(localWorkspace));
318
319
    else {
      setProperty("OutputWorkspace",
320
                  std::dynamic_pointer_cast<Workspace>(localWorkspace));
321
    }
Karl Palmen's avatar
Karl Palmen committed
322

323
324
325
326
  } // loop over periods
}

/** loadData
LamarMoore's avatar
LamarMoore committed
327
328
 *  Load the counts data from an NXInt into a workspace
 */
LamarMoore's avatar
LamarMoore committed
329
330
331
Histogram LoadMuonNexus2::loadData(const BinEdges &edges,
                                   const Mantid::NeXus::NXInt &counts,
                                   int period, int spec) {
332
  int nBins = 0;
333
  const int *data = nullptr;
334
335
336
337
338
339
340
341

  if (counts.rank() == 3) {
    nBins = counts.dim2();
    data = &counts(period, spec, 0);
  } else if (counts.rank() == 2) {
    nBins = counts.dim1();
    data = &counts(spec, 0);
  } else {
342
    throw std::runtime_error("Data have unsupported dimensionality");
343
344
  }

LamarMoore's avatar
LamarMoore committed
345
  return Histogram(edges, Counts(data, data + nBins));
346
347
348
}

/**  Load logs from Nexus file. Logs are expected to be in
LamarMoore's avatar
LamarMoore committed
349
350
351
352
353
 *   /run/sample group of the file.
 *   @param ws :: The workspace to load the logs to.
 *   @param entry :: The Nexus entry
 *   @param period :: The period of this workspace
 */
David Fairbrother's avatar
David Fairbrother committed
354
355
void LoadMuonNexus2::loadLogs(const API::MatrixWorkspace_sptr &ws,
                              NXEntry &entry, int period) {
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
  // Avoid compiler warning
  (void)period;

  std::string start_time = entry.getString("start_time");

  std::string sampleName = entry.getString("sample/name");
  NXMainClass runlogs = entry.openNXClass<NXMainClass>("sample");
  ws->mutableSample().setName(sampleName);

  for (std::vector<NXClassInfo>::const_iterator it = runlogs.groups().begin();
       it != runlogs.groups().end(); ++it) {
    NXLog nxLog = runlogs.openNXLog(it->nxname);
    Kernel::Property *logv = nxLog.createTimeSeries(start_time);
    if (!logv)
      continue;
    ws->mutableRun().addLogData(logv);
  }

  ws->setTitle(entry.getString("title"));

  if (entry.containsDataSet("notes")) {
    ws->setComment(entry.getString("notes"));
  }

380
  std::string run_num = std::to_string(entry.getInt("run_number"));
381
382
383
384
385
386
387
388
  // The sample is left to delete the property
  ws->mutableRun().addLogData(
      new PropertyWithValue<std::string>("run_number", run_num));

  ws->populateInstrumentParameters();
}

/**  Log the run details from the file
LamarMoore's avatar
LamarMoore committed
389
390
 * @param localWorkspace :: The workspace details to use
 */
391
void LoadMuonNexus2::loadRunDetails(
David Fairbrother's avatar
David Fairbrother committed
392
    const DataObjects::Workspace2D_sptr &localWorkspace) {
393
394
395
396
  API::Run &runDetails = localWorkspace->mutableRun();

  runDetails.addProperty("run_title", localWorkspace->getTitle(), true);

397
  auto numSpectra = static_cast<int>(localWorkspace->getNumberHistograms());
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
  runDetails.addProperty("nspectra", numSpectra);

  m_filename = getPropertyValue("Filename");
  NXRoot root(m_filename);
  NXEntry entry = root.openEntry(m_entry_name);

  std::string start_time = entry.getString("start_time");
  runDetails.addProperty("run_start", start_time);

  std::string stop_time = entry.getString("end_time");
  runDetails.addProperty("run_end", stop_time);

  if (entry.containsGroup("run")) {
    NXClass runRun = entry.openNXGroup("run");

    if (runRun.containsDataSet("good_total_frames")) {
      int dum = runRun.getInt("good_total_frames");
      runDetails.addProperty("goodfrm", dum);
    }
417

418
419
420
421
422
423
424
    if (runRun.containsDataSet("number_periods")) {
      int dum = runRun.getInt("number_periods");
      runDetails.addProperty("nperiods", dum);
    }
  }

  { // Duration taken to be stop_time minus stat_time
425
426
    auto start = createFromSanitizedISO8601(start_time);
    auto end = createFromSanitizedISO8601(stop_time);
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
    double duration_in_secs = DateAndTime::secondsFromDuration(end - start);
    runDetails.addProperty("dur_secs", duration_in_secs);
  }
}

/**
 * Return the confidence with with this algorithm can load the file
 * @param descriptor A descriptor for the file
 * @returns An integer specifying the confidence level. 0 indicates it will not
 * be used
 */
int LoadMuonNexus2::confidence(Kernel::NexusDescriptor &descriptor) const {
  const auto &firstEntryNameType = descriptor.firstEntryNameType();
  const std::string root = "/" + firstEntryNameType.first;
  if (!descriptor.pathExists(root + "/definition"))
    return 0;

  bool upperIDF(true);
  if (descriptor.pathExists(root + "/IDF_version"))
    upperIDF = true;
  else {
    if (descriptor.pathExists(root + "/idf_version"))
      upperIDF = false;
    else
451
      return 0;
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
  }

  try {
    std::string versionField = "idf_version";
    if (upperIDF)
      versionField = "IDF_version";

    auto &file = descriptor.data();
    file.openPath(root + "/" + versionField);
    int32_t version = 0;
    file.getData(&version);
    if (version != 2)
      return 0;

    file.openPath(root + "/definition");
    std::string def = file.getStrData();
    if (def == "muonTD" || def == "pulsedTD") {
      // If all this succeeded then we'll assume this is an ISIS Muon NeXus file
      // version 2
      return 81;
472
    }
473
474
475
476
  } catch (...) {
  }
  return 0;
}
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
/**
 * Loads the mapping between index -> set of detector IDs
 *
 * If "detector_index", "detector_count" and "detector_list" are all present,
 * use these to get the mapping, otherwise spectrum number = detector ID
 * (one-to-one)
 *
 * The spectrum spectrum_index[i] maps to detector_count[i] detectors, whose
 * detector IDs are in detector_list starting at the index detector_index[i]
 *
 * @returns :: map of index -> detector IDs
 * @throws std::runtime_error if fails to read data from file
 */
std::map<int, std::set<int>>
LoadMuonNexus2::loadDetectorMapping(const Mantid::NeXus::NXInt &spectrumIndex) {
  std::map<int, std::set<int>> mapping;
  const int nSpectra = spectrumIndex.dim0();

  // Find and open the data group
  NXRoot root(getPropertyValue("Filename"));
  NXEntry entry = root.openEntry(m_entry_name);
  const std::string detectorName = [&entry]() {
    // Only the first NXdata found
    for (auto &group : entry.groups()) {
      std::string className = group.nxclass;
      if (className == "NXdata") {
        return group.nxname;
      }
    }
    throw std::runtime_error("No NXdata found in file");
  }();
  NXData dataGroup = entry.openNXData(detectorName);

  // Usually for muon data, detector id = spectrum number
  // If not, the optional groups "detector_index", "detector_list" and
  // "detector_count" will be present to map one to the other
  const bool hasDetectorMapping = dataGroup.containsDataSet("detector_index") &&
                                  dataGroup.containsDataSet("detector_list") &&
                                  dataGroup.containsDataSet("detector_count");
  if (hasDetectorMapping) {
    // Read detector IDs
    try {
      const auto detIndex = dataGroup.openNXInt("detector_index");
      const auto detCount = dataGroup.openNXInt("detector_count");
      const auto detList = dataGroup.openNXInt("detector_list");
523
524
      const int nDet = detIndex.dim0();
      for (int i = 0; i < nDet; ++i) {
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
        const int start = detIndex[i];
        const int nDetectors = detCount[i];
        std::set<int> detIDs;
        for (int jDet = 0; jDet < nDetectors; ++jDet) {
          detIDs.insert(detList[start + jDet]);
        }
        mapping[i] = detIDs;
      }
    } catch (const ::NeXus::Exception &err) {
      // Throw a more user-friendly message
      std::ostringstream message;
      message << "Failed to read detector mapping: " << err.what();
      throw std::runtime_error(message.str());
    }
  } else {
    for (int i = 0; i < nSpectra; ++i) {
      mapping[i] = std::set<int>{spectrumIndex[i]};
    }
  }

  return mapping;
}

548
} // namespace DataHandling
549
} // namespace Mantid