Peak.cpp 26.9 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/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 "MantidGeometry/Surfaces/LineIntersectVisit.h"
13
#include "MantidKernel/ConfigService.h"
14
#include "MantidKernel/Exception.h"
Janik Zikovsky's avatar
Janik Zikovsky committed
15
#include "MantidKernel/Strings.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>
David Fairbrother's avatar
David Fairbrother committed
22
#include <utility>
23

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

28
namespace Mantid {
Lynch, Vickie's avatar
Lynch, Vickie committed
29
30
31
32
namespace DataObjects {

//----------------------------------------------------------------------------------------------
/** Default constructor */
33
Peak::Peak()
34
    : BasePeak(), m_detectorID(-1), m_initialEnergy(0.), m_finalEnergy(0.) {}
Lynch, Vickie's avatar
Lynch, Vickie committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48

//----------------------------------------------------------------------------------------------
/** 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
 * @param detectorDistance :: Optional distance between the sample and the
 *detector. Calculated if not explicitly provided.
 *        Used to give a valid TOF. Default 1.0 meters.
 */
Peak::Peak(const Geometry::Instrument_const_sptr &m_inst,
           const Mantid::Kernel::V3D &QLabFrame,
           boost::optional<double> detectorDistance)
49
    : BasePeak() {
Lynch, Vickie's avatar
Lynch, Vickie committed
50
  this->setInstrument(m_inst);
David Fairbrother's avatar
David Fairbrother committed
51
  this->setQLabFrame(QLabFrame, std::move(detectorDistance));
Lynch, Vickie's avatar
Lynch, Vickie committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
}

//----------------------------------------------------------------------------------------------
/** 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
 * @param detectorDistance :: Optional distance between the sample and the
 *detector. Calculated if not explicitly provided.
 *        Used to give a valid TOF. Default 1.0 meters.
 */
Peak::Peak(const Geometry::Instrument_const_sptr &m_inst,
           const Mantid::Kernel::V3D &QSampleFrame,
           const Mantid::Kernel::Matrix<double> &goniometer,
           boost::optional<double> detectorDistance)
71
    : BasePeak(goniometer) {
Lynch, Vickie's avatar
Lynch, Vickie committed
72
  this->setInstrument(m_inst);
David Fairbrother's avatar
David Fairbrother committed
73
  this->setQSampleFrame(QSampleFrame, std::move(detectorDistance));
Lynch, Vickie's avatar
Lynch, Vickie committed
74
75
76
77
78
79
80
81
82
83
84
85
}

//----------------------------------------------------------------------------------------------
/** Constructor
 *
 * @param m_inst :: Shared pointer to the instrument for this peak detection
 * @param m_detectorID :: ID to the detector of the center of the peak
 * @param m_Wavelength :: incident neutron wavelength, in Angstroms
 * @return
 */
Peak::Peak(const Geometry::Instrument_const_sptr &m_inst, int m_detectorID,
           double m_Wavelength)
86
    : BasePeak() {
Lynch, Vickie's avatar
Lynch, Vickie committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
  this->setInstrument(m_inst);
  this->setDetectorID(m_detectorID);
  this->setWavelength(m_Wavelength);
}

//----------------------------------------------------------------------------------------------
/** Constructor
 *
 * @param m_inst :: Shared pointer to the instrument for this peak detection
 * @param m_detectorID :: ID to the detector of the center of the peak
 * @param m_Wavelength :: incident neutron wavelength, in Angstroms
 * @param HKL :: vector with H,K,L position of the peak
 * @return
 */
Peak::Peak(const Geometry::Instrument_const_sptr &m_inst, int m_detectorID,
           double m_Wavelength, const Mantid::Kernel::V3D &HKL)
103
    : BasePeak() {
Lynch, Vickie's avatar
Lynch, Vickie committed
104
105
106
  this->setInstrument(m_inst);
  this->setDetectorID(m_detectorID);
  this->setWavelength(m_Wavelength);
107
  this->setHKL(HKL);
Lynch, Vickie's avatar
Lynch, Vickie committed
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
}

//----------------------------------------------------------------------------------------------
/** Constructor
 *
 * @param m_inst :: Shared pointer to the instrument for this peak detection
 * @param m_detectorID :: ID to the detector of the center of the peak
 * @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
 */
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)
123
    : BasePeak(goniometer) {
Lynch, Vickie's avatar
Lynch, Vickie committed
124
125
126
  this->setInstrument(m_inst);
  this->setDetectorID(m_detectorID);
  this->setWavelength(m_Wavelength);
127
  this->setHKL(HKL);
Lynch, Vickie's avatar
Lynch, Vickie committed
128
129
130
131
132
133
134
135
136
137
138
}
//----------------------------------------------------------------------------------------------
/** 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
 */
Peak::Peak(const Geometry::Instrument_const_sptr &m_inst, double scattering,
           double m_Wavelength)
139
    : BasePeak() {
Lynch, Vickie's avatar
Lynch, Vickie committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
  this->setInstrument(m_inst);
  this->setWavelength(m_Wavelength);
  m_detectorID = -1;
  // get the approximate location of the detector
  const auto detectorDir = V3D(sin(scattering), 0.0, cos(scattering));
  detPos = getVirtualDetectorPosition(detectorDir);
}

/**
 * @brief Copy constructor
 * @param other : Source
 * @return
 */
Peak::Peak(const Peak &other)
154
    : BasePeak(other), m_inst(other.m_inst), m_det(other.m_det),
155
156
      m_detectorID(other.m_detectorID), m_initialEnergy(other.m_initialEnergy),
      m_finalEnergy(other.m_finalEnergy), sourcePos(other.sourcePos),
Lynch, Vickie's avatar
Lynch, Vickie committed
157
      samplePos(other.samplePos), detPos(other.detPos),
158
      m_detIDs(other.m_detIDs) {}
Lynch, Vickie's avatar
Lynch, Vickie committed
159
160
161
162
163
164
165
166

//----------------------------------------------------------------------------------------------
/** Constructor making a Peak from IPeak interface
 *
 * @param ipeak :: const reference to an IPeak object
 * @return
 */
Peak::Peak(const Geometry::IPeak &ipeak)
167
168
169
    : BasePeak(ipeak), m_detectorID(ipeak.getDetectorID()),
      m_initialEnergy(ipeak.getInitialEnergy()),
      m_finalEnergy(ipeak.getFinalEnergy()) {
Lynch, Vickie's avatar
Lynch, Vickie committed
170
171
172
173
174
175
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
  setInstrument(ipeak.getInstrument());
  detid_t id = ipeak.getDetectorID();
  if (id >= 0) {
    setDetectorID(id);
  }
176
  if (const auto *peak = dynamic_cast<const Peak *>(&ipeak)) {
Lynch, Vickie's avatar
Lynch, Vickie committed
177
178
179
180
    this->m_detIDs = peak->m_detIDs;
  }
}

181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
//----------------------------------------------------------------------------------------------
/** 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
  m_initialEnergy = energy / PhysicalConstants::meV;
  m_finalEnergy = m_initialEnergy;
}

Lynch, Vickie's avatar
Lynch, Vickie committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
//----------------------------------------------------------------------------------------------
/** 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!");

  this->m_detectorID = id;
  addContributingDetID(id);

  detPos = m_det->getPos();

  // We now look for the row/column. -1 if not found.
219
220
  setRow(-1);
  setCol(-1);
Lynch, Vickie's avatar
Lynch, Vickie committed
221
222
223
224
225
226

  // 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.
227
  setRow(Strings::endsWithInt(m_det->getName()));
Lynch, Vickie's avatar
Lynch, Vickie committed
228
229
230

  if (!parent)
    return;
231
  setBankName(parent->getName());
Lynch, Vickie's avatar
Lynch, Vickie committed
232
233
234

  // Find the COLUMN by looking at the string name of the parent. E.g. "tube003"
  // gives column 3.
235
  setCol(Strings::endsWithInt(parent->getName()));
Lynch, Vickie's avatar
Lynch, Vickie committed
236
237
238
239
240
241
242
243

  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 =
244
      std::dynamic_pointer_cast<const Instrument>(parent);
Lynch, Vickie's avatar
Lynch, Vickie committed
245
246
247
  if (instrument)
    return;
  // Use the grand-parent whenever possible
248
  setBankName(parent->getName());
Lynch, Vickie's avatar
Lynch, Vickie committed
249
  // For CORELLI, one level above sixteenpack
250
  if (getBankName() == "sixteenpack") {
Lynch, Vickie's avatar
Lynch, Vickie committed
251
    parent = parent->getParent();
252
    setBankName(parent->getName());
Lynch, Vickie's avatar
Lynch, Vickie committed
253
254
255
256
  }

  // Special for rectangular detectors: find the row and column.
  RectangularDetector_const_sptr retDet =
257
      std::dynamic_pointer_cast<const RectangularDetector>(parent);
Lynch, Vickie's avatar
Lynch, Vickie committed
258
259
260
  if (!retDet)
    return;
  std::pair<int, int> xy = retDet->getXYForDetectorID(m_detectorID);
261
262
  setRow(xy.second);
  setCol(xy.first);
Lynch, Vickie's avatar
Lynch, Vickie committed
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
}

//----------------------------------------------------------------------------------------------
/** Get the ID of the detector at the center of the peak  */
int Peak::getDetectorID() const { return m_detectorID; }

//----------------------------------------------------------------------------------------------
/**
 * 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
 */
void Peak::setInstrument(const Geometry::Instrument_const_sptr &inst) {
  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();
  if (sourceObj == nullptr)
    throw Exception::InstrumentDefinitionError("Peak::setInstrument(): Failed "
                                               "to get source component from "
                                               "instrument");
  const Geometry::IComponent_const_sptr sampleObj = m_inst->getSample();
  if (sampleObj == nullptr)
    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; }

324
325
326
327
328
329
/** Return a shared ptr to the instrument for this peak. */
std::shared_ptr<const Geometry::ReferenceFrame>
Peak::getReferenceFrame() const {
  return m_inst->getReferenceFrame();
}

330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// -------------------------------------------------------------------------------------
/** 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
  double energy = PhysicalConstants::meV * m_finalEnergy;
  // 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;
}

Lynch, Vickie's avatar
Lynch, Vickie committed
346
347
348
349
350
351
352
353
354
// -------------------------------------------------------------------------------------
/** 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
355
356
  double Ei = PhysicalConstants::meV * getInitialEnergy();
  double Ef = PhysicalConstants::meV * getFinalEnergy();
Lynch, Vickie's avatar
Lynch, Vickie committed
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
  // 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);
}

// -------------------------------------------------------------------------------------
/** 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());
}

// -------------------------------------------------------------------------------------
/** 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;

392
393
394
  double two_theta;
  try {
    two_theta = detDir.angle(beamDir);
395
  } catch (std::runtime_error &) {
396
397
    two_theta = 0.;
  }
Lynch, Vickie's avatar
Lynch, Vickie committed
398
399
400
401
402

  // 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) /
403
404
405
         sqrt(getInitialEnergy() + getFinalEnergy() -
              2.0 * sqrt(getInitialEnergy() * getFinalEnergy()) *
                  cos(two_theta));
Lynch, Vickie's avatar
Lynch, Vickie committed
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
}

//----------------------------------------------------------------------------------------------
/** 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
423
  double ei = PhysicalConstants::meV * getInitialEnergy();
Lynch, Vickie's avatar
Lynch, Vickie committed
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
  // 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
  // Default for ki-kf is positive
  double qSign = 1.0;
  if (convention == "Crystallography")
    qSign = -1.0;
  return (beamDir * wvi - detDir * wvf) * qSign;
}

//----------------------------------------------------------------------------------------------
/** 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
448
  V3D Qsample = getInverseGoniometerMatrix() * Qlab;
Lynch, Vickie's avatar
Lynch, Vickie committed
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
  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.
 *        Used to give a valid TOF. You do NOT need to explicitly set this.
 */
void Peak::setQSampleFrame(const Mantid::Kernel::V3D &QSampleFrame,
                           boost::optional<double> detectorDistance) {
467
  V3D Qlab = getGoniometerMatrix() * QSampleFrame;
Lynch, Vickie's avatar
Lynch, Vickie committed
468
469
470
471
472
473
474
475
476
477
478
  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
 *
479
 * @param qLab :: Q of the center of the peak, in reciprocal space.
Lynch, Vickie's avatar
Lynch, Vickie committed
480
481
482
483
484
485
486
 *        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).
 * @param detectorDistance :: distance between the sample and the detector. If
 *this is provided. Then we do not
 * ray trace to find the intersecing detector.
 */
487
void Peak::setQLabFrame(const Mantid::Kernel::V3D &qLab,
Lynch, Vickie's avatar
Lynch, Vickie committed
488
                        boost::optional<double> detectorDistance) {
489
490
491
492
  if (!this->m_inst) {
    throw std::invalid_argument("Setting QLab without an instrument would lead "
                                "to an inconsistent state for the Peak");
  }
Lynch, Vickie's avatar
Lynch, Vickie committed
493
494
495
496
  // Clear out the detector = we can't know them
  m_detectorID = -1;
  detPos = V3D();
  m_det = IDetector_sptr();
497
498
499
  setRow(-1);
  setCol(-1);
  setBankName("None");
Lynch, Vickie's avatar
Lynch, Vickie committed
500

501
502
503
  const double wl = calculateWavelengthFromQLab(qLab);

  std::shared_ptr<const ReferenceFrame> refFrame = getReferenceFrame();
Lynch, Vickie's avatar
Lynch, Vickie committed
504
505
  const V3D refBeamDir = refFrame->vecPointingAlongBeam();
  // Default for ki-kf has -q
506
507
  const double qSign = (convention != "Crystallography") ? 1.0 : -1.0;
  const double qBeam = qLab.scalar_prod(refBeamDir) * qSign;
508
  const double one_over_wl = (2.0 * M_PI) / wl;
Lynch, Vickie's avatar
Lynch, Vickie committed
509
510
511
512

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

513
  V3D detectorDir = -qLab * qSign;
Lynch, Vickie's avatar
Lynch, Vickie committed
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
  detectorDir[refFrame->pointingAlongBeam()] = one_over_wl - qBeam;
  detectorDir.normalize();

  // Use the given detector distance to find the detector position.
  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
    InstrumentRayTracer tracer(m_inst);
    const bool found = findDetector(detectorDir, tracer);
    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 : " +
530
                  qLab.toString());
Lynch, Vickie's avatar
Lynch, Vickie committed
531
532
533
534
535
536
537
538
539
540
541
542

