Peak.cpp 28.2 KB
Newer Older
1
2
3
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
4
5
//   NScD Oak Ridge National Laboratory, European Spallation Source,
//   Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6
// SPDX - License - Identifier: GPL - 3.0 +
7
#include "MantidDataObjects/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
34
Peak::Peak()
    : 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
49
50
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
}

//----------------------------------------------------------------------------------------------
/** 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)
51
    : BasePeak() {
Lynch, Vickie's avatar
Lynch, Vickie committed
52
53
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
  this->setInstrument(m_inst);
David Fairbrother's avatar
David Fairbrother committed
54
  this->setQLabFrame(QLabFrame, std::move(detectorDistance));
Lynch, Vickie's avatar
Lynch, Vickie committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
}

//----------------------------------------------------------------------------------------------
/** 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)
74
    : BasePeak(goniometer) {
Lynch, Vickie's avatar
Lynch, Vickie committed
75
76
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
  this->setInstrument(m_inst);
David Fairbrother's avatar
David Fairbrother committed
77
  this->setQSampleFrame(QSampleFrame, std::move(detectorDistance));
Lynch, Vickie's avatar
Lynch, Vickie committed
78
79
80
81
82
83
84
85
86
87
88
89
}

//----------------------------------------------------------------------------------------------
/** 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)
90
    : BasePeak() {
Lynch, Vickie's avatar
Lynch, Vickie committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
  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)
108
    : BasePeak() {
Lynch, Vickie's avatar
Lynch, Vickie committed
109
110
111
112
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
  this->setInstrument(m_inst);
  this->setDetectorID(m_detectorID);
  this->setWavelength(m_Wavelength);
113
  this->setHKL(HKL);
Lynch, Vickie's avatar
Lynch, Vickie committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
}

//----------------------------------------------------------------------------------------------
/** 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)
129
    : BasePeak(goniometer) {
Lynch, Vickie's avatar
Lynch, Vickie committed
130
131
132
133
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
  this->setInstrument(m_inst);
  this->setDetectorID(m_detectorID);
  this->setWavelength(m_Wavelength);
134
  this->setHKL(HKL);
Lynch, Vickie's avatar
Lynch, Vickie committed
135
136
137
138
139
140
141
142
143
144
145
}
//----------------------------------------------------------------------------------------------
/** 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)
146
    : BasePeak() {
Lynch, Vickie's avatar
Lynch, Vickie committed
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
  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)
162
    : BasePeak(other), m_inst(other.m_inst), m_det(other.m_det),
163
164
      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
165
      samplePos(other.samplePos), detPos(other.detPos),
166
      m_detIDs(other.m_detIDs), convention(other.convention) {}
Lynch, Vickie's avatar
Lynch, Vickie committed
167
168
169
170
171
172
173
174

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

189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
//----------------------------------------------------------------------------------------------
/** 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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
//----------------------------------------------------------------------------------------------
/** 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.
227
228
  setRow(-1);
  setCol(-1);
Lynch, Vickie's avatar
Lynch, Vickie committed
229
230
231
232
233
234

  // 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.
235
  setRow(Strings::endsWithInt(m_det->getName()));
Lynch, Vickie's avatar
Lynch, Vickie committed
236
237
238

  if (!parent)
    return;
239
  setBankName(parent->getName());
Lynch, Vickie's avatar
Lynch, Vickie committed
240
241
242

  // Find the COLUMN by looking at the string name of the parent. E.g. "tube003"
  // gives column 3.
243
  setCol(Strings::endsWithInt(parent->getName()));
Lynch, Vickie's avatar
Lynch, Vickie committed
244
245
246
247
248
249
250
251

  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 =
252
      std::dynamic_pointer_cast<const Instrument>(parent);
Lynch, Vickie's avatar
Lynch, Vickie committed
253
254
255
  if (instrument)
    return;
  // Use the grand-parent whenever possible
256
  setBankName(parent->getName());
Lynch, Vickie's avatar
Lynch, Vickie committed
257
  // For CORELLI, one level above sixteenpack
258
  if (getBankName() == "sixteenpack") {
Lynch, Vickie's avatar
Lynch, Vickie committed
259
    parent = parent->getParent();
260
    setBankName(parent->getName());
Lynch, Vickie's avatar
Lynch, Vickie committed
261
262
263
264
  }

  // Special for rectangular detectors: find the row and column.
  RectangularDetector_const_sptr retDet =
265
      std::dynamic_pointer_cast<const RectangularDetector>(parent);
Lynch, Vickie's avatar
Lynch, Vickie committed
266
267
268
  if (!retDet)
    return;
  std::pair<int, int> xy = retDet->getXYForDetectorID(m_detectorID);
269
270
  setRow(xy.second);
  setCol(xy.first);
Lynch, Vickie's avatar
Lynch, Vickie committed
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
324
325
326
327
328
329
330
331
}

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

332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// -------------------------------------------------------------------------------------
/** 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
348
349
350
351
352
353
354
355
356
// -------------------------------------------------------------------------------------
/** 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
357
358
  double Ei = PhysicalConstants::meV * getInitialEnergy();
  double Ef = PhysicalConstants::meV * getFinalEnergy();
Lynch, Vickie's avatar
Lynch, Vickie committed
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
392
393
  // 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;

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

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

//----------------------------------------------------------------------------------------------
/** 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
425
  double ei = PhysicalConstants::meV * getInitialEnergy();
Lynch, Vickie's avatar
Lynch, Vickie committed
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
  // 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
450
  V3D Qsample = getInverseGoniometerMatrix() * Qlab;
Lynch, Vickie's avatar
Lynch, Vickie committed
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
  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) {
469
  V3D Qlab = getGoniometerMatrix() * QSampleFrame;
Lynch, Vickie's avatar
Lynch, Vickie committed
470
471
472
473
474
475
476
477
478
479
480
  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
 *
481
 * @param qLab :: Q of the center of the peak, in reciprocal space.
Lynch, Vickie's avatar
Lynch, Vickie committed
482
483
484
485
486
487
488
 *        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.
 */
