PeaksWorkspace.cpp 34.8 KB
Newer Older
1
2
3
4
5
6
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
//     NScD Oak Ridge National Laboratory, European Spallation Source
//     & Institut Laue - Langevin
// SPDX - License - Identifier: GPL - 3.0 +
7
#include "MantidDataObjects/PeaksWorkspace.h"
8
9
#include "MantidAPI/AlgorithmFactory.h"
#include "MantidAPI/Column.h"
Peterson, Peter's avatar
Peterson, Peter committed
10
#include "MantidAPI/ColumnFactory.h"
11
#include "MantidAPI/MatrixWorkspace.h"
12
13
#include "MantidAPI/Run.h"
#include "MantidAPI/Sample.h"
Peterson, Peter's avatar
Peterson, Peter committed
14
#include "MantidAPI/WorkspaceFactory.h"
15
#include "MantidDataObjects/Peak.h"
16
17
#include "MantidDataObjects/TableColumn.h"
#include "MantidDataObjects/TableWorkspace.h"
18
19
#include "MantidGeometry/Crystal/OrientedLattice.h"
#include "MantidGeometry/Instrument/Goniometer.h"
20
21
22
#include "MantidKernel/DateAndTime.h"
#include "MantidKernel/Logger.h"
#include "MantidKernel/PhysicalConstants.h"
23
#include "MantidKernel/Quat.h"
24
#include "MantidKernel/Unit.h"
25
#include "MantidKernel/UnitConversion.h"
26
#include "MantidKernel/V3D.h"
27

Peterson, Peter's avatar
Peterson, Peter committed
28
#include <algorithm>
29
#include <boost/shared_ptr.hpp>
30
31
32
#include <cmath>
#include <cstdio>
#include <cstdlib>
Peterson, Peter's avatar
Peterson, Peter committed
33
34
#include <exception>
#include <fstream>
35
// clang-format off
36
#include <nexus/NeXusFile.hpp>
37
38
#include <nexus/NeXusException.hpp>
// clang-format on
39
40
41
42
43
44
#include <ostream>
#include <string>

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

46
47
48
namespace Mantid {
namespace DataObjects {
/// Register the workspace as a type
49
DECLARE_WORKSPACE(PeaksWorkspace)
50

51
52
Mantid::Kernel::Logger g_log("PeaksWorkspace");

Owen Arnold's avatar
Owen Arnold committed
53
//---------------------------------------------------------------------------------------------
54
55
56
57
/** Constructor. Create a table with all the required columns.
 *
 * @return PeaksWorkspace object
 */
58
59
60
61
PeaksWorkspace::PeaksWorkspace()
    : IPeaksWorkspace(), peaks(), columns(), columnNames(),
      m_coordSystem(None) {
  initColumns();
62
63
  // PeaksWorkspace does not use the grouping mechanism of ExperimentInfo.
  setNumberOfDetectorGroups(0);
64
}
65

66
67
68
69
70
71
72
//---------------------------------------------------------------------------------------------
/** Copy constructor
 *
 * @param other :: other PeaksWorkspace to copy from
 * @return
 */
PeaksWorkspace::PeaksWorkspace(const PeaksWorkspace &other)
73
74
    : IPeaksWorkspace(other), peaks(other.peaks), columns(), columnNames(),
      m_coordSystem(other.m_coordSystem) {
75
  initColumns();
76
77
  // PeaksWorkspace does not use the grouping mechanism of ExperimentInfo.
  setNumberOfDetectorGroups(0);
78
}
79

80
81
82
83
84
85
86
87
88
89
90
91
//=====================================================================================
//=====================================================================================
/** Comparator class for sorting peaks by one or more criteria
 */
class PeakComparator : public std::binary_function<Peak, Peak, bool> {
public:
  std::vector<std::pair<std::string, bool>> &criteria;

  /** 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.
   */
92
  explicit PeakComparator(std::vector<std::pair<std::string, bool>> &criteria)
93
94
95
96
      : criteria(criteria) {}