      detPos = getVirtualDetectorPosition(detectorDir);
    }
  }
}

V3D Peak::getVirtualDetectorPosition(const V3D &detectorDir) const {
  const auto component =
      getInstrument()->getComponentByName("extended-detector-space");
  if (!component) {
    return detectorDir; // the best idea we have is just the direction
  }
543
  const auto object = std::dynamic_pointer_cast<const ObjComponent>(component);
544
545
546
  const auto distance =
      object->shape()->distance(Geometry::Track(samplePos, detectorDir));
  return detectorDir * distance;
Lynch, Vickie's avatar
Lynch, Vickie committed
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
}

/** 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() {
  InstrumentRayTracer tracer(m_inst);
  return findDetector(tracer);
}

/**
 * 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.
 */
bool Peak::findDetector(const InstrumentRayTracer &tracer) {
  // Scattered beam direction
573
  const V3D beam = normalize(detPos - samplePos);
Lynch, Vickie's avatar
Lynch, Vickie committed
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603

  return findDetector(beam, tracer);
}

/**
 * @brief Peak::findDetector : Find the detector along the beam location. sets
 * the detector, and detector position if found
 * @param beam : Detector direction from the sample as V3D
 * @param tracer : Ray tracer to use for detector finding
 * @return True if a detector has been found
 */