489
void Peak::setQLabFrame(const Mantid::Kernel::V3D &qLab,
Lynch, Vickie's avatar
Lynch, Vickie committed
490
                        boost::optional<double> detectorDistance) {
491
492
493
494
  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
495
496
497
498
  // Clear out the detector = we can't know them
  m_detectorID = -1;
  detPos = V3D();
  m_det = IDetector_sptr();
499
500
501
  setRow(-1);
  setCol(-1);
  setBankName("None");
Lynch, Vickie's avatar
Lynch, Vickie committed
502

503
504
  /* The q-vector direction of the peak is = goniometer * ub * hkl_vector
   * The incident neutron wavevector is along the beam direction, ki = 1/wl
Lynch, Vickie's avatar
Lynch, Vickie committed
505
506
507
508
509
510
511
   * (usually z, but referenceframe is definitive).
   * In the inelastic convention, q = ki - kf.
   * The final neutron wavector kf = -qx in x; -qy in y; and (-q.beam_dir+1/wl)
   * in beam direction.
   * AND: norm(kf) = norm(ki) = 2*pi/wavelength
   * THEREFORE: 1/wl = norm(q)^2 / (2*q.beam_dir)
   */
512
513
514
515
  const double norm_q = qLab.norm();
  if (norm_q == 0.0)
    throw std::invalid_argument("Peak::setQLabFrame(): Q cannot be 0,0,0.");

516
  std::shared_ptr<const ReferenceFrame> refFrame =
Lynch, Vickie's avatar
Lynch, Vickie committed
517
518
519
      this->m_inst->getReferenceFrame();
  const V3D refBeamDir = refFrame->vecPointingAlongBeam();
  // Default for ki-kf has -q
520
521
  const double qSign = (convention != "Crystallography") ? 1.0 : -1.0;
  const double qBeam = qLab.scalar_prod(refBeamDir) * qSign;
Lynch, Vickie's avatar
Lynch, Vickie committed
522
523
524
525
526

  if (qBeam == 0.0)
    throw std::invalid_argument(
        "Peak::setQLabFrame(): Q cannot be 0 in the beam direction.");

527
528
  const double one_over_wl = (norm_q * norm_q) / (2.0 * qBeam);
  const double wl = (2.0 * M_PI) / one_over_wl;
Lynch, Vickie's avatar
Lynch, Vickie committed
529
530
531
532
533
534
535
536
537
538
  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);