  /** Compare two peaks using the stored criteria */
  inline bool operator()(const Peak &a, const Peak &b) {
Hahn, Steven's avatar
Hahn, Steven committed
97
98
99
    for (auto &name : criteria) {
      std::string &col = name.first;
      bool ascending = name.second;
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
      bool lessThan = false;
      if (col == "BankName") {
        // If this criterion is equal, move on to the next one
        std::string valA = a.getBankName();
        std::string valB = b.getBankName();
        // Move on to lesser criterion if equal
        if (valA == valB)
          continue;
        lessThan = (valA < valB);
      } else {
        // General double comparison
        double valA = a.getValueByColName(col);
        double valB = b.getValueByColName(col);
        // Move on to lesser criterion if equal
        if (valA == valB)
          continue;
        lessThan = (valA < valB);
Owen Arnold's avatar
Owen Arnold committed
117
      }
118
119
120
      // Flip the sign of comparison if descending.
      if (ascending)
        return lessThan;
Owen Arnold's avatar
Owen Arnold committed
121
      else
122
        return !lessThan;
123
    }
124
125
126
127
    // If you reach here, all criteria were ==; so not <, so return false
    return false;
  }
};
128

129
130
131
132
133
134
135
136
137
138
139
140
//---------------------------------------------------------------------------------------------
/** 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.
 */
void PeaksWorkspace::sort(std::vector<std::pair<std::string, bool>> &criteria) {
  PeakComparator comparator(criteria);
  std::stable_sort(peaks.begin(), peaks.end(), comparator);
}
141

142
143
144
145
//---------------------------------------------------------------------------------------------
/** @return the number of peaks
 */
int PeaksWorkspace::getNumberPeaks() const { return int(peaks.size()); }
146

147
148
149
150
151
//---------------------------------------------------------------------------------------------
/** @return the convention
 */
std::string PeaksWorkspace::getConvention() const { return convention; }

152
153
154
155
156
157
158
159
160
161
162
//---------------------------------------------------------------------------------------------
/** 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);
}
163

164
/** Removes multiple peaks
LamarMoore's avatar
LamarMoore committed
165
166
 * @param badPeaks peaks to be removed
 */
167
168
void PeaksWorkspace::removePeaks(std::vector<int> badPeaks) {
  if (badPeaks.empty())
Matthew Bowles's avatar
Matthew Bowles committed
169
    return;
Lynch, Vickie's avatar
Lynch, Vickie committed
170
171
172
173
174
175
  // 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++;
176
177
        for (int badPeak : badPeaks) {
          if (badPeak == ip)
Lynch, Vickie's avatar
Lynch, Vickie committed
178
179
            return true;
        }
180
        return false;
Lynch, Vickie's avatar
Lynch, Vickie committed
181
182
      });
  peaks.erase(it, peaks.end());
183
184
}

185
186
//---------------------------------------------------------------------------------------------
/** Add a peak to the list
187
 * @param ipeak :: Peak object to add (copy) into this.
188
 */
Owen Arnold's avatar
Owen Arnold committed
189
void PeaksWorkspace::addPeak(const Geometry::IPeak &ipeak) {
190
191
192
193
194
195
  if (dynamic_cast<const Peak *>(&ipeak)) {
    peaks.push_back((const Peak &)ipeak);
  } else {
    peaks.push_back(Peak(ipeak));
  }
}
196

197
198
199
200
201
//---------------------------------------------------------------------------------------------
/** 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
 */
202
203
void PeaksWorkspace::addPeak(const V3D &position,
                             const SpecialCoordinateSystem &frame) {
204
205
206
207
  auto peak = createPeak(position, frame);
  addPeak(*peak);
}

208
209
//---------------------------------------------------------------------------------------------
/** Add a peak to the list
210
 * @param peak :: Peak object to add (move) into this.
211
 */
212
void PeaksWorkspace::addPeak(Peak &&peak) { peaks.push_back(peak); }
213

214
215
216
217
218
219
220
221
222
223
224
225
//---------------------------------------------------------------------------------------------
/** 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];
}
226

227
228
229
230
231
232
233
234
235
236
237
238
//---------------------------------------------------------------------------------------------
/** 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];
}
239

240
241
242
//---------------------------------------------------------------------------------------------
/** 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
243
244
 * @param detectorDistance :: optional distance between the sample and the
 * detector. You do NOT need to explicitly provide this distance.
245
246
 * @return a pointer to a new Peak object.
 */
