PeaksWorkspace.cpp 34.2 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 "MantidDataObjects/PeaksWorkspace.h"
8
9
#include "MantidAPI/Run.h"
#include "MantidAPI/Sample.h"
Peterson, Peter's avatar
Peterson, Peter committed
10
#include "MantidAPI/WorkspaceFactory.h"
11
12
#include "MantidGeometry/Crystal/OrientedLattice.h"
#include "MantidGeometry/Instrument/Goniometer.h"
13
#include "MantidKernel/IPropertyManager.h"
14
#include "MantidKernel/Logger.h"
15
#include "MantidKernel/UnitConversion.h"
16

17
// clang-format off
18
#include <nexus/NeXusFile.hpp>
19
20
#include <nexus/NeXusException.hpp>
// clang-format on
21
22

#include <cmath>
23
24
25
26

using namespace Mantid::API;
using namespace Mantid::Kernel;
using namespace Mantid::Geometry;
Peterson, Peter's avatar
Peterson, Peter committed
27

28
29
30
namespace Mantid {
namespace DataObjects {
/// Register the workspace as a type
31
DECLARE_WORKSPACE(PeaksWorkspace)
32

33
34
Mantid::Kernel::Logger g_log("PeaksWorkspace");

Owen Arnold's avatar
Owen Arnold committed
35
//---------------------------------------------------------------------------------------------
36
37
38
39
/** Constructor. Create a table with all the required columns.
 *
 * @return PeaksWorkspace object
 */
40
41
42
43
PeaksWorkspace::PeaksWorkspace()
    : IPeaksWorkspace(), peaks(), columns(), columnNames(),
      m_coordSystem(None) {
  initColumns();
44
45
  // PeaksWorkspace does not use the grouping mechanism of ExperimentInfo.
  setNumberOfDetectorGroups(0);
46
}
47

48
49
50
51
52
//---------------------------------------------------------------------------------------------
/** Copy constructor
 *
 * @param other :: other PeaksWorkspace to copy from
 */
53
// PeaksWorkspace::PeaksWorkspace(const PeaksWorkspace &other) = default;
54
PeaksWorkspace::PeaksWorkspace(const PeaksWorkspace &other)
55
56
    : IPeaksWorkspace(other), peaks(other.peaks), columns(), columnNames(),
      m_coordSystem(other.m_coordSystem) {
57
  initColumns();
58
59
  // PeaksWorkspace does not use the grouping mechanism of ExperimentInfo.
  setNumberOfDetectorGroups(0);
60
}
61

62
63
/** Comparator class for sorting peaks by one or more criteria
 */
64
class PeakComparator {
65
public:
66
67
  using ColumnAndDirection = PeaksWorkspace::ColumnAndDirection;
  std::vector<ColumnAndDirection> &criteria;
68
69
70
71
72

  /** Constructor for the comparator for sorting peaks
   * @param criteria : a vector with a list of pairs: column name, bool;
   *        where bool = true for ascending, false for descending sort.
   */
73
  explicit PeakComparator(std::vector<ColumnAndDirection> &criteria)
74
75
76
77
      : criteria(criteria) {}