bool Peak::findDetector(const Mantid::Kernel::V3D &beam,
                        const InstrumentRayTracer &tracer) {
  bool found = false;
  // Create a ray tracer
  tracer.traceFromSample(beam);
  IDetector_const_sptr det = tracer.getDetectorResult();
  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()) {
604
      const auto gap = static_cast<double>(gaps.front());
Lynch, Vickie's avatar
Lynch, Vickie committed
605
606
607
      // 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++) {
608
        V3D gapDir;
Lynch, Vickie's avatar
Lynch, Vickie committed
609
610
        gapDir[i] = gap;
        V3D beam1 = beam + gapDir;
611
        tracer.traceFromSample(normalize(beam1));
Lynch, Vickie's avatar
Lynch, Vickie committed
612
613
        IDetector_const_sptr det1 = tracer.getDetectorResult();
        V3D beam2 = beam - gapDir;
614
        tracer.traceFromSample(normalize(beam2));
Lynch, Vickie's avatar
Lynch, Vickie committed
615
616
617
618
619
620
621
        IDetector_const_sptr det2 = tracer.getDetectorResult();
        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;
622
        }
Lynch, Vickie's avatar
Lynch, Vickie committed
623
624
625
626
627
628
      }
    }
  }
  return found;
}

629
630
631
632
633
634
635
636
637
638
639
640
//----------------------------------------------------------------------------------------------
/** Get the final neutron energy in meV */
double Peak::getFinalEnergy() const { return m_finalEnergy; }