Owen Arnold's avatar
Owen Arnold committed
247
Geometry::IPeak *
Hahn, Steven's avatar
Hahn, Steven committed
248
PeaksWorkspace::createPeak(const Kernel::V3D &QLabFrame,
249
                           boost::optional<double> detectorDistance) const {
250
251
252
  Geometry::Goniometer goniometer = this->run().getGoniometer();

  // create a peak using the qLab frame
253
  auto peak = new Peak(this->getInstrument(), QLabFrame, detectorDistance);
254
255
256
257
258
259
260
261

  // Set the goniometer
  peak->setGoniometerMatrix(goniometer.getR());

  // Take the run number from this
  peak->setRunNumber(this->getRunNumber());

  return peak;
262
}
263

264
265
266
267
268
269
270
271
272
273
//---------------------------------------------------------------------------------------------
/** 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 {
274
275
276
277
278
279
280
  if (frame == Mantid::Kernel::HKL) {
    return std::unique_ptr<Geometry::IPeak>(createPeakHKL(position));
  } else if (frame == Mantid::Kernel::QLab) {
    return std::unique_ptr<Geometry::IPeak>(createPeak(position));
  } else {
    return std::unique_ptr<Geometry::IPeak>(createPeakQSample(position));
  }
281
282
283
284
}

//---------------------------------------------------------------------------------------------
/** Creates an instance of a Peak BUT DOES NOT ADD IT TO THE WORKSPACE
285
286
 * @param position :: QSample position of the center of the peak, in reciprocal
 * space
287
288
289
 * detector. You do NOT need to explicitly provide this distance.
 * @return a pointer to a new Peak object.
 */
290
Peak *PeaksWorkspace::createPeakQSample(const V3D &position) const {
291
  // Create a peak from QSampleFrame
292
293
294
295

  Geometry::Goniometer goniometer;

  LogManager_const_sptr props = getLogs();
296
297
298
299
300
301
302
303
304
305
306
307
308
309
  // 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) {
310
    goniometer.calcFromQSampleAndWavelength(position, wavelength);
311
312
313
    g_log.information() << "Found goniometer rotation to be "
                        << goniometer.getEulerAngles()[0]
                        << " degrees for Q sample = " << position << "\n";
314
315
316
  } else {
    goniometer = run().getGoniometer();
  }
317
318
319
320
321
322
323
  // create a peak using the qLab frame
  auto peak = new Peak(getInstrument(), position, goniometer.getR());
  // Take the run number from this
  peak->setRunNumber(getRunNumber());
  return peak;
}

