LoadILLDiffraction.cpp 22.5 KB
Newer Older
1
#include "MantidDataHandling/LoadILLDiffraction.h"
Owen Arnold's avatar
Owen Arnold committed
2
#include "MantidGeometry/Instrument/ComponentInfo.h"
3
#include "MantidGeometry/Instrument/DetectorInfo.h"
Gagik Vardanyan's avatar
Gagik Vardanyan committed
4
#include "MantidAPI/FileProperty.h"
5
#include "MantidAPI/MatrixWorkspace.h"
6
#include "MantidAPI/RegisterFileLoader.h"
7
#include "MantidAPI/WorkspaceFactory.h"
Gagik Vardanyan's avatar
Gagik Vardanyan committed
8
#include "MantidDataHandling/H5Util.h"
9
#include "MantidDataObjects/ScanningWorkspaceBuilder.h"
Gagik Vardanyan's avatar
Gagik Vardanyan committed
10
#include "MantidGeometry/Instrument/ComponentHelper.h"
11
#include "MantidKernel/ConfigService.h"
Gagik Vardanyan's avatar
Gagik Vardanyan committed
12
#include "MantidKernel/DateAndTime.h"
13
#include "MantidKernel/OptionalBool.h"
Gagik Vardanyan's avatar
Gagik Vardanyan committed
14
#include "MantidKernel/TimeSeriesProperty.h"
15
#include "MantidKernel/make_unique.h"
16

17
#include <boost/algorithm/string/predicate.hpp>
Gagik Vardanyan's avatar
Gagik Vardanyan committed
18
#include <numeric>
19
20

#include <H5Cpp.h>
21
#include <nexus/napi.h>
22
#include <Poco/Path.h>
23
24
25
26
27

