Peak.cpp 40.3 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/Peak.h"
8
#include "MantidDataObjects/NoShape.h"
9
#include "MantidGeometry/Instrument/RectangularDetector.h"
10
#include "MantidGeometry/Instrument/ReferenceFrame.h"
11
#include "MantidGeometry/Objects/InstrumentRayTracer.h"
12
#include "MantidKernel/ConfigService.h"
13
#include "MantidKernel/Exception.h"
Janik Zikovsky's avatar
Janik Zikovsky committed
14
15
#include "MantidKernel/Strings.h"
#include "MantidKernel/System.h"
16

17
18
#include "boost/make_shared.hpp"

19
20
#include <algorithm>
#include <cctype>
Janik Zikovsky's avatar
Janik Zikovsky committed
21
#include <string>
22

23
24
25
26
using namespace Mantid;
using namespace Mantid::Kernel;
using namespace Mantid::Geometry;

27
28
29
30
31
32
namespace Mantid {
namespace DataObjects {

//----------------------------------------------------------------------------------------------
/** Default constructor */
Peak::Peak()
33
34
35
36
37
    : m_detectorID(-1), m_H(0), m_K(0), m_L(0), m_intensity(0),
      m_sigmaIntensity(0), m_binCount(0), m_initialEnergy(0.),
      m_finalEnergy(0.), m_GoniometerMatrix(3, 3, true),
      m_InverseGoniometerMatrix(3, 3, true), m_runNumber(0), m_monitorCount(0),
      m_row(-1), m_col(-1), m_orig_H(0), m_orig_K(0), m_orig_L(0),
38
      m_peakNumber(0), m_peakShape(boost::make_shared<NoShape>()) {
Lynch, Vickie's avatar
Lynch, Vickie committed
39
40
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
}
41
42
43
44
45
46
47

//----------------------------------------------------------------------------------------------
/** Constructor that uses the Q position of the peak (in the lab frame).
 * No detector ID is set.
 *
 * @param m_inst :: Shared pointer to the instrument for this peak detection
 * @param QLabFrame :: Q of the center of the peak, in reciprocal space
48
49
 * @param detectorDistance :: Optional distance between the sample and the
 *detector. Calculated if not explicitly provided.
50
51
 *        Used to give a valid TOF. Default 1.0 meters.
 */
52
53
Peak::Peak(const Geometry::Instrument_const_sptr &m_inst,
           const Mantid::Kernel::V3D &QLabFrame,
Hahn, Steven's avatar
Hahn, Steven committed
54
           boost::optional<double> detectorDistance)
55
56
57
    : m_H(0), m_K(0), m_L(0), m_intensity(0), m_sigmaIntensity(0),
      m_binCount(0), m_GoniometerMatrix(3, 3, true),
      m_InverseGoniometerMatrix(3, 3, true), m_runNumber(0), m_monitorCount(0),
58
      m_orig_H(0), m_orig_K(0), m_orig_L(0), m_peakNumber(0),
59
      m_peakShape(boost::make_shared<NoShape>()) {
Lynch, Vickie's avatar
Lynch, Vickie committed
60
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
61
62
63
64
65
66
67
68
69
70
71
72
73
  this->setInstrument(m_inst);
  this->setQLabFrame(QLabFrame, detectorDistance);
}

//----------------------------------------------------------------------------------------------
/** Constructor that uses the Q position of the peak (in the sample frame)
 * and a goniometer rotation matrix.
 * No detector ID is set.
 *
 * @param m_inst :: Shared pointer to the instrument for this peak detection
 * @param QSampleFrame :: Q of the center of the peak, in reciprocal space, in
 *the sample frame (goniometer rotation accounted for).
 * @param goniometer :: a 3x3 rotation matrix
74
75
 * @param detectorDistance :: Optional distance between the sample and the
 *detector. Calculated if not explicitly provided.
76
77
 *        Used to give a valid TOF. Default 1.0 meters.
 */
78
79
80
Peak::Peak(const Geometry::Instrument_const_sptr &m_inst,
           const Mantid::Kernel::V3D &QSampleFrame,
           const Mantid::Kernel::Matrix<double> &goniometer,
Hahn, Steven's avatar
Hahn, Steven committed
81
           boost::optional<double> detectorDistance)
82
83
84
    : m_H(0), m_K(0), m_L(0), m_intensity(0), m_sigmaIntensity(0),
      m_binCount(0), m_GoniometerMatrix(goniometer),
      m_InverseGoniometerMatrix(goniometer), m_runNumber(0), m_monitorCount(0),
85
      m_orig_H(0), m_orig_K(0), m_orig_L(0), m_peakNumber(0),
86
      m_peakShape(boost::make_shared<NoShape>()) {
Lynch, Vickie's avatar
Lynch, Vickie committed
87
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
88
89
90
91
92
93
94
95
96
97
98
  if (fabs(m_InverseGoniometerMatrix.Invert()) < 1e-8)
    throw std::invalid_argument(
        "Peak::ctor(): Goniometer matrix must non-singular.");
  this->setInstrument(m_inst);
  this->setQSampleFrame(QSampleFrame, detectorDistance);
}

//----------------------------------------------------------------------------------------------
/** Constructor
 *
 * @param m_inst :: Shared pointer to the instrument for this peak detection
99
 * @param m_detectorID :: ID to the detector of the center of the peak
100
101
102
 * @param m_Wavelength :: incident neutron wavelength, in Angstroms
 * @return
 */
103
Peak::Peak(const Geometry::Instrument_const_sptr &m_inst, int m_detectorID,
104
           double m_Wavelength)
105
106
107
    : m_H(0), m_K(0), m_L(0), m_intensity(0), m_sigmaIntensity(0),
      m_binCount(0), m_GoniometerMatrix(3, 3, true),
      m_InverseGoniometerMatrix(3, 3, true), m_runNumber(0), m_monitorCount(0),
108
      m_orig_H(0), m_orig_K(0), m_orig_L(0), m_peakNumber(0),
109
      m_peakShape(boost::make_shared<NoShape>()) {
Lynch, Vickie's avatar
Lynch, Vickie committed
110
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
111
  this->setInstrument(m_inst);
112
  this->setDetectorID(m_detectorID);
113
114
115
116
117
118
119
  this->setWavelength(m_Wavelength);
}

//----------------------------------------------------------------------------------------------
/** Constructor
 *
 * @param m_inst :: Shared pointer to the instrument for this peak detection
120
 * @param m_detectorID :: ID to the detector of the center of the peak
121
122
123
124
 * @param m_Wavelength :: incident neutron wavelength, in Angstroms
 * @param HKL :: vector with H,K,L position of the peak
 * @return
 */
125
126
Peak::Peak(const Geometry::Instrument_const_sptr &m_inst, int m_detectorID,
           double m_Wavelength, const Mantid::Kernel::V3D &HKL)
127
128
129
    : m_H(HKL[0]), m_K(HKL[1]), m_L(HKL[2]), m_intensity(0),
      m_sigmaIntensity(0), m_binCount(0), m_GoniometerMatrix(3, 3, true),
      m_InverseGoniometerMatrix(3, 3, true), m_runNumber(0), m_monitorCount(0),
130
      m_orig_H(0), m_orig_K(0), m_orig_L(0), m_peakNumber(0),
Hahn, Steven's avatar
Hahn, Steven committed
131
      m_peakShape(boost::make_shared<NoShape>()) {
Lynch, Vickie's avatar
Lynch, Vickie committed
132
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
133
  this->setInstrument(m_inst);
134
  this->setDetectorID(m_detectorID);
135
136
137
138
139
140
141
  this->setWavelength(m_Wavelength);
}

//----------------------------------------------------------------------------------------------
/** Constructor
 *
 * @param m_inst :: Shared pointer to the instrument for this peak detection
142
 * @param m_detectorID :: ID to the detector of the center of the peak
143
144
145
146
147
 * @param m_Wavelength :: incident neutron wavelength, in Angstroms
 * @param HKL :: vector with H,K,L position of the peak
 * @param goniometer :: a 3x3 rotation matrix
 * @return
 */
148
149
150
Peak::Peak(const Geometry::Instrument_const_sptr &m_inst, int m_detectorID,
           double m_Wavelength, const Mantid::Kernel::V3D &HKL,
           const Mantid::Kernel::Matrix<double> &goniometer)
151
152
153
    : m_H(HKL[0]), m_K(HKL[1]), m_L(HKL[2]), m_intensity(0),
      m_sigmaIntensity(0), m_binCount(0), m_GoniometerMatrix(goniometer),
      m_InverseGoniometerMatrix(goniometer), m_runNumber(0), m_monitorCount(0),
154
      m_orig_H(0), m_orig_K(0), m_orig_L(0), m_peakNumber(0),
Hahn, Steven's avatar
Hahn, Steven committed
155
      m_peakShape(boost::make_shared<NoShape>()) {
Lynch, Vickie's avatar
Lynch, Vickie committed
156
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
157
158
159
160
  if (fabs(m_InverseGoniometerMatrix.Invert()) < 1e-8)
    throw std::invalid_argument(
        "Peak::ctor(): Goniometer matrix must non-singular.");
  this->setInstrument(m_inst);
161
  this->setDetectorID(m_detectorID);
162
163
164
165
166
167
168
169
170
171
  this->setWavelength(m_Wavelength);
}
//----------------------------------------------------------------------------------------------
/** Constructor
 *
 * @param m_inst :: Shared pointer to the instrument for this peak detection
 * @param scattering :: fake detector position using scattering angle
 * @param m_Wavelength :: incident neutron wavelength, in Angstroms
 * @return
 */
172
Peak::Peak(const Geometry::Instrument_const_sptr &m_inst, double scattering,
173
           double m_Wavelength)
174
175
176
177
    : m_H(0), m_K(0), m_L(0), m_intensity(0), m_sigmaIntensity(0),
      m_binCount(0), m_GoniometerMatrix(3, 3, true),
      m_InverseGoniometerMatrix(3, 3, true), m_runNumber(0), m_monitorCount(0),
      m_row(-1), m_col(-1), m_orig_H(0), m_orig_K(0), m_orig_L(0),
178
      m_peakNumber(0), m_peakShape(boost::make_shared<NoShape>()) {
Lynch, Vickie's avatar
Lynch, Vickie committed
179
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
180
181
  this->setInstrument(m_inst);
  this->setWavelength(m_Wavelength);
182
  m_detectorID = -1;
183
184
185
  // get the approximate location of the detector
  const auto detectorDir = V3D(sin(scattering), 0.0, cos(scattering));
  detPos = getVirtualDetectorPosition(detectorDir);
186
187
}

188
189
190
191
192
193
/**
 * @brief Copy constructor
 * @param other : Source
 * @return
 */
Peak::Peak(const Peak &other)
194
195
196
197
198
199
    : m_inst(other.m_inst), m_det(other.m_det), m_bankName(other.m_bankName),
      m_detectorID(other.m_detectorID), m_H(other.m_H), m_K(other.m_K),
      m_L(other.m_L), m_intensity(other.m_intensity),
      m_sigmaIntensity(other.m_sigmaIntensity), m_binCount(other.m_binCount),
      m_initialEnergy(other.m_initialEnergy),
      m_finalEnergy(other.m_finalEnergy),
200
201
      m_GoniometerMatrix(other.m_GoniometerMatrix),
      m_InverseGoniometerMatrix(other.m_InverseGoniometerMatrix),
202
203
204
205
      m_runNumber(other.m_runNumber), m_monitorCount(other.m_monitorCount),
      m_row(other.m_row), m_col(other.m_col), sourcePos(other.sourcePos),
      samplePos(other.samplePos), detPos(other.detPos),
      m_orig_H(other.m_orig_H), m_orig_K(other.m_orig_K),
206
207
208
      m_orig_L(other.m_orig_L), m_peakNumber(other.m_peakNumber),
      m_detIDs(other.m_detIDs), m_peakShape(other.m_peakShape->clone()),
      convention(other.convention) {}
209

210
211
212
213
214
215
//----------------------------------------------------------------------------------------------
/** Constructor making a Peak from IPeak interface
 *
 * @param ipeak :: const reference to an IPeak object
 * @return
 */
Owen Arnold's avatar
Owen Arnold committed
216
Peak::Peak(const Geometry::IPeak &ipeak)
217
218
    : IPeak(ipeak), m_detectorID(ipeak.getDetectorID()), m_H(ipeak.getH()),
      m_K(ipeak.getK()), m_L(ipeak.getL()), m_intensity(ipeak.getIntensity()),
219
220
221
222
      m_sigmaIntensity(ipeak.getSigmaIntensity()),
      m_binCount(ipeak.getBinCount()),
      m_initialEnergy(ipeak.getInitialEnergy()),
      m_finalEnergy(ipeak.getFinalEnergy()),
223
224
      m_GoniometerMatrix(ipeak.getGoniometerMatrix()),
      m_InverseGoniometerMatrix(ipeak.getGoniometerMatrix()),
225
      m_runNumber(ipeak.getRunNumber()),
226
227
      m_monitorCount(ipeak.getMonitorCount()), m_row(ipeak.getRow()),
      m_col(ipeak.getCol()), m_orig_H(0.), m_orig_K(0.), m_orig_L(0.),
Lynch, Vickie's avatar
Lynch, Vickie committed
228
      m_peakNumber(ipeak.getPeakNumber()),
229
      m_peakShape(boost::make_shared<NoShape>()) {
Lynch, Vickie's avatar
Lynch, Vickie committed
230
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
  if (fabs(m_InverseGoniometerMatrix.Invert()) < 1e-8)
    throw std::invalid_argument(
        "Peak::ctor(): Goniometer matrix must non-singular.");
  setInstrument(ipeak.getInstrument());
  detid_t id = ipeak.getDetectorID();
  if (id >= 0) {
    setDetectorID(id);
  }
  if (const Peak *peak = dynamic_cast<const Peak *>(&ipeak)) {
    this->m_detIDs = peak->m_detIDs;
  }
}

//----------------------------------------------------------------------------------------------
/** Set the incident wavelength of the neutron. Calculates the energy from this.
 * Assumes elastic scattering.
 *
 * @param wavelength :: wavelength in Angstroms.
 */
void Peak::setWavelength(double wavelength) {
  // Velocity of the neutron (non-relativistic)
  double velocity = PhysicalConstants::h /
                    (wavelength * 1e-10 * PhysicalConstants::NeutronMass);
  // Energy in J of the neutron
  double energy = PhysicalConstants::NeutronMass * velocity * velocity / 2.0;
  // Convert to meV
257
258
  m_initialEnergy = energy / PhysicalConstants::meV;
  m_finalEnergy = m_initialEnergy;
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
}

//----------------------------------------------------------------------------------------------
/** Set the detector ID of the pixel at the centre of the peak and look up and
 * cache
 *  values related to it. It also adds it to the list of contributing detectors
 * for this peak but
 *  does NOT remove the old centre.
 * @param id :: ID of detector at the centre of the peak.
 */
void Peak::setDetectorID(int id) {
  if (!m_inst)
    throw std::runtime_error("Peak::setInstrument(): No instrument is set!");
  this->m_det = m_inst->getDetector(id);
  if (!m_det)
    throw std::runtime_error("Peak::setInstrument(): No detector was found!");

276
  this->m_detectorID = id;
277
278
279
280
281
  addContributingDetID(id);

  detPos = m_det->getPos();

  // We now look for the row/column. -1 if not found.
282
283
  m_row = -1;
  m_col = -1;
284
285
286
287
288
289

  // Go up 2 parents to find the bank/rectangular detector
  IComponent_const_sptr parent = m_det->getParent();

  // Find the ROW by looking at the string name of the pixel. E.g. "pixel12"
  // gives row 12.
290
  m_row = Strings::endsWithInt(m_det->getName());
291
292
293

  if (!parent)
    return;
294
  m_bankName = parent->getName();
295
296
297

  // Find the COLUMN by looking at the string name of the parent. E.g. "tube003"
  // gives column 3.
298
  m_col = Strings::endsWithInt(parent->getName());
299
300
301
302
303
304
305
306
307
308
309
310

  parent = parent->getParent();
  // Use the parent if there is no grandparent.
  if (!parent)
    return;

  // Use the parent if the grandparent is the instrument
  Instrument_const_sptr instrument =
      boost::dynamic_pointer_cast<const Instrument>(parent);
  if (instrument)
    return;
  // Use the grand-parent whenever possible
311
  m_bankName = parent->getName();
312
  // For CORELLI, one level above sixteenpack
313
  if (m_bankName == "sixteenpack") {
314
315
316
317
    parent = parent->getParent();
    m_bankName = parent->getName();
  }

318
319
320
321
322
  // Special for rectangular detectors: find the row and column.
  RectangularDetector_const_sptr retDet =
      boost::dynamic_pointer_cast<const RectangularDetector>(parent);
  if (!retDet)
    return;
323
324
325
  std::pair<int, int> xy = retDet->getXYForDetectorID(m_detectorID);
  m_row = xy.second;
  m_col = xy.first;
326
327
328
329
}

//----------------------------------------------------------------------------------------------
/** Get the ID of the detector at the center of the peak  */
330
int Peak::getDetectorID() const { return m_detectorID; }
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
357
358

//----------------------------------------------------------------------------------------------
/**
 * Add a detector ID that contributed to this peak
 * @param id :: The ID of a detector that contributed to this peak
 */
void Peak::addContributingDetID(const int id) { m_detIDs.insert(id); }

//-------------------------------------------------------------------------------------
/**
 * Removes an ID from the list of contributing detectors
 * @param id :: This ID is removed from the list.
 */
void Peak::removeContributingDetector(const int id) { m_detIDs.erase(id); }

//----------------------------------------------------------------------------------------------
/**
 * Return the set of detector IDs that contribute to this peak
 * @returns A set of unique detector IDs that form this peak
 */
const std::set<int> &Peak::getContributingDetIDs() const { return m_detIDs; }

//----------------------------------------------------------------------------------------------
/** Set the instrument (and save the source/sample pos).
 * Call setDetectorID AFTER this call.
 *
 * @param inst :: Instrument sptr to use
 */
359
void Peak::setInstrument(const Geometry::Instrument_const_sptr &inst) {
360
361
362
363
364
365
  m_inst = inst;
  if (!inst)
    throw std::runtime_error("Peak::setInstrument(): No instrument is set!");

  // Cache some positions
  const Geometry::IComponent_const_sptr sourceObj = m_inst->getSource();
366
  if (sourceObj == nullptr)
367
368
369
370
    throw Exception::InstrumentDefinitionError("Peak::setInstrument(): Failed "
                                               "to get source component from "
                                               "instrument");
  const Geometry::IComponent_const_sptr sampleObj = m_inst->getSample();
371
  if (sampleObj == nullptr)
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
    throw Exception::InstrumentDefinitionError("Peak::setInstrument(): Failed "
                                               "to get sample component from "
                                               "instrument");

  sourcePos = sourceObj->getPos();
  samplePos = sampleObj->getPos();
}

//----------------------------------------------------------------------------------------------
/** Return a shared ptr to the detector at center of peak. */
Geometry::IDetector_const_sptr Peak::getDetector() const { return m_det; }

/** Return a shared ptr to the instrument for this peak. */
Geometry::Instrument_const_sptr Peak::getInstrument() const { return m_inst; }

// -------------------------------------------------------------------------------------
/** Calculate the neutron wavelength (in angstroms) at the peak
 * (Note for inelastic scattering - it is the wavelength corresponding to the
 * final energy)*/
double Peak::getWavelength() const {
  // Energy in J of the neutron
393
  double energy = PhysicalConstants::meV * m_finalEnergy;
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
  // v = sqrt(2.0 * E / m)
  double velocity = sqrt(2.0 * energy / PhysicalConstants::NeutronMass);
  // wavelength = h / mv
  double wavelength =
      PhysicalConstants::h / (PhysicalConstants::NeutronMass * velocity);
  // Return it in angstroms
  return wavelength * 1e10;
}

// -------------------------------------------------------------------------------------
/** Calculate the time of flight (in microseconds) of the neutrons for this
 * peak,
 * using the geometry of the detector  */
double Peak::getTOF() const {
  // First, get the neutron traveling distances
  double L1 = this->getL1();
  double L2 = this->getL2();
  // Energy in J of the neutron
412
413
  double Ei = PhysicalConstants::meV * m_initialEnergy;
  double Ef = PhysicalConstants::meV * m_finalEnergy;
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
  // v = sqrt(2 * E / m)
  double vi = sqrt(2.0 * Ei / PhysicalConstants::NeutronMass);
  double vf = sqrt(2.0 * Ef / PhysicalConstants::NeutronMass);
  // Time of flight in seconds = distance / speed
  double tof = L1 / vi + L2 / vf;
  // Return in microsecond units
  return tof * 1e6;
}

// -------------------------------------------------------------------------------------
/** Calculate the scattering angle of the peak  */
double Peak::getScattering() const {
  // The detector is at 2 theta scattering angle
  V3D beamDir = samplePos - sourcePos;
  V3D detDir = detPos - samplePos;

  return detDir.angle(beamDir);
}

433
434
435
436
437
438
439
440
441
// -------------------------------------------------------------------------------------
/** Calculate the azimuthal angle of the peak  */
double Peak::getAzimuthal() const {
  // The detector is at 2 theta scattering angle
  V3D detDir = detPos - samplePos;

  return atan2(detDir.Y(), detDir.X());
}

442
443
444
445
446
447
448
449
450
451
452
453
454
// -------------------------------------------------------------------------------------
/** Calculate the d-spacing of the peak, in 1/Angstroms  */
double Peak::getDSpacing() const {
  // The detector is at 2 theta scattering angle
  V3D beamDir = samplePos - sourcePos;
  V3D detDir = detPos - samplePos;

  double two_theta = detDir.angle(beamDir);

  // In general case (2*pi/d)^2=k_i^2+k_f^2-2*k_i*k_f*cos(two_theta)
  // E_i,f=k_i,f^2*hbar^2/(2 m)
  return 1e10 * PhysicalConstants::h /
         sqrt(2.0 * PhysicalConstants::NeutronMass * PhysicalConstants::meV) /
455
456
         sqrt(m_initialEnergy + m_finalEnergy -
              2.0 * sqrt(m_initialEnergy * m_finalEnergy) * cos(two_theta));
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
}

//----------------------------------------------------------------------------------------------
/** Return the Q change (of the lattice, k_i - k_f) for this peak.
 * The Q is in the Lab frame: the goniometer rotation was NOT taken out.
 *
 * Note: There is a 2*pi factor used, so |Q| = 2*pi/wavelength.
 * */
Mantid::Kernel::V3D Peak::getQLabFrame() const {
  // Normalized beam direction
  V3D beamDir = samplePos - sourcePos;
  beamDir /= beamDir.norm();
  // Normalized detector direction
  V3D detDir = (detPos - samplePos);
  detDir /= detDir.norm();

  // Energy in J of the neutron
474
  double ei = PhysicalConstants::meV * m_initialEnergy;
475
476
477
478
479
480
481
482
483
484
485
  // v = sqrt(2.0 * E / m)
  double vi = sqrt(2.0 * ei / PhysicalConstants::NeutronMass);
  // wavenumber = h_bar / mv
  double wi = PhysicalConstants::h_bar / (PhysicalConstants::NeutronMass * vi);
  // in angstroms
  wi *= 1e10;
  // wavevector=1/wavenumber = 2pi/wavelength
  double wvi = 1.0 / wi;
  // Now calculate the wavevector of the scattered neutron
  double wvf = (2.0 * M_PI) / this->getWavelength();
  // And Q in the lab frame
486
487
488
489
490
  // Default for ki-kf is positive
  double qSign = 1.0;
  if (convention == "Crystallography")
    qSign = -1.0;
  return (beamDir * wvi - detDir * wvf) * qSign;
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
}

//----------------------------------------------------------------------------------------------
/** Return the Q change (of the lattice, k_i - k_f) for this peak.
 * The Q is in the Sample frame: the goniometer rotation WAS taken out. */
Mantid::Kernel::V3D Peak::getQSampleFrame() const {
  V3D Qlab = this->getQLabFrame();
  // Multiply by the inverse of the goniometer matrix to get the sample frame
  V3D Qsample = m_InverseGoniometerMatrix * Qlab;
  return Qsample;
}

//----------------------------------------------------------------------------------------------
/** Set the peak using the peak's position in reciprocal space, in the sample
 *frame.
 * The GoniometerMatrix will be used to find the Q in the lab frame, so it
 *should
 * be set beforehand.
 *
 * @param QSampleFrame :: Q of the center of the peak, in reciprocal space
 *        This is in inelastic convention: momentum transfer of the LATTICE!
 *        Also, q does NOT have a 2pi factor = it is equal to 1/wavelength.
 * @param detectorDistance :: distance between the sample and the detector.
514
 *        Used to give a valid TOF. You do NOT need to explicitly set this.
515
 */
516
void Peak::setQSampleFrame(const Mantid::Kernel::V3D &QSampleFrame,
Hahn, Steven's avatar
Hahn, Steven committed
517
                           boost::optional<double> detectorDistance) {
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
  V3D Qlab = m_GoniometerMatrix * QSampleFrame;
  this->setQLabFrame(Qlab, detectorDistance);
}

//----------------------------------------------------------------------------------------------
/** Set the peak using the peak's position in reciprocal space, in the lab
 *frame.
 * The detector position will be determined.
 * DetectorID, row and column will be set to -1 since they are not (necessarily)
 *found.
 * You can call findDetector to look for the detector ID
 *
 * @param QLabFrame :: Q of the center of the peak, in reciprocal space.
 *        This is in inelastic convention: momentum transfer of the LATTICE!
 *        Also, q does have a 2pi factor = it is equal to 2pi/wavelength (in
 *Angstroms).
534
535
 * @param detectorDistance :: distance between the sample and the detector. If
 *this is provided. Then we do not
536
 * ray trace to find the intersecing detector.
537
 */
538
void Peak::setQLabFrame(const Mantid::Kernel::V3D &QLabFrame,
Hahn, Steven's avatar
Hahn, Steven committed
539
                        boost::optional<double> detectorDistance) {
540
  // Clear out the detector = we can't know them
541
  m_detectorID = -1;
Samuel Jackson's avatar
Samuel Jackson committed
542
  detPos = V3D();
543
  m_det = IDetector_sptr();
544
545
546
  m_row = -1;
  m_col = -1;
  m_bankName = "None";
547

548
549
550
  // The q-vector direction of the peak is = goniometer * ub * hkl_vector
  V3D q = QLabFrame;

551
552
  /* The incident neutron wavevector is along the beam direction, ki = 1/wl
   * (usually z, but referenceframe is definitive).
553
   * In the inelastic convention, q = ki - kf.
554
555
   * The final neutron wavector kf = -qx in x; -qy in y; and (-q.beam_dir+1/wl)
   * in beam direction.
556
   * AND: norm(kf) = norm(ki) = 2*pi/wavelength
557
   * THEREFORE: 1/wl = norm(q)^2 / (2*q.beam_dir)
558
   */
559
  double norm_q = q.norm();
560
561
562
  if (!this->m_inst) {
    throw std::invalid_argument("Setting QLab without an instrument would lead "
                                "to an inconsistent state for the Peak");
563
  }
564
565
  boost::shared_ptr<const ReferenceFrame> refFrame =
      this->m_inst->getReferenceFrame();
566
  const V3D refBeamDir = refFrame->vecPointingAlongBeam();
567
568
569
570
571
  // Default for ki-kf has -q
  double qSign = 1.0;
  if (convention == "Crystallography")
    qSign = -1.0;
  const double qBeam = q.scalar_prod(refBeamDir) * qSign;
572
573
574

  if (norm_q == 0.0)
    throw std::invalid_argument("Peak::setQLabFrame(): Q cannot be 0,0,0.");
575
  if (qBeam == 0.0)
576
    throw std::invalid_argument(
577
        "Peak::setQLabFrame(): Q cannot be 0 in the beam direction.");
578

579
  double one_over_wl = (norm_q * norm_q) / (2.0 * qBeam);
580
581
582
583
584
585
586
587
588
589
590
  double wl = (2.0 * M_PI) / one_over_wl;
  if (wl < 0.0) {
    std::ostringstream mess;
    mess << "Peak::setQLabFrame(): Wavelength found was negative (" << wl
         << " Ang)! This Q is not physical.";
    throw std::invalid_argument(mess.str());
  }

  // Save the wavelength
  this->setWavelength(wl);

591
592
593
594
595
596
  // Default for ki-kf has -q
  qSign = -1.0;
  if (convention == "Crystallography")
    qSign = 1.0;

  V3D detectorDir = q * qSign;
597
  detectorDir[refFrame->pointingAlongBeam()] = one_over_wl - qBeam;
598
599
  detectorDir.normalize();

600
  // Use the given detector distance to find the detector position.
601
602
603
604
605
606
  if (detectorDistance.is_initialized()) {
    detPos = samplePos + detectorDir * detectorDistance.get();
    // We do not-update the detector as by manually setting the distance the
    // client seems to know better.
  } else {
    // Find the detector
607
608
    InstrumentRayTracer tracer(m_inst);
    const bool found = findDetector(detectorDir, tracer);
609
610
611
612
613
    if (!found) {
      // This is important, so we ought to log when this fails to happen.
      g_log.debug("Could not find detector after setting qLab via setQLab with "
                  "QLab : " +
                  q.toString());
614
615

      detPos = getVirtualDetectorPosition(detectorDir);
616
    }
617
  }
618
619
}

620
621
622
V3D Peak::getVirtualDetectorPosition(const V3D &detectorDir) const {
  const auto component =
      getInstrument()->getComponentByName("extended-detector-space");
623
  if (!component) {
624
    return detectorDir; // the best idea we have is just the direction
625
626
  }

627
628
  const auto object =
      boost::dynamic_pointer_cast<const ObjComponent>(component);
629
  Geometry::Track track(samplePos, detectorDir);
630
  object->shape()->interceptSurface(track);
631
632
633
  return track.back().exitPoint;
}

634
635
636
637
638
639
640
641
642
643
/** After creating a peak using the Q in the lab frame,
 * the detPos is set to the direction of the detector (but the detector is
 *unknown)
 *
 * Using the instrument set in the peak, perform ray tracing
 * to find the exact detector.
 *
 * @return true if the detector ID was found.
 */
bool Peak::findDetector() {
644
645
646
  InstrumentRayTracer tracer(m_inst);
  return findDetector(tracer);
}
647

648
649
650
651
652
653
654
655
/**
 * Performs the same algorithm as findDetector() but uses a pre-existing
 * InstrumentRayTracer object to be able to take adavtange of its caches.
 * This method should be preferred if findDetector is to be called many times
 * over the same instrument.
 * @param tracer A reference to an existing InstrumentRayTracer object.
 * @return true if the detector ID was found.
 */
656
bool Peak::findDetector(const InstrumentRayTracer &tracer) {
657
658
659
660
  // Scattered beam direction
  V3D beam = detPos - samplePos;
  beam.normalize();

661
  return findDetector(beam, tracer);
662
663
664
}

/**
665
666
 * @brief Peak::findDetector : Find the detector along the beam location. sets
 * the detector, and detector position if found
Owen Arnold's avatar
Owen Arnold committed
667
668
 * @param beam : Detector direction from the sample as V3D
 * @param tracer : Ray tracer to use for detector finding
669
670
 * @return True if a detector has been found
 */
671
672
bool Peak::findDetector(const Mantid::Kernel::V3D &beam,
                        const InstrumentRayTracer &tracer) {
673
  bool found = false;
674
  // Create a ray tracer
675
676
  tracer.traceFromSample(beam);
  IDetector_const_sptr det = tracer.getDetectorResult();
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
  if (det) {
    // Set the detector ID, the row, col, etc.
    this->setDetectorID(det->getID());
    // The old detector position is not more precise if it comes from
    // FindPeaksMD
    detPos = det->getPos();
    found = true;
  }
  // Use tube-gap parameter in instrument parameter file  to find peaks with
  // center in gaps between tubes
  else if (m_inst->hasParameter("tube-gap")) {
    std::vector<double> gaps = m_inst->getNumberParameter("tube-gap", true);
    if (!gaps.empty()) {
      const double gap = static_cast<double>(gaps.front());
      // try adding and subtracting tube-gap in 3 q dimensions to see if you can
      // find detectors on each side of tube gap
      for (int i = 0; i < 3; i++) {
        V3D gapDir = V3D(0., 0., 0.);
        gapDir[i] = gap;
        V3D beam1 = beam + gapDir;
697
698
        tracer.traceFromSample(beam1);
        IDetector_const_sptr det1 = tracer.getDetectorResult();
699
        V3D beam2 = beam - gapDir;
700
701
        tracer.traceFromSample(beam2);
        IDetector_const_sptr det2 = tracer.getDetectorResult();
702
703
704
705
706
707
708
        if (det1 && det2) {
          // Set the detector ID to one of the neighboring pixels
          this->setDetectorID(static_cast<int>(det1->getID()));
          ;
          detPos = det1->getPos();
          found = true;
          break;
Lynch, Vickie's avatar
Lynch, Vickie committed
709
        }
710
      }
Lynch, Vickie's avatar
Lynch, Vickie committed
711
    }
712
  }
713
714
715
716
717
  return found;
}

//----------------------------------------------------------------------------------------------
/** Return the run number this peak was measured at. */
718
int Peak::getRunNumber() const { return m_runNumber; }
719
720

/** Set the run number that measured this peak
721
722
 * @param m_runNumber :: the run number   */
void Peak::setRunNumber(int m_runNumber) { this->m_runNumber = m_runNumber; }
723
724
725

//----------------------------------------------------------------------------------------------
/** Return the monitor count stored in this peak. */
726
double Peak::getMonitorCount() const { return m_monitorCount; }
727
728

/** Set the monitor count for this peak
729
730
731
 * @param m_monitorCount :: the monitor count */
void Peak::setMonitorCount(double m_monitorCount) {
  this->m_monitorCount = m_monitorCount;
732
733
734
}

//----------------------------------------------------------------------------------------------
Samuel Jackson's avatar
Samuel Jackson committed
735
/** Get the final neutron energy in meV */
736
double Peak::getFinalEnergy() const { return m_finalEnergy; }
737

Samuel Jackson's avatar
Samuel Jackson committed
738
/** Get the initial (incident) neutron energy in meV */
739
double Peak::getInitialEnergy() const { return m_initialEnergy; }
740

Samuel Jackson's avatar
Samuel Jackson committed
741
/** Get the difference between the initial and final neutron energy in meV */
Samuel Jackson's avatar
Samuel Jackson committed
742
743
744
double Peak::getEnergyTransfer() const {
  return getInitialEnergy() - getFinalEnergy();
}
745

746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
//----------------------------------------------------------------------------------------------
/** Get the H index of the peak */
double Peak::getH() const { return m_H; }

/** Get the K index of the peak */
double Peak::getK() const { return m_K; }

/** Get the L index of the peak */
double Peak::getL() const { return m_L; }

/** Return the HKL vector */
Mantid::Kernel::V3D Peak::getHKL() const { return V3D(m_H, m_K, m_L); }

//----------------------------------------------------------------------------------------------
/** Set the H index of this peak
 * @param m_H :: index to set   */
void Peak::setH(double m_H) { this->m_H = m_H; }

/** Set the K index of this peak
 * @param m_K :: index to set   */
void Peak::setK(double m_K) { this->m_K = m_K; }

/** Set the L index of this peak
 * @param m_L :: index to set   */
void Peak::setL(double m_L) { this->m_L = m_L; }

/** Set the BankName of this peak
773
774
775
 * @param m_bankName :: index to set   */
void Peak::setBankName(std::string m_bankName) {
  this->m_bankName = m_bankName;
776
777
778
779
}

/** Set all three H,K,L indices of the peak */
void Peak::setHKL(double H, double K, double L) {
780
781
782
783
  if (m_orig_H == 0 && m_orig_K == 0 && m_orig_L == 0) {
    m_orig_H = m_H;
    m_orig_K = m_K;
    m_orig_L = m_L;
784
785
786
787
788
789
790
791
  }
  m_H = H;
  m_K = K;
  m_L = L;
}

/** Reset all three H,K,L indices of the peak to values before setHKL */
void Peak::resetHKL() {
792
  if (m_orig_H == 0 && m_orig_K == 0 && m_orig_L == 0)
793
    return;
794
795
796
  m_H = m_orig_H;
  m_K = m_orig_K;
  m_L = m_orig_L;
797
798
799
800
801
802
}

/** Set all HKL
 *
 * @param HKL :: vector with x,y,z -> h,k,l
 */
803
void Peak::setHKL(const Mantid::Kernel::V3D &HKL) {
804
805
806
807
  if (m_orig_H == 0 && m_orig_K == 0 && m_orig_L == 0) {
    m_orig_H = m_H;
    m_orig_K = m_K;
    m_orig_L = m_L;
808
809
810
811
812
813
814
815
  }
  m_H = HKL.X();
  m_K = HKL.Y();
  m_L = HKL.Z();
}

//----------------------------------------------------------------------------------------------
/** Return the # of counts in the bin at its peak*/
816
double Peak::getBinCount() const { return m_binCount; }
817
818

/** Return the integrated peak intensity */
819
double Peak::getIntensity() const { return m_intensity; }
820
821

/** Return the error on the integrated peak intensity */
822
double Peak::getSigmaIntensity() const { return m_sigmaIntensity; }
823

824
/** Return the peak intensity divided by the error in the intensity */
825
double Peak::getIntensityOverSigma() const {
826
827
  const auto result = m_intensity / m_sigmaIntensity;
  return (std::isinf(result)) ? 0.0 : result;
828
829
}

830
/** Set the integrated peak intensity
831
832
 * @param m_intensity :: intensity value   */
void Peak::setIntensity(double m_intensity) { this->m_intensity = m_intensity; }
833
834

/** Set the # of counts in the bin at its peak
835
836
 * @param m_binCount :: counts  */
void Peak::setBinCount(double m_binCount) { this->m_binCount = m_binCount; }
837
838

/** Set the error on the integrated peak intensity
839
840
841
 * @param m_sigmaIntensity :: intensity error value   */
void Peak::setSigmaIntensity(double m_sigmaIntensity) {
  this->m_sigmaIntensity = m_sigmaIntensity;
842
843
844
}

/** Set the final energy
845
846
847
 * @param m_finalEnergy :: final energy in meV   */
void Peak::setFinalEnergy(double m_finalEnergy) {
  this->m_finalEnergy = m_finalEnergy;
848
849
850
}

/** Set the initial energy
851
852
853
 * @param m_initialEnergy :: initial energy in meV   */
void Peak::setInitialEnergy(double m_initialEnergy) {
  this->m_initialEnergy = m_initialEnergy;
854
855
856
857
858
859
860
861
862
863
864
865
}

// -------------------------------------------------------------------------------------
/** Get the goniometer rotation matrix at which this peak was measured. */
Mantid::Kernel::Matrix<double> Peak::getGoniometerMatrix() const {
  return this->m_GoniometerMatrix;
}

/** Set the goniometer rotation matrix at which this peak was measured.
 * @param goniometerMatrix :: 3x3 matrix that represents the rotation matrix of
 * the goniometer
 * @throw std::invalid_argument if matrix is not 3x3*/
866
void Peak::setGoniometerMatrix(
867
    const Mantid::Kernel::Matrix<double> &goniometerMatrix) {
868
869
870
871
872
873
874
875
  if ((goniometerMatrix.numCols() != 3) || (goniometerMatrix.numRows() != 3))
    throw std::invalid_argument(
        "Peak::setGoniometerMatrix(): Goniometer matrix must be 3x3.");
  this->m_GoniometerMatrix = goniometerMatrix;
  // Calc the inverse rotation matrix
  m_InverseGoniometerMatrix = m_GoniometerMatrix;
  if (fabs(m_InverseGoniometerMatrix.Invert()) < 1e-8)
    throw std::invalid_argument(
Samuel Jackson's avatar
Samuel Jackson committed
876
        "Peak::setGoniometerMatrix(): Goniometer matrix must be non-singular.");
877
878
879
880
881
882
883
}

// -------------------------------------------------------------------------------------
/** Find the name of the bank that is the parent of the detector. This works
 * best for RectangularDetector instruments (goes up two levels)
 * @return name of the bank.
 */
884
std::string Peak::getBankName() const { return m_bankName; }
885
886
887

// -------------------------------------------------------------------------------------
/** For RectangularDetectors only, returns the row (y) of the pixel of the
888
889
 * detector.
 * Returns -1 if it could not find it. */
890
int Peak::getRow() const { return m_row; }
891
892
893
894
895

// -------------------------------------------------------------------------------------
/** For RectangularDetectors only, returns the column (x) of the pixel of the
 * detector.
 * Returns -1 if it could not find it. */
896
int Peak::getCol() const { return m_col; }
897

898
899
900
// -------------------------------------------------------------------------------------
/**Returns the unique peak number
 * Returns -1 if it could not find it. */
901
int Peak::getPeakNumber() const { return m_peakNumber; }
902

903
904
905
906
907
908
909
910
911
912
913
914
// -------------------------------------------------------------------------------------
/** For RectangularDetectors only, sets the row (y) of the pixel of the
 * detector.
 * @param m_row :: row value   */
void Peak::setRow(int m_row) { this->m_row = m_row; }

// -------------------------------------------------------------------------------------
/** For RectangularDetectors only, sets the column (x) of the pixel of the
 * detector.
 * @param m_col :: col value   */
void Peak::setCol(int m_col) { this->m_col = m_col; }

915
916
// -------------------------------------------------------------------------------------
/** Sets the unique peak number
917
 * @param m_peakNumber :: unique peak number value   */
918
void Peak::setPeakNumber(int m_peakNumber) {
919
920
921
  this->m_peakNumber = m_peakNumber;
}

922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
// -------------------------------------------------------------------------------------
/** Return the detector position vector */
Mantid::Kernel::V3D Peak::getDetPos() const { return detPos; }

// -------------------------------------------------------------------------------------
/** Return the L1 flight path length (source to sample), in meters. */
double Peak::getL1() const { return (samplePos - sourcePos).norm(); }

// -------------------------------------------------------------------------------------
/** Return the L2 flight path length (sample to detector), in meters. */
double Peak::getL2() const { return (detPos - samplePos).norm(); }

// -------------------------------------------------------------------------------------
/** Helper function for displaying/sorting peaks in MantidPlot
 *
 * @param name_in :: name of the column in the table workspace
 * @return a double representing that value (if that's possible)
 * @throw std::runtime_error if you asked for a column that can't convert to
 *double.
 */
double Peak::getValueByColName(const std::string &name_in) const {
  std::string name = name_in;
  std::transform(name.begin(), name.end(), name.begin(), ::tolower);
  if (name == "runnumber")
    return double(this->getRunNumber());
  else if (name == "detid")
    return double(this->getDetectorID());
  else if (name == "h")
    return this->getH();
  else if (name == "k")
    return this->getK();
  else if (name == "l")
    return this->getL();
  else if (name == "wavelength")
    return this->getWavelength();
  else if (name == "energy")
    return this->getInitialEnergy();
  else if (name == "tof")
    return this->getTOF();
  else if (name == "dspacing")
    return this->getDSpacing();
  else if (name == "intens")
    return this->getIntensity();
  else if (name == "sigint")
    return this->getSigmaIntensity();
967
968
  else if (name == "int/sigint")
    return this->getIntensityOverSigma();
969
970
971
972
973
974
  else if (name == "bincount")
    return this->getBinCount();
  else if (name == "row")
    return this->getRow();
  else if (name == "col")
    return this->getCol();
Lynch, Vickie's avatar
Lynch, Vickie committed
975
  else if (name == "peaknumber")
976
    return double(this->getPeakNumber());
977
978
979
980
981
982
  else
    throw std::runtime_error(
        "Peak::getValueByColName() unknown column or column is not a number: " +
        name);
}

983
984
985
986
/**
 * @brief Get the peak shape
 * @return : const ref to current peak shape.
 */
Owen Arnold's avatar
Owen Arnold committed
987
const PeakShape &Peak::getPeakShape() const { return *this->m_peakShape; }
988
989
990
991
992

/**
 * @brief Set the peak shape
 * @param shape : Desired shape
 */
993
994
995
void Peak::setPeakShape(Mantid::Geometry::PeakShape *shape) {
  this->m_peakShape = PeakShape_const_sptr(shape);
}
996
997
998
999
1000

/**
 * @brief Set the peak shape
 * @param shape : Desired shape
 */
For faster browsing, not all history is shown. View entire blame