  /** Compare two peaks using the stored criteria */
  inline bool operator()(const Peak &a, const Peak &b) {
78
79
80
    for (const auto &name : criteria) {
      const auto &col = name.first;
      const bool ascending = name.second;
81
82
83
      bool lessThan = false;
      if (col == "BankName") {
        // If this criterion is equal, move on to the next one
84
85
        const std::string valA = a.getBankName();
        const std::string valB = b.getBankName();
86
87
88
89
90
91
        // Move on to lesser criterion if equal
        if (valA == valB)
          continue;
        lessThan = (valA < valB);
      } else {
        // General double comparison
92
93
        const double valA = a.getValueByColName(col);
        const double valB = b.getValueByColName(col);
94
95
96
97
        // Move on to lesser criterion if equal
        if (valA == valB)
          continue;
        lessThan = (valA < valB);
Owen Arnold's avatar
Owen Arnold committed
98
      }
99
100
101
      // Flip the sign of comparison if descending.
      if (ascending)
        return lessThan;
Owen Arnold's avatar
Owen Arnold committed
102
      else
103
        return !lessThan;
104
    }
105
106
107
108
    // If you reach here, all criteria were ==; so not <, so return false
    return false;
  }
};
109

110
111
112
113
114
115
116
117
//---------------------------------------------------------------------------------------------
/** Sort the peaks by one or more criteria
 *
 * @param criteria : a vector with a list of pairs: column name, bool;
 *        where bool = true for ascending, false for descending sort.
 *        The peaks are sorted by the first criterion first, then the 2nd if
 *equal, etc.
 */
118
void PeaksWorkspace::sort(std::vector<ColumnAndDirection> &criteria) {
119
120
121
  PeakComparator comparator(criteria);
  std::stable_sort(peaks.begin(), peaks.end(), comparator);
}
122

123
124
125
126
//---------------------------------------------------------------------------------------------
/** @return the number of peaks
 */
int PeaksWorkspace::getNumberPeaks() const { return int(peaks.size()); }
127

128
129
130
131
132
//---------------------------------------------------------------------------------------------
/** @return the convention
 */
std::string PeaksWorkspace::getConvention() const { return convention; }

133
134
135
136
137
138
139
140
141
142
143
//---------------------------------------------------------------------------------------------
/** Removes the indicated peak
 * @param peakNum  the peak to remove. peakNum starts at 0
 */
void PeaksWorkspace::removePeak(const int peakNum) {
  if (peakNum >= static_cast<int>(peaks.size()) || peakNum < 0) {
    throw std::invalid_argument(
        "PeaksWorkspace::removePeak(): peakNum is out of range.");
  }
  peaks.erase(peaks.begin() + peakNum);
}
144

145
/** Removes multiple peaks
LamarMoore's avatar
LamarMoore committed
146
147
 * @param badPeaks peaks to be removed
 */
148
149
void PeaksWorkspace::removePeaks(std::vector<int> badPeaks) {
  if (badPeaks.empty())
Matthew Bowles's avatar
Matthew Bowles committed
150
    return;
Lynch, Vickie's avatar
Lynch, Vickie committed
151
152
153
154
155
156
  // if index of peak is in badPeaks remove
  int ip = -1;
  auto it =
      std::remove_if(peaks.begin(), peaks.end(), [&ip, badPeaks](Peak &pk) {
        (void)pk;
        ip++;
157
158
        return std::any_of(badPeaks.cbegin(), badPeaks.cend(),
                           [ip](int badPeak) { return badPeak == ip; });
Lynch, Vickie's avatar
Lynch, Vickie committed
159
160
      });
  peaks.erase(it, peaks.end());
161
162
}

163
164
//---------------------------------------------------------------------------------------------
/** Add a peak to the list
165
 * @param ipeak :: Peak object to add (copy) into this.
166
 */
Owen Arnold's avatar
Owen Arnold committed
167
void PeaksWorkspace::addPeak(const Geometry::IPeak &ipeak) {
168
  if (dynamic_cast<const Peak *>(&ipeak)) {
169
    peaks.emplace_back((const Peak &)ipeak);
170
  } else {
171
    peaks.emplace_back(Peak(ipeak));
172
173
  }
}
174

175
176
177
178
179
//---------------------------------------------------------------------------------------------
/** Add a peak to the list
 * @param position :: position on the peak in the specified coordinate frame
 * @param frame :: the coordinate frame that the position is specified in
 */
180
181
void PeaksWorkspace::addPeak(const V3D &position,
                             const SpecialCoordinateSystem &frame) {
182
183
184
185
  auto peak = createPeak(position, frame);
  addPeak(*peak);
}

186
187
//---------------------------------------------------------------------------------------------
/** Add a peak to the list
188
 * @param peak :: Peak object to add (move) into this.
189
 */
190
void PeaksWorkspace::addPeak(Peak &&peak) { peaks.emplace_back(peak); }
191

192
193
194
195
196
197
198
199
200
201
202
203
//---------------------------------------------------------------------------------------------
/** Return a reference to the Peak
 * @param peakNum :: index of the peak to get.
 * @return a reference to a Peak object.
 */
Peak &PeaksWorkspace::getPeak(const int peakNum) {
  if (peakNum >= static_cast<int>(peaks.size()) || peakNum < 0) {
    throw std::invalid_argument(
        "PeaksWorkspace::getPeak(): peakNum is out of range.");
  }
  return peaks[peakNum];
}
204

205
206
207
208
209
210
211
212
213
214
215
216
//---------------------------------------------------------------------------------------------
/** Return a const reference to the Peak
 * @param peakNum :: index of the peak to get.
 * @return a reference to a Peak object.
 */
const Peak &PeaksWorkspace::getPeak(const int peakNum) const {
  if (peakNum >= static_cast<int>(peaks.size()) || peakNum < 0) {
    throw std::invalid_argument(
        "PeaksWorkspace::getPeak(): peakNum is out of range.");
  }
  return peaks[peakNum];
}
217

218
219
220
//---------------------------------------------------------------------------------------------
/** Creates an instance of a Peak BUT DOES NOT ADD IT TO THE WORKSPACE
 * @param QLabFrame :: Q of the center of the peak, in reciprocal space
221
222
 * @param detectorDistance :: optional distance between the sample and the
 * detector. You do NOT need to explicitly provide this distance.
223
224
 * @return a pointer to a new Peak object.
 */
225
std::unique_ptr<Geometry::IPeak>
Hahn, Steven's avatar
Hahn, Steven committed
226
PeaksWorkspace::createPeak(const Kernel::V3D &QLabFrame,
227
                           boost::optional<double> detectorDistance) const {
228
  // create a peak using the qLab frame
229
230
  std::unique_ptr<IPeak> peak = std::make_unique<Peak>(
      this->getInstrument(), QLabFrame, detectorDistance);
231
  // Set the goniometer
232
  peak->setGoniometerMatrix(this->run().getGoniometer().getR());
233
234
235
236
  // Take the run number from this
  peak->setRunNumber(this->getRunNumber());

  return peak;
237
}
238

239
240
241
242
243
244
245
246
247
248
//---------------------------------------------------------------------------------------------
/** Creates an instance of a Peak BUT DOES NOT ADD IT TO THE WORKSPACE
 * @param position :: position of the center of the peak, in reciprocal space
 * @param frame :: the coordinate system that the position is specified in
 * detector. You do NOT need to explicitly provide this distance.
 * @return a pointer to a new Peak object.
 */
std::unique_ptr<Geometry::IPeak>
PeaksWorkspace::createPeak(const Kernel::V3D &position,
                           const Kernel::SpecialCoordinateSystem &frame) const {
249
  if (frame == Mantid::Kernel::HKL) {
250
    return createPeakHKL(position);
251
  } else if (frame == Mantid::Kernel::QLab) {
252
    return createPeak(position);
253
  } else {
254
    return createPeakQSample(position);
255
  }
256
257
258
259
}

//---------------------------------------------------------------------------------------------
/** Creates an instance of a Peak BUT DOES NOT ADD IT TO THE WORKSPACE
260
261
 * @param position :: QSample position of the center of the peak, in reciprocal
 * space
262
263
264
 * detector. You do NOT need to explicitly provide this distance.
 * @return a pointer to a new Peak object.
 */
265
266
std::unique_ptr<IPeak>
PeaksWorkspace::createPeakQSample(const V3D &position) const {
267
  // Create a peak from QSampleFrame
268
269
270
271

  Geometry::Goniometer goniometer;

  LogManager_const_sptr props = getLogs();
272
273
274
275
276
277
278
279
280
281
282
283
284
285
  // See if we can get a wavelength/energy
  // Then assume constant wavelenth
  double wavelength(0);
  if (props->hasProperty("wavelength")) {
    wavelength = props->getPropertyValueAsType<double>("wavelength");
  } else if (props->hasProperty("energy")) {
    wavelength = Kernel::UnitConversion::run(
        "Energy", "Wavelength", props->getPropertyValueAsType<double>("energy"),
        0, 0, 0, Kernel::DeltaEMode::Elastic, 0);
  } else if (getInstrument()->hasParameter("wavelength")) {
    wavelength = getInstrument()->getNumberParameter("wavelength").at(0);
  }

  if (wavelength > 0) {
286
    goniometer.calcFromQSampleAndWavelength(position, wavelength);
287
288
289
    g_log.information() << "Found goniometer rotation to be "
                        << goniometer.getEulerAngles()[0]
                        << " degrees for Q sample = " << position << "\n";
290
291
292
  } else {
    goniometer = run().getGoniometer();
  }
293
  // create a peak using the qLab frame
294
295
  std::unique_ptr<IPeak> peak =
      std::make_unique<Peak>(getInstrument(), position, goniometer.getR());
296
297
298
299
300
  // Take the run number from this
  peak->setRunNumber(getRunNumber());
  return peak;
}

301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/**
 * Returns selected information for a "peak" at QLabFrame.
 *
 * @param qFrame      An arbitrary position in Q-space.  This does not have to
 *be the
 *                    position of a peak.
 * @param labCoords   Set true if the position is in the lab coordinate system,
 *false if
 *                    it is in the sample coordinate system.
 * @return a vector whose elements contain different information about the
 *"peak" at that position.
 *         each element is a pair of description of information and the string
 *form for the corresponding
 *         value.
 */
std::vector<std::pair<std::string, std::string>>
Hahn, Steven's avatar
Hahn, Steven committed
317
PeaksWorkspace::peakInfo(const Kernel::V3D &qFrame, bool labCoords) const {
318
319
320
321
  std::vector<std::pair<std::string, std::string>> Result;
  std::ostringstream oss;
  oss << std::setw(12) << std::fixed << std::setprecision(3) << (qFrame.norm());
  std::pair<std::string, std::string> QMag("|Q|", oss.str());
322
  Result.emplace_back(QMag);
323
324
325
326
327
328
329
330
331

  oss.str("");
  oss.clear();
  oss << std::setw(12) << std::fixed << std::setprecision(3)
      << (2.0 * M_PI / qFrame.norm());

  std::pair<std::string, std::string> dspc("d-spacing", oss.str());
  oss.str("");
  oss.clear();
332
  Result.emplace_back(dspc);
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348

  int seqNum = -1;
  bool hasOneRunNumber = true;
  int runNum = -1;
  int NPeaks = getNumberPeaks();
  try {
    double minDist = 10000000;
    for (int i = 0; i < NPeaks; i++) {
      Peak pk = getPeak(i);
      V3D Q = pk.getQLabFrame();
      if (!labCoords)
        Q = pk.getQSampleFrame();
      double D = qFrame.distance(Q);
      if (D < minDist) {
        minDist = D;
        seqNum = i;
349
      }
350

351
352
353
354
355
356
357
358
359
360
361
362
      int run = pk.getRunNumber();
      if (runNum < 0)
        runNum = run;
      else if (runNum != run)
        hasOneRunNumber = false;
    }
  } catch (...) {
    seqNum = -1; // peak could have been removed
  }
  V3D Qlab = qFrame;
  V3D Qsamp;
  Kernel::Matrix<double> Gon(3, 3, true);
363

364
365
366
  if (seqNum >= 0 && NPeaks == getNumberPeaks())
    Gon = getPeak(seqNum).getGoniometerMatrix();
  if (labCoords) {
367

368
369
370
    Kernel::Matrix<double> InvGon(Gon);
    InvGon.Invert();
    Qsamp = InvGon * Qlab;
371

372
373
374
375
  } else {
    Qsamp = qFrame;
    Qlab = Gon * Qsamp;
  }
376

377
  if (labCoords || seqNum >= 0)
378

379
380
381
  {
    std::pair<std::string, std::string> QlabStr(
        "Qlab", boost::lexical_cast<std::string>(Qlab));
382
    Result.emplace_back(QlabStr);
383
  }
384

385
  if (!labCoords || seqNum >= 0) {
386

387
388
    std::pair<std::string, std::string> QsampStr(
        "QSample", boost::lexical_cast<std::string>(Qsamp));
389
    Result.emplace_back(QsampStr);
390
  }
391

392
  try {
393
394
395
    IPeak_uptr iPeak = createPeak(Qlab);
    Peak_uptr peak(static_cast<DataObjects::Peak*>(iPeak.release()));

396
    if (sample().hasOrientedLattice()) {
397

398
399
      peak->setGoniometerMatrix(Gon);
      const Geometry::OrientedLattice &lat = (sample().getOrientedLattice());
400

401
402
403
404
      const Kernel::Matrix<double> &UB0 = lat.getUB();
      Kernel::Matrix<double> UB(UB0);
      UB.Invert();
      V3D hkl = UB * Qsamp / 2 / M_PI;
Owen Arnold's avatar
Owen Arnold committed
405

406
407
      std::pair<std::string, std::string> HKL(
          "HKL", boost::lexical_cast<std::string>(hkl));
408
      Result.emplace_back(HKL);
409
410
    }

411
    if (hasOneRunNumber) {
412
413
      std::pair<std::string, std::string> runn("RunNumber",
                                               "   " + std::to_string(runNum));
414
      Result.emplace_back(runn);
415
    }
416

417
418
419
420
421
422
423
    //------- Now get phi, chi and omega ----------------
    Geometry::Goniometer GonG(Gon);
    std::vector<double> OmegaChiPhi = GonG.getEulerAngles("YZY");
    Kernel::V3D PhiChiOmega(OmegaChiPhi[2], OmegaChiPhi[1], OmegaChiPhi[0]);

    std::pair<std::string, std::string> GRead(
        "Goniometer Angles", boost::lexical_cast<std::string>(PhiChiOmega));
424
    Result.emplace_back(GRead);
425
426

    std::pair<std::string, std::string> SeqNum(
427
        "Seq Num,1st=1", "    " + std::to_string(seqNum + 1));
428
    Result.emplace_back(SeqNum);
429
430
431
432

    oss << std::setw(12) << std::fixed << std::setprecision(3)
        << (peak->getWavelength());
    std::pair<std::string, std::string> wl("Wavelength", oss.str());
433
    Result.emplace_back(wl);
434
435
436
437
438
439
440
    oss.str("");
    oss.clear();

    if (peak->findDetector()) {
      std::pair<std::string, std::string> detpos(
          "Position(x,y,z)",
          boost::lexical_cast<std::string>(peak->getDetPos()));
441
      Result.emplace_back(detpos);
442
443
444
445

      oss << std::setw(15) << std::fixed << std::setprecision(3)
          << (peak->getTOF());
      std::pair<std::string, std::string> tof("TOF", oss.str());
446
      Result.emplace_back(tof);
447
448
449
450
451
452
      oss.str("");
      oss.clear();

      oss << std::setw(12) << std::fixed << std::setprecision(3)
          << (peak->getFinalEnergy());
      std::pair<std::string, std::string> Energy("Energy", oss.str());
453
      Result.emplace_back(Energy);
454
455
456
457
      oss.str("");
      oss.clear();

      std::pair<std::string, std::string> row(
458
          "Row", "    " + std::to_string(peak->getRow()));
459
      Result.emplace_back(row);
460
461

      std::pair<std::string, std::string> col(
462
          "Col", "    " + std::to_string(peak->getCol()));
463
      Result.emplace_back(col);
464
465
466

      std::pair<std::string, std::string> bank("Bank",
                                               "    " + peak->getBankName());
467
      Result.emplace_back(bank);
468
469
470
471

      oss << std::setw(12) << std::fixed << std::setprecision(3)
          << (peak->getScattering());
      std::pair<std::string, std::string> scat("Scattering Angle", oss.str());
472
      Result.emplace_back(scat);
473
    }
474

475
476
477
478
479
  } catch (...) // Impossible position
  {
  }
  return Result;
}
480

481
482
483
484
485
486
487
/**
 * Create a Peak from a HKL value provided by the client.
 *
 *
 * @param HKL : reciprocal lattice vector coefficients
 * @return Fully formed peak.
 */
488
std::unique_ptr<IPeak> PeaksWorkspace::createPeakHKL(const V3D &HKL) const {
489
490
491
  /*
   The following allows us to add peaks where we have a single UB to work from.
   */
492
493
  const auto &lattice = this->sample().getOrientedLattice();
  const auto &goniometer = this->run().getGoniometer();
494

495
496
  // Calculate qLab from q HKL. As per Busing and Levy 1967, q_lab_frame = 2pi *
  // Goniometer * UB * HKL
497
  const V3D qLabFrame = goniometer.getR() * lattice.getUB() * HKL * 2 * M_PI;
498

499
  // create a peak using the qLab frame
500
501
502
  // This should calculate the detector positions too
  std::unique_ptr<IPeak> peak =
      std::make_unique<Peak>(this->getInstrument(), qLabFrame);
503
504
  // We need to set HKL separately to keep things consistent.
  peak->setHKL(HKL[0], HKL[1], HKL[2]);
505
  peak->setIntHKL(peak->getHKL());
506
507
508
509
  // Set the goniometer
  peak->setGoniometerMatrix(goniometer.getR());
  // Take the run number from this
  peak->setRunNumber(this->getRunNumber());
510

511
  return peak;
512
513
}

514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
/**
 * Returns selected information for a "peak" at QLabFrame.
 *
 * @param qFrame      An arbitrary position in Q-space.  This does not have to
 *be the
 *                    position of a peak.
 * @param labCoords  Set true if the position is in the lab coordinate system,
 *false if
 *                    it is in the sample coordinate system.
 * @return a vector whose elements contain different information about the
 *"peak" at that position.
 *         each element is a pair of description of information and the string
 *form for the corresponding
 *         value.
 */
Hahn, Steven's avatar
Hahn, Steven committed
529
530
int PeaksWorkspace::peakInfoNumber(const Kernel::V3D &qFrame,
                                   bool labCoords) const {
531
532
533
534
  std::vector<std::pair<std::string, std::string>> Result;
  std::ostringstream oss;
  oss << std::setw(12) << std::fixed << std::setprecision(3) << (qFrame.norm());
  std::pair<std::string, std::string> QMag("|Q|", oss.str());
535
  Result.emplace_back(QMag);
536
537
538
539
540
541
542
543
544

  oss.str("");
  oss.clear();
  oss << std::setw(12) << std::fixed << std::setprecision(3)
      << (2.0 * M_PI / qFrame.norm());

  std::pair<std::string, std::string> dspc("d-spacing", oss.str());
  oss.str("");
  oss.clear();
545
  Result.emplace_back(dspc);
546
547
548
549
550
551
552
553
554
555
556
557
558

  int seqNum = -1;
  double minDist = 10000000;

  for (int i = 0; i < getNumberPeaks(); i++) {
    Peak pk = getPeak(i);
    V3D Q = pk.getQLabFrame();
    if (!labCoords)
      Q = pk.getQSampleFrame();
    double D = qFrame.distance(Q);
    if (D < minDist) {
      minDist = D;
      seqNum = i + 1;
559
    }
560
561
562
  }
  return seqNum;
}
Peterson, Peter's avatar
Peterson, Peter committed
563

564
565
566
567
568
569
570
571
572
573
574
575
576
577
//---------------------------------------------------------------------------------------------
/** Return a reference to the Peaks vector */
std::vector<Peak> &PeaksWorkspace::getPeaks() { return peaks; }

/** Return a const reference to the Peaks vector */
const std::vector<Peak> &PeaksWorkspace::getPeaks() const { return peaks; }

/** Getter for the integration status.
 @return TRUE if it has been integrated using a peak integration algorithm.
 */
bool PeaksWorkspace::hasIntegratedPeaks() const {
  bool ret = false;
  const std::string peaksIntegrated = "PeaksIntegrated";
  if (this->run().hasProperty(peaksIntegrated)) {
578
    const auto value = boost::lexical_cast<int>(
579
580
581
582
583
        this->run().getProperty(peaksIntegrated)->value());
    ret = (value != 0);
  }
  return ret;
}
584

585
586
587
588
589
//---------------------------------------------------------------------------------------------
/// Return the memory used in bytes
size_t PeaksWorkspace::getMemorySize() const {
  return getNumberPeaks() * sizeof(Peak);
}
590

591
592
593
594
595
596
597
598
599
600
601
602
603
//---------------------------------------------------------------------------------------------
/**
 *  Creates a new TableWorkspace with detailing the contributing Detector IDs.
 * The table
 *  will have 2 columns: Index &  DetectorID, where Index maps into the current
 * index
 *  within the PeaksWorkspace of the peak
 */
API::ITableWorkspace_sptr PeaksWorkspace::createDetectorTable() const {
  auto table = API::WorkspaceFactory::Instance().createTable("TableWorkspace");
  table->addColumn("int", "Index");
  table->addColumn("int", "DetectorID");

604
  const auto npeaks(static_cast<int>(this->rowCount()));
605
606
607
608
609
610
611
612
613
614
  int nrows(0);
  for (int i = 0; i < npeaks; ++i) {
    const Peak &peak = this->peaks[i];
    auto detIDs = peak.getContributingDetIDs();
    auto itEnd = detIDs.end();
    for (auto it = detIDs.begin(); it != itEnd; ++it) {
      table->appendRow();
      table->cell<int>(nrows, 0) = i;
      table->cell<int>(nrows, 1) = *it;
      ++nrows;
Owen Arnold's avatar
Owen Arnold committed
615
    }
616
  }
617

618
619
  return table;
}
Peterson, Peter's avatar
Peterson, Peter committed
620

621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//---------------------------------------------------------------------------------------------
/** Initialize all columns */
void PeaksWorkspace::initColumns() {
  // Note: The column types are controlled in PeakColumn.cpp
  addPeakColumn("RunNumber");
  addPeakColumn("DetID");
  addPeakColumn("h");
  addPeakColumn("k");
  addPeakColumn("l");
  addPeakColumn("Wavelength");
  addPeakColumn("Energy");
  addPeakColumn("TOF");
  addPeakColumn("DSpacing");
  addPeakColumn("Intens");
  addPeakColumn("SigInt");
636
  addPeakColumn("Intens/SigInt");
637
638
639
640
641
642
  addPeakColumn("BinCount");
  addPeakColumn("BankName");
  addPeakColumn("Row");
  addPeakColumn("Col");
  addPeakColumn("QLab");
  addPeakColumn("QSample");
643
  addPeakColumn("PeakNumber");
644
  addPeakColumn("TBar");
645
}
Peterson, Peter's avatar
Peterson, Peter committed
646

647
648
649
650
651
652
653
//---------------------------------------------------------------------------------------------
/**
 * Add a PeakColumn
 * @param name :: The name of the column
 **/
void PeaksWorkspace::addPeakColumn(const std::string &name) {
  // Create the PeakColumn.
654
655
  columns.emplace_back(
      std::make_shared<DataObjects::PeakColumn>(this->peaks, name));
656
  // Cache the names
657
  columnNames.emplace_back(name);
658
}
Peterson, Peter's avatar
Peterson, Peter committed
659

660
661
662
663
664
665
666
667
668
//---------------------------------------------------------------------------------------------
/// @return the index of the column with the given name.
size_t PeaksWorkspace::getColumnIndex(const std::string &name) const {
  for (size_t i = 0; i < columns.size(); i++)
    if (columns[i]->name() == name)
      return i;
  throw std::invalid_argument("Column named " + name +
                              " was not found in the PeaksWorkspace.");
}
Peterson, Peter's avatar
Peterson, Peter committed
669

670
671
//---------------------------------------------------------------------------------------------
/// Gets the shared pointer to a column by index.
672
std::shared_ptr<Mantid::API::Column> PeaksWorkspace::getColumn(size_t index) {
673
674
675
676
677
  if (index >= columns.size())
    throw std::invalid_argument(
        "PeaksWorkspace::getColumn() called with invalid index.");
  return columns[index];
}
678

679
680
//---------------------------------------------------------------------------------------------
/// Gets the shared pointer to a column by index.
681
std::shared_ptr<const Mantid::API::Column>
682
683
684
685
686
687
PeaksWorkspace::getColumn(size_t index) const {
  if (index >= columns.size())
    throw std::invalid_argument(
        "PeaksWorkspace::getColumn() called with invalid index.");
  return columns[index];
}
688

689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
void PeaksWorkspace::saveNexus(::NeXus::File *file) const {

  // Number of Peaks
  const size_t np(peaks.size());

  // Column vectors for peaks table
  std::vector<int> detectorID(np);
  std::vector<double> H(np);
  std::vector<double> K(np);
  std::vector<double> L(np);
  std::vector<double> intensity(np);
  std::vector<double> sigmaIntensity(np);
  std::vector<double> binCount(np);
  std::vector<double> initialEnergy(np);
  std::vector<double> finalEnergy(np);
  std::vector<double> waveLength(np);
  std::vector<double> scattering(np);
  std::vector<double> dSpacing(np);
  std::vector<double> TOF(np);
  std::vector<int> runNumber(np);
709
  std::vector<int> peakNumber(np);
710
  std::vector<double> tbar(np);
711
  std::vector<double> goniometerMatrix(9 * np);
712
  std::vector<std::string> shapes(np);
713
714

  // Populate column vectors from Peak Workspace
715
  size_t maxShapeJSONLength = 0;
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
  for (size_t i = 0; i < np; i++) {
    Peak p = peaks[i];
    detectorID[i] = p.getDetectorID();
    H[i] = p.getH();
    K[i] = p.getK();
    L[i] = p.getL();
    intensity[i] = p.getIntensity();
    sigmaIntensity[i] = p.getSigmaIntensity();
    binCount[i] = p.getBinCount();
    initialEnergy[i] = p.getInitialEnergy();
    finalEnergy[i] = p.getFinalEnergy();
    waveLength[i] = p.getWavelength();
    scattering[i] = p.getScattering();
    dSpacing[i] = p.getDSpacing();
    TOF[i] = p.getTOF();
    runNumber[i] = p.getRunNumber();
732
    peakNumber[i] = p.getPeakNumber();
733
    tbar[i] = p.getAbsorptionWeightedPathLength();
734
    {
735
736
737
738
739
740
741
742
743
744
      Matrix<double> gm = p.getGoniometerMatrix();
      goniometerMatrix[9 * i] = gm[0][0];
      goniometerMatrix[9 * i + 1] = gm[1][0];
      goniometerMatrix[9 * i + 2] = gm[2][0];
      goniometerMatrix[9 * i + 3] = gm[0][1];
      goniometerMatrix[9 * i + 4] = gm[1][1];
      goniometerMatrix[9 * i + 5] = gm[2][1];
      goniometerMatrix[9 * i + 6] = gm[0][2];
      goniometerMatrix[9 * i + 7] = gm[1][2];
      goniometerMatrix[9 * i + 8] = gm[2][2];
745
    }
746
747
    const std::string shapeJSON = p.getPeakShape().toJSON();
    shapes[i] = shapeJSON;
748
749
    if (shapeJSON.size() > maxShapeJSONLength) {
      maxShapeJSONLength = shapeJSON.size();
750
    }
751
  }
752

753
  // Start Peaks Workspace in Nexus File
754
755
756
  const std::string specifyInteger = "An integer";
  const std::string specifyDouble = "A double";
  const std::string specifyString = "A string";
757
758
759
  file->makeGroup("peaks_workspace", "NXentry",
                  true); // For when peaksWorkspace can be loaded

760
761
  // Coordinate system
  file->writeData("coordinate_system", static_cast<uint32_t>(m_coordSystem));
762

763
764
765
766
767
  // Write out the Qconvention
  // ki-kf for Inelastic convention; kf-ki for Crystallography convention
  std::string m_QConvention = this->getConvention();
  file->putAttr("QConvention", m_QConvention);

768
769
770
  // Detectors column
  file->writeData("column_1", detectorID);
  file->openData("column_1");
771
  file->putAttr("name", "Detector ID");
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
  file->putAttr("interpret_as", specifyInteger);
  file->putAttr("units", "Not known");
  file->closeData();

  // H column
  file->writeData("column_2", H);
  file->openData("column_2");
  file->putAttr("name", "H");
  file->putAttr("interpret_as", specifyDouble);
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->closeData();

  // K column
  file->writeData("column_3", K);
  file->openData("column_3");
  file->putAttr("name", "K");
  file->putAttr("interpret_as", specifyDouble);
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->closeData();

  // L column
  file->writeData("column_4", L);
  file->openData("column_4");
  file->putAttr("name", "L");
  file->putAttr("interpret_as", specifyDouble);
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->closeData();

  // Intensity column
  file->writeData("column_5", intensity);
  file->openData("column_5");
  file->putAttr("name", "Intensity");
  file->putAttr("interpret_as", specifyDouble);
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->closeData();

  // Sigma Intensity column
  file->writeData("column_6", sigmaIntensity);
  file->openData("column_6");
  file->putAttr("name", "Sigma Intensity");
  file->putAttr("interpret_as", specifyDouble);
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->closeData();

  // Bin Count column
  file->writeData("column_7", binCount);
  file->openData("column_7");
  file->putAttr("name", "Bin Count");
  file->putAttr("interpret_as", specifyDouble);
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->closeData();

  // Initial Energy column
  file->writeData("column_8", initialEnergy);
  file->openData("column_8");
  file->putAttr("name", "Initial Energy");
  file->putAttr("interpret_as", specifyDouble);
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->closeData();

  // Final Energy column
  file->writeData("column_9", finalEnergy);
  file->openData("column_9");
  file->putAttr("name", "Final Energy");
  file->putAttr("interpret_as", specifyDouble);
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->closeData();

  // Wave Length Column
  file->writeData("column_10", waveLength);
  file->openData("column_10");
  file->putAttr("name", "Wave Length");
  file->putAttr("interpret_as", specifyDouble);
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->closeData();

  // Scattering Column
  file->writeData("column_11", scattering);
  file->openData("column_11");
  file->putAttr("name", "Scattering");
  file->putAttr("interpret_as", specifyDouble);
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->closeData();

  // D Spacing Column
  file->writeData("column_12", dSpacing);
  file->openData("column_12");
  file->putAttr("name", "D Spacing");
  file->putAttr("interpret_as", specifyDouble);
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->closeData();

  // TOF Column
  file->writeData("column_13", TOF);
  file->openData("column_13");
  file->putAttr("name", "TOF");
  file->putAttr("interpret_as", specifyDouble);
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->closeData();

  // Run Number column
  file->writeData("column_14", runNumber);
  file->openData("column_14");
  file->putAttr("name", "Run Number");
  file->putAttr("interpret_as", specifyInteger);
  file->putAttr("units", "Not known"); // Units may need changing when known
878
879
880
  file->closeData();

  // Peak Number column
881
882
  file->writeData("column_17", peakNumber);
  file->openData("column_17");
883
884
885
  file->putAttr("name", "Peak Number");
  file->putAttr("interpret_as", specifyInteger);
  file->putAttr("units", "Not known"); // Units may need changing when known
886
887
  file->closeData();

888
889
890
891
892
893
894
895
  // TBar column
  file->writeData("column_18", tbar);
  file->openData("column_18");
  file->putAttr("name", "TBar");
  file->putAttr("interpret_as", specifyDouble);
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->closeData();

896
897
  // Goniometer Matrix Column
  std::vector<int> array_dims;
898
899
  array_dims.emplace_back(static_cast<int>(peaks.size()));
  array_dims.emplace_back(9);
900
901
902
903
904
905
906
  file->writeData("column_15", goniometerMatrix, array_dims);
  file->openData("column_15");
  file->putAttr("name", "Goniometer Matrix");
  file->putAttr("interpret_as", "A matrix of 3x3 doubles");
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->closeData();

907
908
  // Shape
  std::vector<int64_t> dims;
909
910
  dims.emplace_back(np);
  dims.emplace_back(static_cast<int>(maxShapeJSONLength));
911
912
913
914
  const std::string name = "column_16";
  file->makeData(name, NeXus::CHAR, dims, false);
  file->openData(name);

915
  auto toNexus = new char[maxShapeJSONLength * np];
Owen Arnold's avatar
Owen Arnold committed
916
  for (size_t ii = 0; ii < np; ii++) {
917
918
919
    std::string rowStr = shapes[ii];
    for (size_t ic = 0; ic < rowStr.size(); ic++)
      toNexus[ii * maxShapeJSONLength + ic] = rowStr[ic];
920
921
    for (size_t ic = rowStr.size();
         ic < static_cast<size_t>(maxShapeJSONLength); ic++)
922
923
924
925
926
927
928
929
930
931
932
      toNexus[ii * maxShapeJSONLength + ic] = ' ';
  }

  file->putData((void *)(toNexus));

  delete[] toNexus;
  file->putAttr("units", "Not known"); // Units may need changing when known
  file->putAttr("name", "Shape");
  file->putAttr("interpret_as", specifyString);
  file->closeData();

933
934
935
936
  // QLab & QSample are calculated and do not need to be saved

  file->closeGroup(); // end of peaks workpace
}
937

938
939
940
941
942
/**
 * Set the special Q3D coordinate system.
 * @param coordinateSystem : Option to set.
 */
void PeaksWorkspace::setCoordinateSystem(
943
944
    const Kernel::SpecialCoordinateSystem coordinateSystem) {
  m_coordSystem = coordinateSystem;
945
}
946

947
948
949
/**
 * @return the special Q3D coordinate system.
 */
950
Kernel::SpecialCoordinateSystem
951
PeaksWorkspace::getSpecialCoordinateSystem() const {
952
  return m_coordSystem;
Peterson, Peter's avatar
Peterson, Peter committed
953
}
954

955
956
// prevent shared pointer from deleting this
struct NullDeleter {
957
  template <typename T> void operator()(T * /*unused*/) {}
958
};
959
/**Get access to shared pointer containing workspace porperties */
960
API::LogManager_sptr PeaksWorkspace::logs() {
961
  return API::LogManager_sptr(&(this->mutableRun()), NullDeleter());
962
}
963

964
965
966
967
968
969
970
/** Get constant access to shared pointer containing workspace porperties;
 * Copies logs into new LogManager variable Meaningfull only for some
 * multithereaded methods when a thread wants to have its own copy of logs */
API::LogManager_const_sptr PeaksWorkspace::getLogs() const {
  return API::LogManager_const_sptr(new API::LogManager(this->run()));
}

971
972
ITableWorkspace *PeaksWorkspace::doCloneColumns(
    const std::vector<std::string> & /*colNames*/) const {
973
974
  throw Kernel::Exception::NotImplementedError(
      "PeaksWorkspace cannot clone columns.");
975
}
LamarMoore's avatar
LamarMoore committed
976
977
} // namespace DataObjects
} // namespace Mantid
978