namespace Mantid {
namespace DataHandling {

using namespace API;
28
29
using namespace Geometry;
using namespace H5;
30
using namespace Kernel;
31
32
using namespace NeXus;

33
namespace {
Gagik Vardanyan's avatar
Gagik Vardanyan committed
34
35
36
37
// This defines the number of physical pixels in D20 (low resolution mode)
// Then each pixel can be split into 2 (nominal) or 3 (high resolution) by DAQ
constexpr size_t D20_NUMBER_PIXELS = 1600;
// This defines the number of dead pixels on each side in low resolution mode
38
constexpr size_t D20_NUMBER_DEAD_PIXELS = 32;
39
40
// This defines the number of monitors in the instrument. If there are cases
// where this is no longer one this decleration should be moved.
41
constexpr size_t NUMBER_MONITORS = 1;
42
43
// This is the angular size of a pixel in degrees (in low resolution mode)
constexpr double D20_PIXEL_SIZE = 0.1;
44
constexpr double rad2deg = 180. / M_PI;
45
46
}

47
// Register the algorithm into the AlgorithmFactory
48
DECLARE_NEXUS_FILELOADER_ALGORITHM(LoadILLDiffraction)
49

50
/// Returns confidence. @see IFileLoader::confidence
51
52
53
54
55
56
57
58
59
60
61
int LoadILLDiffraction::confidence(NexusDescriptor &descriptor) const {

  // fields existent only at the ILL Diffraction
  if (descriptor.pathExists("/entry0/data_scan")) {
    return 80;
  } else {
    return 0;
  }
}

/// Algorithms name for identification. @see Algorithm::name
62
63
64
const std::string LoadILLDiffraction::name() const {
  return "LoadILLDiffraction";
}
65
66
67
68
69
70

/// Algorithm's version for identification. @see Algorithm::version
int LoadILLDiffraction::version() const { return 1; }

/// Algorithm's category for identification. @see Algorithm::category
const std::string LoadILLDiffraction::category() const {
Gagik Vardanyan's avatar
Gagik Vardanyan committed
71
  return "DataHandling\\Nexus;ILL\\Diffraction";
72
73
74
75
}

/// Algorithm's summary for use in the GUI and help. @see Algorithm::summary
const std::string LoadILLDiffraction::summary() const {
76
  return "Loads ILL diffraction nexus files.";
77
78
}

79
80
81
82
/**
 * Constructor
 */
LoadILLDiffraction::LoadILLDiffraction()
83
    : IFileLoader<NexusDescriptor>(), m_instNames({"D20", "D2B"}) {}
84
85
86

/**
 * Initialize the algorithm's properties.
87
88
89
90
 */
void LoadILLDiffraction::init() {
  declareProperty(
      make_unique<FileProperty>("Filename", "", FileProperty::Load, ".nxs"),
Gagik Vardanyan's avatar
Gagik Vardanyan committed
91
      "File path of the data file to load");
Gagik Vardanyan's avatar
Gagik Vardanyan committed
92
  declareProperty(make_unique<WorkspaceProperty<MatrixWorkspace>>(
93
                      "OutputWorkspace", "", Direction::Output),
Gagik Vardanyan's avatar
Gagik Vardanyan committed
94
                  "The output workspace.");
95
96
}

97
/**
98
 * Executes the algorithm.
99
100
101
 */
void LoadILLDiffraction::exec() {

102
  Progress progress(this, 0, 1, 3);
103
104
105

  m_fileName = getPropertyValue("Filename");

Ian Bush's avatar
Ian Bush committed
106
  progress.report("Loading the scanned variables");
107
  loadScanVars();
108

109
  progress.report("Loading the detector scan data");
110
  loadDataScan();
111

112
  progress.report("Loading the metadata");
Gagik Vardanyan's avatar
Gagik Vardanyan committed
113
  loadMetaData();
114
115
116
117
118

  setProperty("OutputWorkspace", m_outWorkspace);
}

/**
119
* Loads the scanned detector data
120
*/
121
void LoadILLDiffraction::loadDataScan() {
122

123
124
125
126
127
128
  // open the root entry
  NXRoot dataRoot(m_fileName);
  NXEntry firstEntry = dataRoot.openFirstEntry();

  m_instName = firstEntry.getString("instrument/name");

Gagik Vardanyan's avatar
Gagik Vardanyan committed
129
130
131
  m_startTime = DateAndTime(
      m_loadHelper.dateTimeInIsoFormat(firstEntry.getString("start_time")));

132
  // read the detector data
133
  NXData dataGroup = firstEntry.openNXData("data_scan/detector_data");
134
  NXUInt data = dataGroup.openUIntData();
135
136
  data.load();

137
138
139
140
141
142
143
144
145
  // read the scan data
  NXData scanGroup = firstEntry.openNXData("data_scan/scanned_variables");
  NXDouble scan = scanGroup.openDoubleData();
  scan.load();

  // read which variables are scanned
  NXInt scanned = firstEntry.openNXInt(
      "data_scan/scanned_variables/variables_names/scanned");
  scanned.load();
Gagik Vardanyan's avatar
Gagik Vardanyan committed
146

147
148
149
150
  // read what is going to be the axis
  NXInt axis =
      firstEntry.openNXInt("data_scan/scanned_variables/variables_names/axis");
  axis.load();
151

152
  // read the starting two theta
153
154
  NXFloat twoTheta0 = firstEntry.openNXFloat("instrument/2theta/value");
  twoTheta0.load();
155

Gagik Vardanyan's avatar
Gagik Vardanyan committed
156
  // figure out the dimensions
157
158
159
  m_sizeDim1 = static_cast<size_t>(data.dim1());
  m_sizeDim2 = static_cast<size_t>(data.dim2());
  m_numberDetectorsRead = m_sizeDim1 * m_sizeDim2;
160
  m_numberScanPoints = static_cast<size_t>(data.dim0());
161
162
  g_log.debug() << "Read " << m_numberDetectorsRead << " detectors and "
                << m_numberScanPoints << "\n";
163

Gagik Vardanyan's avatar
Gagik Vardanyan committed
164
  // set which scanned variables are scanned, which should be the axis
165
  for (size_t i = 0; i < m_scanVar.size(); ++i) {
Gagik Vardanyan's avatar
Gagik Vardanyan committed
166
167
    m_scanVar[i].setAxis(axis[static_cast<int>(i)]);
    m_scanVar[i].setScanned(scanned[static_cast<int>(i)]);
168
  }
169

Gagik Vardanyan's avatar
Gagik Vardanyan committed
170
  resolveScanType();
171

172
173
  resolveInstrument();

Gagik Vardanyan's avatar
Gagik Vardanyan committed
174
  if (m_scanType == DetectorScan) {
175
    initMovingWorkspace(scan);
176
    fillMovingInstrumentScan(data, scan);
177
  } else {
178
    initStaticWorkspace();
179
    fillStaticInstrumentScan(data, scan, twoTheta0);
180
181
  }

Ian Bush's avatar
Ian Bush committed
182
183
  fillDataScanMetaData(scan);

184
185
186
187
  scanGroup.close();
  dataGroup.close();
  firstEntry.close();
  dataRoot.close();
Gagik Vardanyan's avatar
Gagik Vardanyan committed
188
189
190
}

/**
191
192
* Dumps the metadata from the whole file to SampleLogs
*/
Gagik Vardanyan's avatar
Gagik Vardanyan committed
193
void LoadILLDiffraction::loadMetaData() {
Gagik Vardanyan's avatar
Gagik Vardanyan committed
194

195
  m_outWorkspace->mutableRun().addProperty("Facility", std::string("ILL"));
Gagik Vardanyan's avatar
Gagik Vardanyan committed
196

197
198
199
  // Open NeXus file
  NXhandle nxHandle;
  NXstatus nxStat = NXopen(m_fileName.c_str(), NXACC_READ, &nxHandle);
Gagik Vardanyan's avatar
Gagik Vardanyan committed
200

201
202
203
204
  if (nxStat != NX_ERROR) {
    m_loadHelper.addNexusFieldsToWsRun(nxHandle, m_outWorkspace->mutableRun());
    nxStat = NXclose(&nxHandle);
  }
Gagik Vardanyan's avatar
Gagik Vardanyan committed
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
/**
 * Initializes the output workspace based on the resolved instrument, scan
 * points, and scan type
 */
void LoadILLDiffraction::initStaticWorkspace() {
  size_t nSpectra = m_numberDetectorsActual + NUMBER_MONITORS;
  size_t nBins = 1;

  if (m_scanType == DetectorScan) {
    nSpectra *= m_numberScanPoints;
  } else if (m_scanType == OtherScan) {
    nBins = m_numberScanPoints;
  }

  m_outWorkspace = WorkspaceFactory::Instance().create("Workspace2D", nSpectra,
                                                       nBins, nBins);
}

/**
 * Use the ScanningWorkspaceBuilder to create a time indexed workspace.
 *
 * @param scan : scan data
 */
void LoadILLDiffraction::initMovingWorkspace(const NXDouble &scan) {
  const size_t nTimeIndexes = m_numberScanPoints;
  const size_t nBins = 1;
233
  const bool isPointData = true;
234
235
236
237

  const auto instrumentWorkspace = loadEmptyInstrument();
  const auto &instrument = instrumentWorkspace->getInstrument();

238
239
  auto scanningWorkspaceBuilder = DataObjects::ScanningWorkspaceBuilder(
      instrument, nTimeIndexes, nBins, isPointData);
240
241
242
243
244

  std::vector<double> timeDurations =
      getScannedVaribleByPropertyName(scan, "Time");
  scanningWorkspaceBuilder.setTimeRanges(m_startTime, timeDurations);

245
246
247
248
249
250
251
252
  g_log.debug() << "First time index starts at:"
                << m_startTime.toISO8601String() << "\n";

  g_log.debug() << "Last time index ends at:"
                << (m_startTime + std::accumulate(timeDurations.begin(),
                                                  timeDurations.end(), 0.0))
                       .toISO8601String() << "\n";

253
254
  // Angles in the NeXus files are the absolute position for tube 1
  std::vector<double> tubeAngles =
255
      getScannedVaribleByPropertyName(scan, "Position");
256

257
258
  const auto &referenceComponentPosition =
      getReferenceComponentPosition(instrumentWorkspace);
259
260

  // Convert the tube positions to relative rotations for all detectors
261
  calculateRelativeRotations(tubeAngles, referenceComponentPosition);
262

263
264
265
  auto rotationCentre = V3D(0, 0, 0);
  auto rotationAxis = V3D(0, 1, 0);
  scanningWorkspaceBuilder.setRelativeRotationsForScans(
266
      std::move(tubeAngles), rotationCentre, rotationAxis);
267
268
269
270

  m_outWorkspace = scanningWorkspaceBuilder.buildWorkspace();
}

271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/**
 * Get the position of the component in the workspace which corresponds to the
 *angle stored in the scanned variables of the NeXus files. For 1D detectors
 *this should be the first detector (ID 1), while for 2D detectors (D2B only) it
 *should be the position of the first tube.
 *
 * @param instrumentWorkspace The empty workspace containing the instrument
 * @return A V3D object containing the position of the relevant component
 */
V3D LoadILLDiffraction::getReferenceComponentPosition(
    const MatrixWorkspace_sptr &instrumentWorkspace) {
  if (m_instName == "D2B") {
    return instrumentWorkspace->getInstrument()
        ->getComponentByName("tube_1")
        ->getPos();
  }

  const auto &detInfo = instrumentWorkspace->detectorInfo();
  const auto &indexOfFirstDet = detInfo.indexOf(1);
  return detInfo.position(indexOfFirstDet);
}

293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/**
 * Convert from absolute rotation angle, around the sample, of tube 1, to a
 *relative rotation angle around the sample.
 *
 * @param tubeRotations Input is the absolute rotations around the sample of
 *tube 1, output is the relative rotations required from the IDF for all
 *detectors
 * @param firstTubePosition A V3D object containing the position of the first
 *tube
 */
void LoadILLDiffraction::calculateRelativeRotations(
    std::vector<double> &tubeRotations, const V3D &firstTubePosition) {
  // The rotations in the NeXus file are the absolute rotation of the first
  // tube. Here we get the angle of that tube as defined in the IDF.

308
  double firstTubeRotationAngle =
309
      firstTubePosition.angle(V3D(0, 0, 1)) * rad2deg;
310
311
312
313

  if (m_instName == "D20")
    firstTubeRotationAngle += D20_NUMBER_DEAD_PIXELS * D20_PIXEL_SIZE;

314
315
316
317
318
319
320
321
322
323
324
325
  g_log.debug() << "First tube rotation:" << firstTubeRotationAngle << "\n";

  // Now pass calculate the rotations to apply for each time index.
  std::transform(
      tubeRotations.begin(), tubeRotations.end(), tubeRotations.begin(),
      [&](double angle) { return (angle - firstTubeRotationAngle); });

  g_log.debug() << "Instrument rotations to be applied : "
                << tubeRotations.front() << " to " << tubeRotations.back()
                << "\n";
}

326
327
328
329
330
331
332
333
334
/**
 * Fills the counts for the instrument with moving detectors.
 *
 * @param data : detector data
 * @param scan : scan data
 */
void LoadILLDiffraction::fillMovingInstrumentScan(const NXUInt &data,
                                                  const NXDouble &scan) {

335
  std::vector<double> axis = {0.};
336
337
338
339
340
  std::vector<double> monitor = getMonitor(scan);

  // First load the monitors
  for (size_t i = 0; i < NUMBER_MONITORS; ++i) {
    for (size_t j = 0; j < m_numberScanPoints; ++j) {
341
342
343
344
      const auto wsIndex = j + i * m_numberScanPoints;
      m_outWorkspace->mutableY(wsIndex) = monitor[j];
      m_outWorkspace->mutableE(wsIndex) = sqrt(monitor[j]);
      m_outWorkspace->mutableX(wsIndex) = axis;
345
346
347
    }
  }

348
349
350
  // Dead pixel offset, should be zero except for D20
  size_t deadOffset = (m_numberDetectorsRead - m_numberDetectorsActual) / 2;

351
352
353
354
  // Then load the detector spectra
  for (size_t i = NUMBER_MONITORS;
       i < m_numberDetectorsActual + NUMBER_MONITORS; ++i) {
    for (size_t j = 0; j < m_numberScanPoints; ++j) {
355
      const auto tubeNumber = (i - NUMBER_MONITORS + deadOffset) / m_sizeDim2;
356
357
358
359
360
361
362
      const auto pixelInTubeNumber = (i - NUMBER_MONITORS) % m_sizeDim2;
      unsigned int y = data(static_cast<int>(j), static_cast<int>(tubeNumber),
                            static_cast<int>(pixelInTubeNumber));
      const auto wsIndex = j + i * m_numberScanPoints;
      m_outWorkspace->mutableY(wsIndex) = y;
      m_outWorkspace->mutableE(wsIndex) = sqrt(y);
      m_outWorkspace->mutableX(wsIndex) = axis;
363
364
365
366
    }
  }
}

367
/**
368
369
 * Fills the loaded data to the workspace when the detector
 * is not moving during the run, but can be moved before
370
 *
371
372
373
 * @param data : detector data
 * @param scan : scan data
 * @param twoTheta0 : starting two theta
374
375
 */
void LoadILLDiffraction::fillStaticInstrumentScan(const NXUInt &data,
376
377
                                                  const NXDouble &scan,
                                                  const NXFloat &twoTheta0) {
378

379
380
  std::vector<double> axis = getAxis(scan);
  std::vector<double> monitor = getMonitor(scan);
381
382

  // Assign monitor counts
383
  m_outWorkspace->mutableX(0) = axis;
384
385
  m_outWorkspace->mutableY(0) = monitor;
  std::transform(monitor.begin(), monitor.end(),
386
387
                 m_outWorkspace->mutableE(0).begin(),
                 [](double e) { return sqrt(e); });
388

389
  // Assign detector counts
390
  size_t deadOffset = (m_numberDetectorsRead - m_numberDetectorsActual) / 2;
391
392
  for (size_t i = NUMBER_MONITORS;
       i < m_numberDetectorsActual + NUMBER_MONITORS; ++i) {
Gagik Vardanyan's avatar
Gagik Vardanyan committed
393
394
    auto &spectrum = m_outWorkspace->mutableY(i);
    auto &errors = m_outWorkspace->mutableE(i);
395
    const auto tubeNumber = (i - NUMBER_MONITORS + deadOffset) / m_sizeDim2;
396
    const auto pixelInTubeNumber = (i - NUMBER_MONITORS) % m_sizeDim2;
397
    for (size_t j = 0; j < m_numberScanPoints; ++j) {
398
399
      unsigned int y = data(static_cast<int>(j), static_cast<int>(tubeNumber),
                            static_cast<int>(pixelInTubeNumber));
Gagik Vardanyan's avatar
Gagik Vardanyan committed
400
401
      spectrum[j] = y;
      errors[j] = sqrt(y);
402
    }
403
    m_outWorkspace->mutableX(i) = axis;
404
  }
405

406
  // Link the instrument
407
408
409
410
411
412
413
414
415
  loadStaticInstrument();

  // Move to the starting 2theta
  moveTwoThetaZero(double(twoTheta0[0]));
}

/**
 * Loads the scanned_variables/variables_names block
 */
Gagik Vardanyan's avatar
Gagik Vardanyan committed
416
void LoadILLDiffraction::loadScanVars() {
417
418
419
420
421
422
423
424
425
426
427
428
429

  H5File h5file(m_fileName, H5F_ACC_RDONLY);

  Group entry0 = h5file.openGroup("entry0");
  Group dataScan = entry0.openGroup("data_scan");
  Group scanVar = dataScan.openGroup("scanned_variables");
  Group varNames = scanVar.openGroup("variables_names");

  const auto names = H5Util::readStringVector(varNames, "name");
  const auto properties = H5Util::readStringVector(varNames, "property");
  const auto units = H5Util::readStringVector(varNames, "unit");

  for (size_t i = 0; i < names.size(); ++i) {
Gagik Vardanyan's avatar
Gagik Vardanyan committed
430
    m_scanVar.emplace_back(ScannedVariables(names[i], properties[i], units[i]));
431
432
433
434
435
436
437
438
439
440
  }

  varNames.close();
  scanVar.close();
  dataScan.close();
  entry0.close();
  h5file.close();
}

/**
Gagik Vardanyan's avatar
Gagik Vardanyan committed
441
 * Creates time series sample logs for the scanned variables
442
443
 * @param scan : scan data
 */
Gagik Vardanyan's avatar
Gagik Vardanyan committed
444
445
void LoadILLDiffraction::fillDataScanMetaData(const NXDouble &scan) {
  auto absoluteTimes = getAbsoluteTimes(scan);
446
  for (size_t i = 0; i < m_scanVar.size(); ++i) {
447
    if (!boost::starts_with(m_scanVar[i].property, "Monitor")) {
Gagik Vardanyan's avatar
Gagik Vardanyan committed
448
      auto property =
Gagik Vardanyan's avatar
Gagik Vardanyan committed
449
          Kernel::make_unique<TimeSeriesProperty<double>>(m_scanVar[i].name);
Gagik Vardanyan's avatar
Gagik Vardanyan committed
450
      for (size_t j = 0; j < m_numberScanPoints; ++j) {
Gagik Vardanyan's avatar
Gagik Vardanyan committed
451
452
        property->addValue(absoluteTimes[j],
                           scan(static_cast<int>(i), static_cast<int>(j)));
453
      }
Gagik Vardanyan's avatar
Gagik Vardanyan committed
454
      m_outWorkspace->mutableRun().addLogData(std::move(property));
455
456
457
458
    }
  }
}

459
460
461
462
463
464
465
/**
 * Gets a scanned variable based on its property type in the scanned_variables
 *block.
 *
 * @param scan : scan data
 * @param propertyName The name of the property
 * @return A vector of doubles containing the scanned variable
466
467
 * @throw runtime_error If a scanned variable property name is missing from the
 *NeXus file
468
469
470
 */
std::vector<double> LoadILLDiffraction::getScannedVaribleByPropertyName(
    const NXDouble &scan, const std::string &propertyName) const {
471
  std::vector<double> scannedVariable;
472
473
474
475

  for (size_t i = 0; i < m_scanVar.size(); ++i) {
    if (m_scanVar[i].property.compare(propertyName) == 0) {
      for (size_t j = 0; j < m_numberScanPoints; ++j) {
476
477
        scannedVariable.push_back(
            scan(static_cast<int>(i), static_cast<int>(j)));
478
479
480
481
482
      }
      break;
    }
  }

483
  if (scannedVariable.empty())
484
485
486
487
488
    throw std::runtime_error(
        "Can not load file because scanned variable with property name " +
        propertyName + " was not found");

  return scannedVariable;
489
490
}

491
492
493
494
/**
 * Returns the monitor spectrum
 * @param scan : scan data
 * @return monitor spectrum
495
496
 * @throw std::runtime_error If there are no entries named Monitor1 or Monitor_1
 * in the NeXus file
497
498
499
500
501
 */
std::vector<double> LoadILLDiffraction::getMonitor(const NXDouble &scan) const {

  std::vector<double> monitor = {0.};
  for (size_t i = 0; i < m_scanVar.size(); ++i) {
Ian Bush's avatar
Ian Bush committed
502
503
    if ((m_scanVar[i].name == "Monitor1") ||
        (m_scanVar[i].name == "Monitor_1")) {
504
505
      monitor.assign(scan() + m_numberScanPoints * i,
                     scan() + m_numberScanPoints * (i + 1));
Ian Bush's avatar
Ian Bush committed
506
      return monitor;
507
508
    }
  }
Ian Bush's avatar
Ian Bush committed
509
  throw std::runtime_error("Monitors not found in scanned variables");
510
511
512
513
514
515
516
517
518
}

/**
 * Returns the x-axis
 * @param scan : scan data
 * @return the x-axis
 */
std::vector<double> LoadILLDiffraction::getAxis(const NXDouble &scan) const {

Ian Bush's avatar
Ian Bush committed
519
  std::vector<double> axis = {0.};
520
521
522
523
524
525
526
527
528
529
530
531
  if (m_scanType == OtherScan) {
    for (size_t i = 0; i < m_scanVar.size(); ++i) {
      if (m_scanVar[i].axis == 1) {
        axis.assign(scan() + m_numberScanPoints * i,
                    scan() + m_numberScanPoints * (i + 1));
        break;
      }
    }
  }
  return axis;
}

Gagik Vardanyan's avatar
Gagik Vardanyan committed
532
/**
533
 * Returns the durations in seconds for each scan point
Gagik Vardanyan's avatar
Gagik Vardanyan committed
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
 * @param scan : scan data
 * @return vector of durations
 */
std::vector<double>
LoadILLDiffraction::getDurations(const NXDouble &scan) const {
  std::vector<double> timeDurations;
  for (size_t i = 0; i < m_scanVar.size(); ++i) {
    if (boost::starts_with(m_scanVar[i].property, "Time")) {
      timeDurations.assign(scan() + m_numberScanPoints * i,
                           scan() + m_numberScanPoints * (i + 1));
      break;
    }
  }
  return timeDurations;
}

/**
 * Returns the vector of absolute times for each scan point
 * @param scan : scan data
 * @return vector of absolute times
 */
std::vector<DateAndTime>
LoadILLDiffraction::getAbsoluteTimes(const NXDouble &scan) const {
557
  std::vector<DateAndTime> times;
Gagik Vardanyan's avatar
Gagik Vardanyan committed
558
559
560
561
562
  std::vector<double> durations = getDurations(scan);
  DateAndTime time = m_startTime;
  times.emplace_back(time);
  size_t timeIndex = 1;
  while (timeIndex < m_numberScanPoints) {
563
    time += durations[timeIndex - 1];
Gagik Vardanyan's avatar
Gagik Vardanyan committed
564
    times.push_back(time);
Gagik Vardanyan's avatar
Gagik Vardanyan committed
565
566
567
    ++timeIndex;
  }
  return times;
Gagik Vardanyan's avatar
Gagik Vardanyan committed
568
569
}

570
571
572
573
574
575
576
577
/**
 * Resolves the scan type
 */
void LoadILLDiffraction::resolveScanType() {
  ScanType result = NoScan;
  for (const auto &scanVar : m_scanVar) {
    if (scanVar.scanned == 1) {
      result = OtherScan;
578
      if (scanVar.name == "2theta") {
579
580
581
582
583
584
        result = DetectorScan;
        break;
      }
    }
  }
  m_scanType = result;
585
586
}

587
588
/**
 * Resolves the instrument based on instrument name and resolution mode
Gagik Vardanyan's avatar
Gagik Vardanyan committed
589
 * @throws runtime_error, if the instrument is not supported
590
 */
591
592
593
void LoadILLDiffraction::resolveInstrument() {
  if (m_instNames.find(m_instName) == m_instNames.end()) {
    throw std::runtime_error("Instrument " + m_instName + " not supported.");
594
  } else {
595
596
    m_numberDetectorsActual = m_numberDetectorsRead;
    if (m_instName == "D20") {
Gagik Vardanyan's avatar
Gagik Vardanyan committed
597
      // Here we have to hardcode the numbers of pixels.
Gagik Vardanyan's avatar
Gagik Vardanyan committed
598
599
      // The only way is to read the size of the detectors read from the files
      // and based on it decide which of the 3 alternative IDFs to load.
600
601
      // Some amount of pixels are dead on each end, these have to be
      // subtracted
602
      // correspondingly dependent on the resolution mode
603
604
605
606
607
608
      m_resolutionMode = m_numberDetectorsRead / D20_NUMBER_PIXELS;
      size_t activePixels = D20_NUMBER_PIXELS - 2 * D20_NUMBER_DEAD_PIXELS;
      m_numberDetectorsActual = m_resolutionMode * activePixels;
      // 1: low resolution, 2: nominal, 3: high resolution
      switch (m_resolutionMode) {
      case 1: {
609
610
        // low resolution mode
        m_instName += "_lr";
611
        m_numberDetectorsActual =
Gagik Vardanyan's avatar
Gagik Vardanyan committed
612
            D20_NUMBER_PIXELS - 2 * D20_NUMBER_DEAD_PIXELS;
613
614
        break;
      }
615
      case 2: {
616
        // nominal resolution
617
        m_numberDetectorsActual =
Gagik Vardanyan's avatar
Gagik Vardanyan committed
618
            2 * (D20_NUMBER_PIXELS - 2 * D20_NUMBER_DEAD_PIXELS);
619
620
        break;
      }
621
      case 3: {
622
623
        // high resolution mode
        m_instName += "_hr";
624
        m_numberDetectorsActual =
Gagik Vardanyan's avatar
Gagik Vardanyan committed
625
            3 * (D20_NUMBER_PIXELS - 2 * D20_NUMBER_DEAD_PIXELS);
626
627
628
629
        break;
      }
      default:
        throw std::runtime_error("Unknown resolution mode for instrument " +
630
                                 m_instName);
631
632
      }
    }
633
634
    g_log.debug() << "Instrument name is " << m_instName << " and has "
                  << m_numberDetectorsActual << " actual detectors.\n";
635
636
637
638
639
640
641
642
  }
}

/**
* Runs LoadInstrument as child to link the non-moving instrument to workspace
*/
void LoadILLDiffraction::loadStaticInstrument() {
  IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument");
643
  loadInst->setPropertyValue("Filename", getInstrumentFilePath(m_instName));
644
645
646
  loadInst->setProperty<MatrixWorkspace_sptr>("Workspace", m_outWorkspace);
  loadInst->setProperty("RewriteSpectraMap", OptionalBool(true));
  loadInst->execute();
647
648
}

649
650
651
652
653
654
655
656
657
658
659
660
661
662
/**
 * Runs LoadEmptyInstrument and returns a workspace with the instrument, to be
 *used in the ScanningWorkspaceBuilder.
 *
 * @return A MatrixWorkspace containing the correct instrument
 */
MatrixWorkspace_sptr LoadILLDiffraction::loadEmptyInstrument() {
  IAlgorithm_sptr loadInst = createChildAlgorithm("LoadEmptyInstrument");
  loadInst->setPropertyValue("InstrumentName", m_instName);
  loadInst->execute();

  return loadInst->getProperty("OutputWorkspace");
}

663
664
/**
* Rotates the detector to the 2theta0 read from the file
665
* @param twoTheta0Read : 2theta0 read from the file
666
*/
667
void LoadILLDiffraction::moveTwoThetaZero(double twoTheta0Read) {
668
669
  Instrument_const_sptr instrument = m_outWorkspace->getInstrument();
  IComponent_const_sptr component = instrument->getComponentByName("detector");
670
671
672
673
674
675
  double twoTheta0Actual = twoTheta0Read;
  if (m_instName == "D20") {
    twoTheta0Actual += D20_NUMBER_DEAD_PIXELS * D20_PIXEL_SIZE;
  }
  Quat rotation(twoTheta0Actual, V3D(0, 1, 0));
  g_log.debug() << "Setting 2theta0 to " << twoTheta0Actual;
676
677
678
679
  auto &componentInfo = m_outWorkspace->mutableComponentInfo();
  const auto componentIndex =
      componentInfo.indexOf(component->getComponentID());
  componentInfo.setRotation(componentIndex, rotation);
680
681
}

682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
/**
* Makes up the full path of the relevant IDF dependent on resolution mode
* @param instName : the name of the instrument (including the resolution mode
* suffix)
* @return : the full path to the corresponding IDF
*/
std::string
LoadILLDiffraction::getInstrumentFilePath(const std::string &instName) const {

  Poco::Path directory(ConfigService::Instance().getInstrumentDirectory());
  Poco::Path file(instName + "_Definition.xml");
  Poco::Path fullPath(directory, file);
  return fullPath.toString();
}

697
698
} // namespace DataHandling
} // namespace Mantid