/** Get the initial (incident) neutron energy in meV */
double Peak::getInitialEnergy() const { return m_initialEnergy; }

/** Get the difference between the initial and final neutron energy in meV */
double Peak::getEnergyTransfer() const {
  return getInitialEnergy() - getFinalEnergy();
}

641
/** Set sample position
Sullivan, Brendan T's avatar
Sullivan, Brendan T committed
642
643
644
 *
 * @ doubles x,y,z-> samplePos(x), samplePos(y), samplePos(z)
 */
645
646
647
648
649
650
651
652
void Peak::setSamplePos(double samX, double samY, double samZ) {

  this->samplePos[0] = samX;
  this->samplePos[1] = samY;
  this->samplePos[2] = samZ;
}

/** Set sample position
Sullivan, Brendan T's avatar
Sullivan, Brendan T committed
653
654
655
656
 *
 * @param XYZ :: vector x,y,z-> samplePos(x), samplePos(y), samplePos(z)
 */
void Peak::setSamplePos(const Mantid::Kernel::V3D &XYZ) {
657
658
659
660
661

  this->samplePos[0] = XYZ[0];
  this->samplePos[1] = XYZ[1];
  this->samplePos[2] = XYZ[2];
}
Lynch, Vickie's avatar
Lynch, Vickie committed
662