539
  V3D detectorDir = -qLab * qSign;
Lynch, Vickie's avatar
Lynch, Vickie committed
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
  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 : " +
556
                  qLab.toString());
Lynch, Vickie's avatar
Lynch, Vickie committed
557
558
559
560
561
562
563
564
565
566
567
568

      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
  }
569
  const auto object = std::dynamic_pointer_cast<const ObjComponent>(component);
570
571
572
  const auto distance =
      object->shape()->distance(Geometry::Track(samplePos, detectorDir));
  return detectorDir * distance;
Lynch, Vickie's avatar
Lynch, Vickie committed
573
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
}

/** 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
599
  const V3D beam = normalize(detPos - samplePos);
Lynch, Vickie's avatar
Lynch, Vickie committed
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629

  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()) {
630
      const auto gap = static_cast<double>(gaps.front());
Lynch, Vickie's avatar
Lynch, Vickie committed
631
632
633
      // 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++) {
634
        V3D gapDir;
Lynch, Vickie's avatar
Lynch, Vickie committed
635
636
        gapDir[i] = gap;
        V3D beam1 = beam + gapDir;
637
        tracer.traceFromSample(normalize(beam1));
Lynch, Vickie's avatar
Lynch, Vickie committed
638
639
        IDetector_const_sptr det1 = tracer.getDetectorResult();
        V3D beam2 = beam - gapDir;
640
        tracer.traceFromSample(normalize(beam2));
Lynch, Vickie's avatar
Lynch, Vickie committed
641
642
643
644
645
646
647
        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;
648
        }
Lynch, Vickie's avatar
Lynch, Vickie committed
649
650
651
652
653
654
      }
    }
  }
  return found;
}

655
656
657
658
659
660
661
662
663
664
665
666
//----------------------------------------------------------------------------------------------
/** 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();
}

667
/** Set sample position
Sullivan, Brendan T's avatar
Sullivan, Brendan T committed
668
669
670
 *
 * @ doubles x,y,z-> samplePos(x), samplePos(y), samplePos(z)
 */
671
672
673
674
675
676
677
678
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
679
680
681
682
 *
 * @param XYZ :: vector x,y,z-> samplePos(x), samplePos(y), samplePos(z)
 */
void Peak::setSamplePos(const Mantid::Kernel::V3D &XYZ) {
683
684
685
686
687

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

689
690
691
692
693
694
695
696
697
698
699
700
/** 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
701
702
703
704
// -------------------------------------------------------------------------------------
/** Return the detector position vector */
Mantid::Kernel::V3D Peak::getDetPos() const { return detPos; }

705
706
707
708
// -------------------------------------------------------------------------------------
/** Return the sample position vector */
Mantid::Kernel::V3D Peak::getSamplePos() const { return samplePos; }

Lynch, Vickie's avatar
Lynch, Vickie committed
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
// -------------------------------------------------------------------------------------
/** 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) {
724
    BasePeak::operator=(other);
Lynch, Vickie's avatar
Lynch, Vickie committed
725
726
727
    m_inst = other.m_inst;
    m_det = other.m_det;
    m_detectorID = other.m_detectorID;
728
729
    m_initialEnergy = other.m_initialEnergy;
    m_finalEnergy = other.m_finalEnergy;
Lynch, Vickie's avatar
Lynch, Vickie committed
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
    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