324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/**
 * 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
340
PeaksWorkspace::peakInfo(const Kernel::V3D &qFrame, bool labCoords) const {
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
  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());
  Result.push_back(QMag);

  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();
  Result.push_back(dspc);

  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;
372
      }
373

374
375
376
377
378
379
380
381
382
383
384
385
      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);
386

387
388
389
  if (seqNum >= 0 && NPeaks == getNumberPeaks())
    Gon = getPeak(seqNum).getGoniometerMatrix();
  if (labCoords) {
390

391
392
393
    Kernel::Matrix<double> InvGon(Gon);
    InvGon.Invert();
    Qsamp = InvGon * Qlab;
394

395
396
397
398
  } else {
    Qsamp = qFrame;
    Qlab = Gon * Qsamp;
  }
399

400
  if (labCoords || seqNum >= 0)
401

402
403
404
405
406
  {
    std::pair<std::string, std::string> QlabStr(
        "Qlab", boost::lexical_cast<std::string>(Qlab));
    Result.push_back(QlabStr);
  }
407

408
  if (!labCoords || seqNum >= 0) {
409

410
411
412
413
    std::pair<std::string, std::string> QsampStr(
        "QSample", boost::lexical_cast<std::string>(Qsamp));
    Result.push_back(QsampStr);
  }
414

415
  try {
416

Owen Arnold's avatar
Owen Arnold committed
417
    Geometry::IPeak *peak = createPeak(Qlab);
418

419
    if (sample().hasOrientedLattice()) {
420

421
422
      peak->setGoniometerMatrix(Gon);
      const Geometry::OrientedLattice &lat = (sample().getOrientedLattice());
423

424
425
426
427
      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
428

429
430
431
      std::pair<std::string, std::string> HKL(
          "HKL", boost::lexical_cast<std::string>(hkl));
      Result.push_back(HKL);
432
433
    }

434
    if (hasOneRunNumber) {
435
436
      std::pair<std::string, std::string> runn("RunNumber",
                                               "   " + std::to_string(runNum));
437
      Result.push_back(runn);
438
    }
439

440
441
442
443
444
445
446
447
448
449
    //------- 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));
    Result.push_back(GRead);

    std::pair<std::string, std::string> SeqNum(
450
        "Seq Num,1st=1", "    " + std::to_string(seqNum + 1));
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
    Result.push_back(SeqNum);

    oss << std::setw(12) << std::fixed << std::setprecision(3)
        << (peak->getWavelength());
    std::pair<std::string, std::string> wl("Wavelength", oss.str());
    Result.push_back(wl);
    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()));
      Result.push_back(detpos);

      oss << std::setw(15) << std::fixed << std::setprecision(3)
          << (peak->getTOF());
      std::pair<std::string, std::string> tof("TOF", oss.str());
      Result.push_back(tof);
      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());
      Result.push_back(Energy);
      oss.str("");
      oss.clear();

      std::pair<std::string, std::string> row(
481
          "Row", "    " + std::to_string(peak->getRow()));
482
483
484
      Result.push_back(row);

      std::pair<std::string, std::string> col(
485
          "Col", "    " + std::to_string(peak->getCol()));
486
487
488
489
490
491
492
493
494
495
      Result.push_back(col);

      std::pair<std::string, std::string> bank("Bank",
                                               "    " + peak->getBankName());
      Result.push_back(bank);

      oss << std::setw(12) << std::fixed << std::setprecision(3)
          << (peak->getScattering());
      std::pair<std::string, std::string> scat("Scattering Angle", oss.str());
      Result.push_back(scat);
496
    }
497

498
499
500
501
502
  } catch (...) // Impossible position
  {
  }
  return Result;
}
503

504
505
506
507
508
509
510
/**
 * Create a Peak from a HKL value provided by the client.
 *
 *
 * @param HKL : reciprocal lattice vector coefficients
 * @return Fully formed peak.
 */
Hahn, Steven's avatar
Hahn, Steven committed
511
Peak *PeaksWorkspace::createPeakHKL(const V3D &HKL) const {
512
513
514
  /*
   The following allows us to add peaks where we have a single UB to work from.
   */
515

516
517
  Geometry::OrientedLattice lattice = this->sample().getOrientedLattice();
  Geometry::Goniometer goniometer = this->run().getGoniometer();
518

519
520
521
  // Calculate qLab from q HKL. As per Busing and Levy 1967, q_lab_frame = 2pi *
  // Goniometer * UB * HKL
  V3D qLabFrame = goniometer.getR() * lattice.getUB() * HKL * 2 * M_PI;
522

523
524
525
526
  // create a peak using the qLab frame
  auto peak =
      new Peak(this->getInstrument(),
               qLabFrame); // This should calculate the detector positions too.
527

528
529
  // We need to set HKL separately to keep things consistent.
  peak->setHKL(HKL[0], HKL[1], HKL[2]);
530

531
532
  // Set the goniometer
  peak->setGoniometerMatrix(goniometer.getR());
533

534
535
  // Take the run number from this
  peak->setRunNumber(this->getRunNumber());
536

537
  return peak;
538
539
}

