ExperimentInfo.cpp 47.4 KB
Newer Older
1
#include "MantidAPI/ExperimentInfo.h"
2
3
4
5
6
7

#include "MantidAPI/ChopperModel.h"
#include "MantidAPI/InstrumentDataService.h"
#include "MantidAPI/ModeratorModel.h"

#include "MantidGeometry/Instrument/InstrumentDefinitionParser.h"
8
#include "MantidGeometry/Crystal/OrientedLattice.h"
9
10
#include "MantidGeometry/Instrument/ParameterMap.h"
#include "MantidGeometry/Instrument/ParComponentFactory.h"
11
#include "MantidGeometry/Instrument/XMLInstrumentParameter.h"
12

13
14
15
#include "MantidKernel/ConfigService.h"
#include "MantidKernel/DateAndTime.h"
#include "MantidKernel/InstrumentInfo.h"
16
17
#include "MantidKernel/Property.h"
#include "MantidKernel/Strings.h"
18

19
#include <boost/algorithm/string.hpp>
20
#include <boost/make_shared.hpp>
21
#include <boost/regex.hpp>
22

23
24
25
26
#include <Poco/DirectoryIterator.h>
#include <Poco/Path.h>
#include <Poco/SAX/ContentHandler.h>
#include <Poco/SAX/SAXParser.h>
27
#include <Poco/ScopedLock.h>
28
#include <nexus/NeXusException.hpp>
29