979
///\cond TEMPLATE
980

981
982
983
984
985
986
987
namespace Mantid {
namespace Kernel {

template <>
DLLExport Mantid::DataObjects::PeaksWorkspace_sptr
IPropertyManager::getValue<Mantid::DataObjects::PeaksWorkspace_sptr>(
    const std::string &name) const {
988
989
990
  auto *prop = dynamic_cast<
      PropertyWithValue<Mantid::DataObjects::PeaksWorkspace_sptr> *>(
      getPointerToProperty(name));
991
992
993
  if (prop) {
    return *prop;
  } else {
994
995
996
    std::string message =
        "Attempt to assign property " + name +
        " to incorrect type. Expected shared_ptr<PeaksWorkspace>.";
997
998
999
    throw std::runtime_error(message);
  }
}
1000

1001
1002
1003
1004
template <>
DLLExport Mantid::DataObjects::PeaksWorkspace_const_sptr
IPropertyManager::getValue<Mantid::DataObjects::PeaksWorkspace_const_sptr>(
    const std::string &name) const {
1005
1006
1007
  auto *prop = dynamic_cast<
      PropertyWithValue<Mantid::DataObjects::PeaksWorkspace_sptr> *>(
      getPointerToProperty(name));
1008
1009
1010
  if (prop) {
    return prop->operator()();
  } else {
1011
1012
1013
    std::string message =
        "Attempt to assign property " + name +
        " to incorrect type. Expected const shared_ptr<PeaksWorkspace>.";
1014
1015
1016
    throw std::runtime_error(message);
  }
}
1017

1018
} // namespace Kernel
1019
1020
} // namespace Mantid

1021
///\endcond TEMPLATE