540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/**
 * 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
555
556
int PeaksWorkspace::peakInfoNumber(const Kernel::V3D &qFrame,
                                   bool labCoords) const {
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
  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());
  Result.push_back(QMag);

  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();
  Result.push_back(dspc);

  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;
585
    }
586
587
588
  }
  return seqNum;
}
Peterson, Peter's avatar
Peterson, Peter committed
589

590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//---------------------------------------------------------------------------------------------
/** 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)) {
    const int value = boost::lexical_cast<int>(
        this->run().getProperty(peaksIntegrated)->value());
    ret = (value != 0);
  }
  return ret;
}
610

611
612
613
614
615
//---------------------------------------------------------------------------------------------
/// Return the memory used in bytes
size_t PeaksWorkspace::getMemorySize() const {
  return getNumberPeaks() * sizeof(Peak);
}
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
//---------------------------------------------------------------------------------------------
/**
 *  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");

  const int npeaks(static_cast<int>(this->rowCount()));
  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
641
    }
642
  }
643

644
645
  return table;
}
Peterson, Peter's avatar
Peterson, Peter committed
646

647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//---------------------------------------------------------------------------------------------
/** 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");
662
  addPeakColumn("Int/SigInt");
663
664
665
666
667
668
  addPeakColumn("BinCount");
  addPeakColumn("BankName");
  addPeakColumn("Row");
  addPeakColumn("Col");
  addPeakColumn("QLab");
  addPeakColumn("QSample");
669
  addPeakColumn("PeakNumber");
670
}
Peterson, Peter's avatar
Peterson, Peter committed
671

672
673
674
675
676
677
678
679
680
681
682
683
//---------------------------------------------------------------------------------------------
/**
 * Add a PeakColumn
 * @param name :: The name of the column
 **/
void PeaksWorkspace::addPeakColumn(const std::string &name) {
  // Create the PeakColumn.
  columns.push_back(boost::shared_ptr<DataObjects::PeakColumn>(
      new DataObjects::PeakColumn(this->peaks, name)));
  // Cache the names
  columnNames.push_back(name);
}
Peterson, Peter's avatar
Peterson, Peter committed
684

685
686
687
688
689
690
691
692
693
//---------------------------------------------------------------------------------------------
/// @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
694

695
696
697
698
699
700
701
702
//---------------------------------------------------------------------------------------------
/// Gets the shared pointer to a column by index.
boost::shared_ptr<Mantid::API::Column> PeaksWorkspace::getColumn(size_t index) {
  if (index >= columns.size())
    throw std::invalid_argument(
        "PeaksWorkspace::getColumn() called with invalid index.");
  return columns[index];
}
703

704
705
706
707
708
709
710
711
712
//---------------------------------------------------------------------------------------------
/// Gets the shared pointer to a column by index.
boost::shared_ptr<const Mantid::API::Column>
PeaksWorkspace::getColumn(size_t index) const {
  if (index >= columns.size())
    throw std::invalid_argument(
        "PeaksWorkspace::getColumn() called with invalid index.");
  return columns[index];
}
713

714
715
716
717
718
719
720
721
722
723
724
725
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);
726
  std::vector<double> intensityOverSigma(np);
727
728
729
730
731
732
733
734
  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);
735
  std::vector<int> peakNumber(np);
736
  std::vector<double> goniometerMatrix(9 * np);
737
  std::vector<std::string> shapes(np);
738
739

  // Populate column vectors from Peak Workspace
740
  size_t maxShapeJSONLength = 0;
741
742
743
744
745
746
747
748
  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();
749
    intensityOverSigma[i] = p.getIntensityOverSigma();
750
751
752
753
754
755
756
757
    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();
758
    peakNumber[i] = p.getPeakNumber();
759
    {
760
761
762
763
764
765
766
767
768
769
      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];
770
    }
771
772
    const std::string shapeJSON = p.getPeakShape().toJSON();
    shapes[i] = shapeJSON;
773
774
    if (shapeJSON.size() > maxShapeJSONLength) {
      maxShapeJSONLength = shapeJSON.size();
775
    }
776
  }
777

778
  // Start Peaks Workspace in Nexus File
779
780
781
  const std::string specifyInteger = "An integer";
  const std::string specifyDouble = "A double";
  const std::string specifyString = "A string";
782
783
784
  file->makeGroup("peaks_workspace", "NXentry",
                  true); // For when peaksWorkspace can be loaded

785
786
  // Coordinate system
  file->writeData("coordinate_system", static_cast<uint32_t>(m_coordSystem));
787

788
789
790
791
792
  // 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);

793
794
795
  // Detectors column
  file->writeData("column_1", detectorID);
  file->openData("column_1");
796
  file->putAttr("name", "Detector ID");
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
  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();