663
664
665
666
667
668
669
670
671
672
673
674
/** Set the final energy
 * @param m_finalEnergy :: final energy in meV   */
void Peak::setFinalEnergy(double m_finalEnergy) {
  this->m_finalEnergy = m_finalEnergy;
}

/** Set the initial energy
 * @param m_initialEnergy :: initial energy in meV   */
void Peak::setInitialEnergy(double m_initialEnergy) {
  this->m_initialEnergy = m_initialEnergy;
}

Lynch, Vickie's avatar
Lynch, Vickie committed
675
676
677
678
// -------------------------------------------------------------------------------------
/** Return the detector position vector */
Mantid::Kernel::V3D Peak::getDetPos() const { return detPos; }

679
680
681
682
// -------------------------------------------------------------------------------------
/** Return the sample position vector */
Mantid::Kernel::V3D Peak::getSamplePos() const { return samplePos; }

Lynch, Vickie's avatar
Lynch, Vickie committed
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
// -------------------------------------------------------------------------------------
/** 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(); }

/**
 * @brief Assignement operator overload
 * @param other : Other peak object to assign from
 * @return this
 */
Peak &Peak::operator=(const Peak &other) {
  if (&other != this) {
698
    BasePeak::operator=(other);
Lynch, Vickie's avatar
Lynch, Vickie committed
699
700
701
    m_inst = other.m_inst;
    m_det = other.m_det;
    m_detectorID = other.m_detectorID;
702
703
    m_initialEnergy = other.m_initialEnergy;
    m_finalEnergy = other.m_finalEnergy;
Lynch, Vickie's avatar
Lynch, Vickie committed
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
    sourcePos = other.sourcePos;
    samplePos = other.samplePos;
    detPos = other.detPos;
    m_detIDs = other.m_detIDs;
    convention = other.convention;
  }
  return *this;
}

/**
 Forwarding function. Exposes the detector position directly.
 */
Mantid::Kernel::V3D Peak::getDetectorPositionNoCheck() const {
  return getDetector()->getPos();
}

/**
 Forwarding function. Exposes the detector position directly, but checks that
 the detector is not null before accessing its position. Throws if null.
 */
Mantid::Kernel::V3D Peak::getDetectorPosition() const {
  auto det = getDetector();
  if (det == nullptr) {
    throw Mantid::Kernel::Exception::NullPointerException("Peak", "Detector");
  }
  return getDetector()->getPos();
}

Mantid::Kernel::Logger Peak::g_log("PeakLogger");

} // namespace DataObjects
} // namespace Mantid