30
using namespace Mantid::Geometry;
31
using namespace Mantid::Kernel;
32
using namespace Poco::XML;
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
namespace Mantid {
namespace API {
namespace {
/// static logger object
Kernel::Logger g_log("ExperimentInfo");
}

//----------------------------------------------------------------------------------------------
/** Constructor
 */
ExperimentInfo::ExperimentInfo()
    : m_moderatorModel(), m_choppers(), m_sample(new Sample()),
      m_run(new Run()), m_parmap(new ParameterMap()),
      sptr_instrument(new Instrument()) {}

//----------------------------------------------------------------------------------------------
/** Destructor
 */
ExperimentInfo::~ExperimentInfo() {}

//---------------------------------------------------------------------------------------
/**
 * Constructs the object from a copy if the input. This leaves the new mutex
 * unlocked.
 * @param source The source object from which to initialize
 */
ExperimentInfo::ExperimentInfo(const ExperimentInfo &source) {
  this->copyExperimentInfoFrom(&source);
}

//---------------------------------------------------------------------------------------
/** Copy the experiment info data from another ExperimentInfo instance,
 * e.g. a MatrixWorkspace.
 * @param other :: the source from which to copy ExperimentInfo
 */
void ExperimentInfo::copyExperimentInfoFrom(const ExperimentInfo *other) {
  m_sample = other->m_sample;
  m_run = other->m_run;
  this->setInstrument(other->getInstrument());
  if (other->m_moderatorModel)
    m_moderatorModel = other->m_moderatorModel->clone();
  m_choppers.clear();
  for (auto iter = other->m_choppers.begin(); iter != other->m_choppers.end();
       ++iter) {
    m_choppers.push_back((*iter)->clone());
79
  }
80
81
82
83
84
85
}

//---------------------------------------------------------------------------------------
/** Clone this ExperimentInfo class into a new one
 */
ExperimentInfo *ExperimentInfo::cloneExperimentInfo() const {
86
  auto out = new ExperimentInfo();
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
  out->copyExperimentInfoFrom(this);
  return out;
}

//---------------------------------------------------------------------------------------

/// @returns A human-readable description of the object
const std::string ExperimentInfo::toString() const {
  std::ostringstream out;

  Geometry::Instrument_const_sptr inst = this->getInstrument();
  out << "Instrument: " << inst->getName() << " ("
      << inst->getValidFromDate().toFormattedString("%Y-%b-%d") << " to "
      << inst->getValidToDate().toFormattedString("%Y-%b-%d") << ")";
  out << "\n";
  if (!inst->getFilename().empty()) {
    out << "Instrument from: " << inst->getFilename();
    out << "\n";
105
106
  }

107
108
109
110
111
  // parameter files loaded
  auto paramFileVector = this->instrumentParameters().getParameterFilenames();
  for (auto itFilename = paramFileVector.begin();
       itFilename != paramFileVector.end(); ++itFilename) {
    out << "Parameters from: " << *itFilename;
112
113
    out << "\n";
  }
114

115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
  std::string runStart = getAvailableWorkspaceStartDate();
  std::string runEnd = getAvailableWorkspaceEndDate();
  std::string msgNA = "not available";
  if (runStart.empty())
    runStart = msgNA;
  if (runEnd.empty())
    runEnd = msgNA;
  out << "Run start: " << runStart << "\n";
  out << "Run end:  " << runEnd
      << "\n"; // note extra space for pseudo/approx-alignment

  if (this->sample().hasOrientedLattice()) {
    const Geometry::OrientedLattice &latt = this->sample().getOrientedLattice();
    out << "Sample: a " << std::fixed << std::setprecision(1) << latt.a()
        << ", b " << latt.b() << ", c " << latt.c();
    out << "; alpha " << std::fixed << std::setprecision(0) << latt.alpha()
        << ", beta " << latt.beta() << ", gamma " << latt.gamma();
    out << "\n";
133
  }
134
135
136
137
138
139
140
141
142
143
144
145
146
  return out.str();
}

//---------------------------------------------------------------------------------------
/** Set the instrument
* @param instr :: Shared pointer to an instrument.
*/
void ExperimentInfo::setInstrument(const Instrument_const_sptr &instr) {
  if (instr->isParametrized()) {
    sptr_instrument = instr->baseInstrument();
    m_parmap = instr->getParameterMap();
  } else {
    sptr_instrument = instr;
147
    m_parmap = boost::make_shared<ParameterMap>();
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
}

//---------------------------------------------------------------------------------------
/** Get a shared pointer to the parametrized instrument associated with this
*workspace
*
*  @return The instrument class
*/
Instrument_const_sptr ExperimentInfo::getInstrument() const {
  return Geometry::ParComponentFactory::createInstrument(sptr_instrument,
                                                         m_parmap);
}

//---------------------------------------------------------------------------------------
/**  Returns a new copy of the instrument parameters
*    @return a (new) copy of the instruments parameter map
*/
Geometry::ParameterMap &ExperimentInfo::instrumentParameters() {
  // TODO: Here duplicates cow_ptr. Figure out if there's a better way

  // Use a double-check for sharing so that we only

  // enter the critical region if absolutely necessary
  if (!m_parmap.unique()) {
    Poco::Mutex::ScopedLock lock(m_mutex);
    // Check again because another thread may have taken copy
    // and dropped reference count since previous check
    if (!m_parmap.unique()) {
      ParameterMap_sptr oldData = m_parmap;
      m_parmap = boost::make_shared<ParameterMap>(*oldData);
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
  return *m_parmap;
}

//---------------------------------------------------------------------------------------
/**  Returns a const reference to the instrument parameters.
*    @return a const reference to the instrument ParameterMap.
*/
const Geometry::ParameterMap &ExperimentInfo::instrumentParameters() const {
  return *m_parmap.get();
}

//---------------------------------------------------------------------------------------
/**  Returns a const reference to the instrument parameters.
*    @return a const reference to the instrument ParameterMap.
*/
const Geometry::ParameterMap &
ExperimentInfo::constInstrumentParameters() const {
  return *m_parmap;
}

namespace {
///@cond

/// Used for storing info about "r-position", "t-position" and "p-position"
/// parameters
/// These are translated to X,Y,Z and so must all be processed together
struct RTP {
  RTP() : radius(0.0), haveRadius(false), theta(0.0), phi(0.0) {}
  double radius;
  bool haveRadius;
  double theta;
  double phi;
};

struct ParameterValue {
  ParameterValue(const Geometry::XMLInstrumentParameter &paramInfo,
                 const API::Run &run)
      : info(paramInfo), runData(run) {}

  operator double() {
    if (info.m_logfileID.empty())
      return boost::lexical_cast<double>(info.m_value);
    else
      return info.createParamValue(
          runData.getTimeSeriesProperty<double>(info.m_logfileID));
226
  }
227
228
229
230
231
232
233
234
  operator int() { return boost::lexical_cast<int>(info.m_value); }
  operator bool() {
    if (boost::iequals(info.m_value, "true"))
      return true;
    else if (boost::iequals(info.m_value, "yes"))
      return true;
    else
      return false;
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
  const Geometry::XMLInstrumentParameter &info;
  const Run &runData;
};
///@endcond
}

//---------------------------------------------------------------------------------------
/** Add parameters to the instrument parameter map that are defined in
* instrument
*   definition file or parameter file, which may contain parameters that require
*   logfile data to be available. Logs must be loaded before running this
* method.
*/
void ExperimentInfo::populateInstrumentParameters() {
  // Get instrument and sample
  boost::shared_ptr<const Instrument> instrument =
      getInstrument()->baseInstrument();

  // Reference to the run
  const auto &runData = run();

  // Get pointer to parameter map that we may add parameters to and information
  // about
  // the parameters that my be specified in the instrument definition file (IDF)
  Geometry::ParameterMap &paramMap = instrumentParameters();
  const auto &paramInfoFromIDF = instrument->getLogfileCache();

  const double deg2rad(M_PI / 180.0);
  std::map<const IComponent *, RTP> rtpParams;

  auto cacheEnd = paramInfoFromIDF.end();
  for (auto cacheItr = paramInfoFromIDF.begin(); cacheItr != cacheEnd;
       ++cacheItr) {
    const auto &nameComp = cacheItr->first;
    const auto &paramInfo = cacheItr->second;
    const std::string &paramN = nameComp.first;
272

273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
    try {
      // Special case where user has specified r-position,t-position, and/or
      // p-position.
      // We need to know all three first to calculate a set of X,Y,Z
      if (paramN.compare(1, 9, "-position") == 0) {
        auto &rtpValues = rtpParams[paramInfo->m_component]; // If not found,
                                                             // constructs
                                                             // default
        double value = ParameterValue(*paramInfo, runData);
        if (paramN.compare(0, 1, "r") == 0) {
          rtpValues.radius = value;
          rtpValues.haveRadius = true;
        } else if (paramN.compare(0, 1, "t") == 0)
          rtpValues.theta = deg2rad * value;
        else if (paramN.compare(0, 1, "p") == 0)
          rtpValues.phi = deg2rad * value;
        else {
290
        }
291
        if (rtpValues.haveRadius) // Just overwrite x,y,z
292
        {
293
          // convert spherical coordinates to Cartesian coordinate values
294
295
296
297
298
299
300
301
          double x = rtpValues.radius * std::sin(rtpValues.theta) *
                     std::cos(rtpValues.phi);
          paramMap.addPositionCoordinate(paramInfo->m_component, "x", x);
          double y = rtpValues.radius * std::sin(rtpValues.theta) *
                     std::sin(rtpValues.phi);
          paramMap.addPositionCoordinate(paramInfo->m_component, "y", y);
          double z = rtpValues.radius * std::cos(rtpValues.theta);
          paramMap.addPositionCoordinate(paramInfo->m_component, "z", z);
302
        }
303
304
      } else {
        populateWithParameter(paramMap, paramN, *paramInfo, runData);
305
      }
306
307
308
309
    } catch (std::exception &exc) {
      g_log.information() << "Unable to add component parameter '"
                          << nameComp.first << "'. Error: " << exc.what();
      continue;
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
}

//---------------------------------------------------------------------------------------
/**
 * Replaces current parameter map with a copy of the given map
 * @ pmap const reference to parameter map whose copy replaces the current
 * parameter map
 */
void ExperimentInfo::replaceInstrumentParameters(
    const Geometry::ParameterMap &pmap) {
  this->m_parmap.reset(new ParameterMap(pmap));
}
//---------------------------------------------------------------------------------------
/**
 * exchanges contents of current parameter map with contents of other map)
 * @ pmap reference to parameter map which would exchange its contents with
 * current map
 */
void ExperimentInfo::swapInstrumentParameters(Geometry::ParameterMap &pmap) {
  this->m_parmap->swap(pmap);
}

//---------------------------------------------------------------------------------------
/**
 * Caches a lookup for the detector IDs of the members that are part of the same
 * group
 * @param mapping :: A map between a detector ID and the other IDs that are part
 * of the same
 * group.
 */
void ExperimentInfo::cacheDetectorGroupings(const det2group_map &mapping) {
  m_detgroups = mapping;
}

//---------------------------------------------------------------------------------------
/// Returns the detector IDs that make up the group that this ID is part of
const std::vector<detid_t> &
ExperimentInfo::getGroupMembers(const detid_t detID) const {
  auto iter = m_detgroups.find(detID);
  if (iter != m_detgroups.end()) {
    return iter->second;
  } else {
    throw std::runtime_error(
        "ExperimentInfo::getGroupMembers - Unable to find ID " +
        boost::lexical_cast<std::string>(detID) + " in lookup");
357
  }
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
}

//---------------------------------------------------------------------------------------
/**
 * Get a detector or detector group from an ID
 * @param detID ::
 * @returns A single detector or detector group depending on the mapping set.
 * @see set
 */
Geometry::IDetector_const_sptr
ExperimentInfo::getDetectorByID(const detid_t detID) const {
  if (m_detgroups.empty()) {
    return getInstrument()->getDetector(detID);
  } else {
    const std::vector<detid_t> &ids = this->getGroupMembers(detID);
    return getInstrument()->getDetectorG(ids);
374
  }
375
376
377
378
379
380
381
382
383
384
385
386
387
}

//---------------------------------------------------------------------------------------

/**
 * Set an object describing the moderator properties and take ownership
 * @param source :: A pointer to an object describing the source. Ownership is
 * transferred to this object
 */
void ExperimentInfo::setModeratorModel(ModeratorModel *source) {
  if (!source) {
    throw std::invalid_argument(
        "ExperimentInfo::setModeratorModel - NULL source object found.");
388
  }
389
390
391
392
393
394
395
396
  m_moderatorModel = boost::shared_ptr<ModeratorModel>(source);
}

/// Returns a reference to the source properties object
ModeratorModel &ExperimentInfo::moderatorModel() const {
  if (!m_moderatorModel) {
    throw std::runtime_error("ExperimentInfo::moderatorModel - No source "
                             "desciption has been defined");
397
  }
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
  return *m_moderatorModel;
}

//---------------------------------------------------------------------------------------
/**
 * Sets a new chopper description at a given point. The point is given by index
 * where 0 is
 * closest to the source
 * @param chopper :: A pointer to a new chopper object, this class takes
 * ownership of the pointer
 * @param index :: An optional index that specifies which chopper point the
 * chopper belongs to (default=0)
 */
void ExperimentInfo::setChopperModel(ChopperModel *chopper,
                                     const size_t index) {
  if (!chopper) {
    throw std::invalid_argument(
        "ExperimentInfo::setChopper - NULL chopper object found.");
416
  }
417
418
419
  auto iter = m_choppers.begin();
  std::advance(iter, index);
  if (index < m_choppers.size()) // Replacement
420
  {
421
422
    (*iter) = boost::shared_ptr<ChopperModel>(chopper);
  } else // Insert it
423
  {
424
    m_choppers.insert(iter, boost::shared_ptr<ChopperModel>(chopper));
425
  }
426
427
428
429
430
431
432
433
434
435
}

/**
 * Returns a const reference to a chopper description
 * @param index :: An optional index giving the point within the instrument this
 * chopper describes (default=0)
 * @return A reference to a const chopper object
 */
ChopperModel &ExperimentInfo::chopperModel(const size_t index) const {
  if (index < m_choppers.size()) {
436
437
    auto iter = m_choppers.begin();
    std::advance(iter, index);
438
439
440
441
442
443
    return **iter;
  } else {
    std::ostringstream os;
    os << "ExperimentInfo::chopper - Invalid index=" << index << ". "
       << m_choppers.size() << " chopper descriptions have been set.";
    throw std::invalid_argument(os.str());
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
}

//---------------------------------------------------------------------------------------
/** Get a constant reference to the Sample associated with this workspace.
* @return const reference to Sample object
*/
const Sample &ExperimentInfo::sample() const {
  Poco::Mutex::ScopedLock lock(m_mutex);
  return *m_sample;
}

/** Get a reference to the Sample associated with this workspace.
*  This non-const method will copy the sample if it is shared between
*  more than one workspace, and the reference returned will be to the copy.
*  Can ONLY be taken by reference!
* @return reference to sample object
*/
Sample &ExperimentInfo::mutableSample() {
  // Use a double-check for sharing so that we only
  // enter the critical region if absolutely necessary
  if (!m_sample.unique()) {
    Poco::Mutex::ScopedLock lock(m_mutex);
    // Check again because another thread may have taken copy
    // and dropped reference count since previous check
    if (!m_sample.unique()) {
      boost::shared_ptr<Sample> oldData = m_sample;
      m_sample = boost::make_shared<Sample>(*oldData);
472
473
    }
  }
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
  return *m_sample;
}

//---------------------------------------------------------------------------------------
/** Get a constant reference to the Run object associated with this workspace.
* @return const reference to run object
*/
const Run &ExperimentInfo::run() const {
  Poco::Mutex::ScopedLock lock(m_mutex);
  return *m_run;
}

/** Get a reference to the Run object associated with this workspace.
*  This non-const method will copy the Run object if it is shared between
*  more than one workspace, and the reference returned will be to the copy.
*  Can ONLY be taken by reference!
* @return reference to Run object
*/
Run &ExperimentInfo::mutableRun() {
  // Use a double-check for sharing so that we only
  // enter the critical region if absolutely necessary
  if (!m_run.unique()) {
496
    Poco::Mutex::ScopedLock lock(m_mutex);
497
498
499
500
501
    // Check again because another thread may have taken copy
    // and dropped reference count since previous check
    if (!m_run.unique()) {
      boost::shared_ptr<Run> oldData = m_run;
      m_run = boost::make_shared<Run>(*oldData);
502
    }
503
  }
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
  return *m_run;
}

/**
 * Get an experimental log either by log name or by type, e.g.
 *   - temperature_log
 *   - chopper_speed_log
 * The logs are first checked for one matching the given string and if that
 * fails then the instrument is checked for a parameter of the same name
 * and if this exists then its value is assume to be the actual log required
 * @param log :: A string giving either a specific log name or instrument
 * parameter whose
 * value is to be retrieved
 * @return A pointer to the property
 */
Kernel::Property *ExperimentInfo::getLog(const std::string &log) const {
  try {
    return run().getProperty(log);
  } catch (Kernel::Exception::NotFoundError &) {
    // No log with that name
524
  }
525
526
527
528
529
530
531
532
  // If the instrument has a parameter with that name then take the value as a
  // log name
  const std::string logName =
      instrumentParameters().getString(sptr_instrument.get(), log);
  if (logName.empty()) {
    throw std::invalid_argument(
        "ExperimentInfo::getLog - No instrument parameter named \"" + log +
        "\". Cannot access full log name");
533
  }
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
  return run().getProperty(logName);
}

/**
 * Get an experimental log as a single value either by log name or by type. @see
 * getLog
 * @param log :: A string giving either a specific log name or instrument
 * parameter whose
 * value is to be retrieved
 * @return A pointer to the property
 */
double ExperimentInfo::getLogAsSingleValue(const std::string &log) const {
  try {
    return run().getPropertyAsSingleValue(log);
  } catch (Kernel::Exception::NotFoundError &) {
    // No log with that name
550
  }
551
552
553
554
555
556
557
558
  // If the instrument has a parameter with that name then take the value as a
  // log name
  const std::string logName =
      instrumentParameters().getString(sptr_instrument.get(), log);
  if (logName.empty()) {
    throw std::invalid_argument(
        "ExperimentInfo::getLog - No instrument parameter named \"" + log +
        "\". Cannot access full log name");
559
  }
560
561
562
563
564
565
566
567
568
569
570
571
  return run().getPropertyAsSingleValue(logName);
}

//---------------------------------------------------------------------------------------
/** Utility method to get the run number
 *
 * @return the run number (int) or 0 if not found.
 */
int ExperimentInfo::getRunNumber() const {
  const Run &thisRun = run();
  if (!thisRun.hasProperty("run_number")) {
    // No run_number property, default to 0
572
    return 0;
573
574
575
576
577
578
579
580
581
582
  } else {
    Property *prop = m_run->getProperty("run_number");
    if (prop) {
      // Use the string representation. That way both a string and a number
      // property will work.
      int val;
      if (Strings::convert(prop->value(), val))
        return val;
      else
        return 0;
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
  return 0;
}

/**
 * Returns the emode for this run. It first searchs the run logs for a
 * "deltaE-mode" log and falls back to
 * the instrument if one is not found. If neither exist then the run is
 * considered Elastic.
 * @return The emode enum for the energy transfer mode of this run. Currently
 * only checks the instrument
 */
Kernel::DeltaEMode::Type ExperimentInfo::getEMode() const {
  static const char *emodeTag = "deltaE-mode";
  std::string emodeStr;
  if (run().hasProperty(emodeTag)) {
    emodeStr = run().getPropertyValueAsType<std::string>(emodeTag);
  } else if (sptr_instrument &&
             instrumentParameters().contains(sptr_instrument.get(), emodeTag)) {
    Geometry::Parameter_sptr param =
        instrumentParameters().get(sptr_instrument.get(), emodeTag);
    emodeStr = param->asString();
  } else {
    return Kernel::DeltaEMode::Elastic;
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
  return Kernel::DeltaEMode::fromString(emodeStr);
}

/**
 * Easy access to the efixed value for this run & detector ID
 * @param detID :: The detector ID to ask for the efixed mode (ignored in Direct
 * & Elastic mode). The
 * detector with ID matching that given is pulled from the instrument with this
 * method and it will
 * throw a Exception::NotFoundError if the ID is unknown.
 * @return The current EFixed value
 */
double ExperimentInfo::getEFixed(const detid_t detID) const {
  IDetector_const_sptr det = getInstrument()->getDetector(detID);
  return getEFixed(det);
}

/**
 * Easy access to the efixed value for this run & detector
 * @param detector :: The detector object to ask for the efixed mode. Only
 * required for Indirect mode
 * @return The current efixed value
 */
double
ExperimentInfo::getEFixed(const Geometry::IDetector_const_sptr detector) const {
  Kernel::DeltaEMode::Type emode = getEMode();
  if (emode == Kernel::DeltaEMode::Direct) {
    try {
      return this->run().getPropertyValueAsType<double>("Ei");
    } catch (Kernel::Exception::NotFoundError &) {
      throw std::runtime_error(
          "Experiment logs do not contain an Ei value. Have you run GetEi?");
    }
  } else if (emode == Kernel::DeltaEMode::Indirect) {
    if (!detector)
      throw std::runtime_error("ExperimentInfo::getEFixed - Indirect mode "
                               "efixed requested without a valid detector.");
    Parameter_sptr par =
        constInstrumentParameters().getRecursive(detector.get(), "Efixed");
    if (par) {
      return par->value<double>();
    } else {
      std::vector<double> efixedVec = detector->getNumberParameter("Efixed");
      if (efixedVec.empty()) {
        int detid = detector->getID();
        IDetector_const_sptr detectorSingle =
            getInstrument()->getDetector(detid);
        efixedVec = detectorSingle->getNumberParameter("Efixed");
657
      }
658
659
660
661
662
663
664
665
      if (!efixedVec.empty()) {
        return efixedVec.at(0);
      } else {
        std::ostringstream os;
        os << "ExperimentInfo::getEFixed - Indirect mode efixed requested but "
              "detector has no Efixed parameter attached. ID="
           << detector->getID();
        throw std::runtime_error(os.str());
666
667
      }
    }
668
669
670
  } else {
    throw std::runtime_error("ExperimentInfo::getEFixed - EFixed requested for "
                             "elastic mode, don't know what to do!");
671
  }
672
673
674
675
676
677
678
679
680
681
682
683
684
685
}

void ExperimentInfo::setEFixed(const detid_t detID, const double value) {
  IDetector_const_sptr det = getInstrument()->getDetector(detID);
  Geometry::ParameterMap &pmap = instrumentParameters();
  pmap.addDouble(det.get(), "Efixed", value);
}

// used to terminate SAX process
class DummyException {
public:
  std::string m_validFrom;
  std::string m_validTo;
  DummyException(std::string validFrom, std::string validTo)
686
      : m_validFrom(validFrom), m_validTo(validTo) {}
687
};
688

689
690
691
692
693
694
695
696
// SAX content handler for grapping stuff quickly from IDF
class myContentHandler : public Poco::XML::ContentHandler {
  virtual void startElement(const XMLString &, const XMLString &localName,
                            const XMLString &, const Attributes &attrList) {
    if (localName == "instrument") {
      throw DummyException(
          static_cast<std::string>(attrList.getValue("", "valid-from")),
          static_cast<std::string>(attrList.getValue("", "valid-to")));
697
698
    }
  }
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
  virtual void endElement(const XMLString &, const XMLString &,
                          const XMLString &) {}
  virtual void startDocument() {}
  virtual void endDocument() {}
  virtual void characters(const XMLChar[], int, int) {}
  virtual void endPrefixMapping(const XMLString &) {}
  virtual void ignorableWhitespace(const XMLChar[], int, int) {}
  virtual void processingInstruction(const XMLString &, const XMLString &) {}
  virtual void setDocumentLocator(const Locator *) {}
  virtual void skippedEntity(const XMLString &) {}
  virtual void startPrefixMapping(const XMLString &, const XMLString &) {}
};

//---------------------------------------------------------------------------------------
/** Return from an IDF the values of the valid-from and valid-to attributes
*
*  @param IDFfilename :: Full path of an IDF
*  @param[out] outValidFrom :: Used to return valid-from date
*  @param[out] outValidTo :: Used to return valid-to date
*/
void ExperimentInfo::getValidFromTo(const std::string &IDFfilename,
                                    std::string &outValidFrom,
                                    std::string &outValidTo) {
  SAXParser pParser;
  // Create on stack to ensure deletion. Relies on pParser also being local
  // variable.
  myContentHandler conHand;
  pParser.setContentHandler(&conHand);

  try {
    pParser.parse(IDFfilename);
  } catch (DummyException &e) {
    outValidFrom = e.m_validFrom;
    outValidTo = e.m_validTo;
  } catch (...) {
    // should throw some sensible here
735
  }
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
}

//---------------------------------------------------------------------------------------
/** Return workspace start date as an ISO 8601 string. If this info not stored
*in workspace the
*   method returns current date. This date is used for example to retrieve the
*instrument file.
*
*  @return workspace start date as a string (current time if start date not
*available)
*/
std::string ExperimentInfo::getWorkspaceStartDate() const {
  std::string date;
  try {
    date = run().startTime().toISO8601String();
  } catch (std::runtime_error &) {
    g_log.information("run_start/start_time not stored in workspace. Default "
                      "to current date.");
    date = Kernel::DateAndTime::getCurrentTime().toISO8601String();
755
  }
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
  return date;
}

//---------------------------------------------------------------------------------------
/** Return workspace start date as a formatted string (strftime, as
 *  returned by Kernel::DateAndTime) string, if available. If
 *  unavailable, an empty string is returned
 *
 *  @return workspace start date as a string (empty if no date available)
 */
std::string ExperimentInfo::getAvailableWorkspaceStartDate() const {
  std::string date;
  try {
    date = run().startTime().toFormattedString();
  } catch (std::runtime_error &) {
    g_log.information("Note: run_start/start_time not stored in workspace.");
  }
  return date;
}

//---------------------------------------------------------------------------------------
/** Return workspace end date as a formatted string (strftime style,
 *  as returned by Kernel::DateAdnTime) string, if available. If
 *  unavailable, an empty string is returned
 *
 *  @return workspace end date as a string (empty if no date available)
 */
std::string ExperimentInfo::getAvailableWorkspaceEndDate() const {
  std::string date;
  try {
    date = run().endTime().toFormattedString();
  } catch (std::runtime_error &) {
    g_log.information("Note: run_start/start_time not stored in workspace.");
  }
  return date;
}

//---------------------------------------------------------------------------------------
/** A given instrument may have multiple IDFs associated with it. This method
*return an
*  identifier which identify a given IDF for a given instrument. An IDF filename
*is
*  required to be of the form IDFname + _Definition + Identifier + .xml, the
*identifier
*  then is the part of a filename that identifies the IDF valid at a given date.
*
*  If several IDF files are valid at the given date the file with the most
*recent from
*  date is selected. If no such files are found the file with the latest from
*date is
*  selected.
*
*  If no file is found for the given instrument, an empty string is returned.
*
*  @param instrumentName :: Instrument name e.g. GEM, TOPAS or BIOSANS
*  @param date :: ISO 8601 date
*  @return full path of IDF
813
814
815
*
* @throws Exception::NotFoundError If no valid instrument definition filename is
* found
816
817
818
819
820
821
822
823
824
825
826
827
*/
std::string
ExperimentInfo::getInstrumentFilename(const std::string &instrumentName,
                                      const std::string &date) {
  if (date.empty()) {
    // Just use the current date
    g_log.debug() << "No date specified, using current date and time."
                  << std::endl;
    const std::string now =
        Kernel::DateAndTime::getCurrentTime().toISO8601String();
    // Recursively call this method, but with both parameters.
    return ExperimentInfo::getInstrumentFilename(instrumentName, now);
828
829
  }

830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
  g_log.debug() << "Looking for instrument XML file for " << instrumentName
                << " that is valid on '" << date << "'\n";
  // Lookup the instrument (long) name
  std::string instrument(
      Kernel::ConfigService::Instance().getInstrument(instrumentName).name());

  // Get the search directory for XML instrument definition files (IDFs)
  const std::vector<std::string> &directoryNames =
      Kernel::ConfigService::Instance().getInstrumentDirectories();

  boost::regex regex(instrument + "_Definition.*\\.xml",
                     boost::regex_constants::icase);
  Poco::DirectoryIterator end_iter;
  DateAndTime d(date);
  bool foundGoodFile =
      false; // True if we have found a matching file (valid at the given date)
  std::string mostRecentIDF; // store most recently starting matching IDF if
                             // found, else most recently starting IDF.
  DateAndTime refDate("1900-01-31 23:59:00"); // used to help determine the most
                                              // recently starting IDF, if none
                                              // match
  DateAndTime refDateGoodFile("1900-01-31 23:59:00"); // used to help determine
                                                      // the most recently
                                                      // starting matching IDF
  for (auto instDirs_itr = directoryNames.begin();
       instDirs_itr != directoryNames.end(); ++instDirs_itr) {
    // This will iterate around the directories from user ->etc ->install, and
    // find the first beat file
    std::string directoryName = *instDirs_itr;
    for (Poco::DirectoryIterator dir_itr(directoryName); dir_itr != end_iter;
         ++dir_itr) {
      if (!Poco::File(dir_itr->path()).isFile())
        continue;
863

864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
      std::string l_filenamePart = Poco::Path(dir_itr->path()).getFileName();
      if (regex_match(l_filenamePart, regex)) {
        g_log.debug() << "Found file: '" << dir_itr->path() << "'\n";
        std::string validFrom, validTo;
        getValidFromTo(dir_itr->path(), validFrom, validTo);
        g_log.debug() << "File '" << dir_itr->path() << " valid dates: from '"
                      << validFrom << "' to '" << validTo << "'\n";
        DateAndTime from(validFrom);
        // Use a default valid-to date if none was found.
        DateAndTime to;
        if (validTo.length() > 0)
          to.setFromISO8601(validTo);
        else
          to.setFromISO8601("2100-01-01T00:00:00");

        if (from <= d && d <= to) {
          if (from > refDateGoodFile) { // We'd found a matching file more
                                        // recently starting than any other
                                        // matching file found
            foundGoodFile = true;
            refDateGoodFile = from;
885
886
            mostRecentIDF = dir_itr->path();
          }
887
        }
888
889
890
891
892
893
        if (!foundGoodFile && (from > refDate)) { // Use most recently starting
                                                  // file, in case we don't find
                                                  // a matching file.
          refDate = from;
          mostRecentIDF = dir_itr->path();
        }
894
895
      }
    }
896
  }
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
  g_log.debug() << "IDF selected is " << mostRecentIDF << std::endl;
  return mostRecentIDF;
}

//--------------------------------------------------------------------------------------------
/** Save the object to an open NeXus file.
 * @param file :: open NeXus file
 */
void ExperimentInfo::saveExperimentInfoNexus(::NeXus::File *file) const {
  Instrument_const_sptr instrument = getInstrument();
  instrument->saveNexus(file, "instrument");
  sample().saveNexus(file, "sample");
  run().saveNexus(file, "logs");
}

//--------------------------------------------------------------------------------------------
/** Load the sample and log info from an open NeXus file.
 * @param file :: open NeXus file
 */
void ExperimentInfo::loadSampleAndLogInfoNexus(::NeXus::File *file) {
  // First, the sample and then the logs
  int sampleVersion = mutableSample().loadNexus(file, "sample");
  if (sampleVersion == 0) {
    // Old-style (before Sep-9-2011) NXS processed
    // sample field contains both the logs and the sample details
    file->openGroup("sample", "NXsample");
    this->mutableRun().loadNexus(file, "");
    file->closeGroup();
  } else {
    // Newer style: separate "logs" field for the Run object
    this->mutableRun().loadNexus(file, "logs");
928
  }
929
930
931
932
933
}

//--------------------------------------------------------------------------------------------
/** Load the object from an open NeXus file.
 * @param file :: open NeXus file
Nick Draper's avatar
Nick Draper committed
934
 * @param nxFilename :: the filename of the nexus file
935
936
937
938
939
940
941
 * @param[out] parameterStr :: special string for all the parameters.
 *             Feed that to ExperimentInfo::readParameterMap() after the
 * instrument is done.
 * @throws Exception::NotFoundError If instrument definition is not in the nexus
 * file and cannot
 *                                  be loaded from the IDF.
 */
942
void ExperimentInfo::loadExperimentInfoNexus(const std::string &nxFilename,
Nick Draper's avatar
Nick Draper committed
943
                                             ::NeXus::File *file,
944
945
946
947
                                             std::string &parameterStr) {
  // load sample and log info
  loadSampleAndLogInfoNexus(file);

Nick Draper's avatar
Nick Draper committed
948
  loadInstrumentInfoNexus(nxFilename, file, parameterStr);
949
950
951
952
}

//--------------------------------------------------------------------------------------------
/** Load the instrument from an open NeXus file.
Nick Draper's avatar
Nick Draper committed
953
 * @param nxFilename :: the filename of the nexus file
954
 * @param file :: open NeXus file
955
956
957
958
959
960
961
 * @param[out] parameterStr :: special string for all the parameters.
 *             Feed that to ExperimentInfo::readParameterMap() after the
 * instrument is done.
 * @throws Exception::NotFoundError If instrument definition is not in the nexus
 * file and cannot
 *                                  be loaded from the IDF.
 */
962
void ExperimentInfo::loadInstrumentInfoNexus(const std::string &nxFilename,
Nick Draper's avatar
Nick Draper committed
963
                                             ::NeXus::File *file,
964
                                             std::string &parameterStr) {
965

966
  // Open instrument group
967
  file->openGroup("instrument", "NXinstrument");
968

969
  // Try to get the instrument embedded in the Nexus file
970
971
  std::string instrumentName;
  std::string instrumentXml;
972
  loadEmbeddedInstrumentInfoNexus(file, instrumentName, instrumentXml);
973

974
  // load parameters if found
975
  loadInstrumentParametersNexus(file, parameterStr);
976

977
978
  // Close the instrument group
  file->closeGroup();
979

980
  // Set the instrument given the name and and XML obtained
981
  setInstumentFromXML(nxFilename, instrumentName, instrumentXml);
982
983
}

984
//--------------------------------------------------------------------------------------------
985
986
/** Load the instrument from an open NeXus file without reading any parameters
 * (yet).
987
988
989
990
991
992
993
 * @param nxFilename :: the filename of the nexus file
 * @param file :: open NeXus file
 * instrument is done.
 * @throws Exception::NotFoundError If instrument definition is not in the nexus
 * file and cannot
 *                                  be loaded from the IDF.
 */
994
995
void ExperimentInfo::loadInstrumentInfoNexus(const std::string &nxFilename,
                                             ::NeXus::File *file) {
996

997
  // Open instrument group
998
999
  file->openGroup("instrument", "NXinstrument");

1000
  // Try to get the instrument embedded in the Nexus file
For faster browsing, not all history is shown. View entire blame