841
842
  // Intensity over Sigma column
  file->writeData("column_7", intensityOverSigma);
843
  file->openData("column_7");
844
845
846
847
848
849
850
851
  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_8", binCount);
  file->openData("column_8");
852
853
854
855
856
857
  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
858
859
  file->writeData("column_9", initialEnergy);
  file->openData("column_9");
860
861
862
863
864
865
  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
866
867
  file->writeData("column_10", finalEnergy);
  file->openData("column_10");
868
869
870
871
872
873
  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
874
875
  file->writeData("column_11", waveLength);
  file->openData("column_11");
876
877
878
879
880
881
  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
882
883
  file->writeData("column_12", scattering);
  file->openData("column_12");
884
885
886
887
888
889
  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
890
891
  file->writeData("column_13", dSpacing);
  file->openData("column_13");
892
893
894
895
896
897
  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
898
899
  file->writeData("column_14", TOF);
  file->openData("column_14");
900
901
902
903
904
905
  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
906
907
  file->writeData("column_15", runNumber);
  file->openData("column_15");
908
909
910
  file->putAttr("name", "Run Number");
  file->putAttr("interpret_as", specifyInteger);
  file->putAttr("units", "Not known"); // Units may need changing when known
911
912
913
  file->closeData();

  // Peak Number column
914
915
  file->writeData("column_18", peakNumber);
  file->openData("column_18");
916
917
918
  file->putAttr("name", "Peak Number");
  file->putAttr("interpret_as", specifyInteger);
  file->putAttr("units", "Not known"); // Units may need changing when known
919
920
921
922
923
924
  file->closeData();

  // Goniometer Matrix Column
  std::vector<int> array_dims;
  array_dims.push_back(static_cast<int>(peaks.size()));
  array_dims.push_back(9);
925
926
  file->writeData("column_16", goniometerMatrix, array_dims);
  file->openData("column_16");
927
928
929
930
931
  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();

932
933
934
935
  // Shape
  std::vector<int64_t> dims;
  dims.push_back(np);
  dims.push_back(static_cast<int>(maxShapeJSONLength));
936
  const std::string name = "column_17";
937
938
939
  file->makeData(name, NeXus::CHAR, dims, false);
  file->openData(name);

940
  auto toNexus = new char[maxShapeJSONLength * np];
Owen Arnold's avatar
Owen Arnold committed
941
  for (size_t ii = 0; ii < np; ii++) {
942
943
944
    std::string rowStr = shapes[ii];
    for (size_t ic = 0; ic < rowStr.size(); ic++)
      toNexus[ii * maxShapeJSONLength + ic] = rowStr[ic];
945
946
    for (size_t ic = rowStr.size();
         ic < static_cast<size_t>(maxShapeJSONLength); ic++)
947
948
949
950
951
952
953
954
955
956
957
      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();

958
959
960
961
  // QLab & QSample are calculated and do not need to be saved

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

963
964
965
966
967
/**
 * Set the special Q3D coordinate system.
 * @param coordinateSystem : Option to set.
 */
void PeaksWorkspace::setCoordinateSystem(
968
969
    const Kernel::SpecialCoordinateSystem coordinateSystem) {
  m_coordSystem = coordinateSystem;
970
}
971

972
973
974
/**
 * @return the special Q3D coordinate system.
 */
975
Kernel::SpecialCoordinateSystem
976
PeaksWorkspace::getSpecialCoordinateSystem() const {
977
  return m_coordSystem;
Peterson, Peter's avatar
Peterson, Peter committed
978
}
979

980
981
982
983
// prevent shared pointer from deleting this
struct NullDeleter {
  template <typename T> void operator()(T *) {}
};
984
/**Get access to shared pointer containing workspace porperties */
985
API::LogManager_sptr PeaksWorkspace::logs() {
986
  return API::LogManager_sptr(&(this->mutableRun()), NullDeleter());
987
}
988

989
990
991
992
993
994
995
/** 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()));
}

996
ITableWorkspace *
997
PeaksWorkspace::doCloneColumns(const std::vector<std::string> &) const {
998
999
  throw Kernel::Exception::NotImplementedError(
      "PeaksWorkspace cannot clone columns.");
1000
}