LeanPeak.cpp 42.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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
257
258
259
260
261
262
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
324
325
326
327
328
329
330
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
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
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
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
599
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
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
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 & CSNS, Institute of High Energy Physics, CAS
// SPDX - License - Identifier: GPL - 3.0 +
#include "MantidDataObjects/LeanPeak.h"
#include "MantidDataObjects/NoShape.h"
#include "MantidGeometry/Instrument/RectangularDetector.h"
#include "MantidGeometry/Instrument/ReferenceFrame.h"
#include "MantidGeometry/Objects/InstrumentRayTracer.h"
#include "MantidGeometry/Surfaces/LineIntersectVisit.h"
#include "MantidKernel/ConfigService.h"
#include "MantidKernel/Exception.h"
#include "MantidKernel/Strings.h"

#include "boost/make_shared.hpp"

#include <algorithm>
#include <cctype>
#include <string>
#include <utility>

using namespace Mantid;
using namespace Mantid::Kernel;
using namespace Mantid::Geometry;

namespace Mantid {
namespace DataObjects {

//----------------------------------------------------------------------------------------------
/** Default constructor */
LeanPeak::LeanPeak()
    : 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_absorptionWeightedPathLength(0),
      m_GoniometerMatrix(3, 3, true), m_InverseGoniometerMatrix(3, 3, true),
      m_runNumber(0), m_monitorCount(0), m_row(-1), m_col(-1), m_peakNumber(0),
      m_intHKL(V3D(0, 0, 0)), m_intMNP(V3D(0, 0, 0)),
      m_peakShape(std::make_shared<NoShape>()) {
  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.
 */
LeanPeak::LeanPeak(const Geometry::Instrument_const_sptr &m_inst,
                   const Mantid::Kernel::V3D &QLabFrame,
                   boost::optional<double> detectorDistance)
    : m_H(0), m_K(0), m_L(0), m_intensity(0), m_sigmaIntensity(0),
      m_binCount(0), m_absorptionWeightedPathLength(0),
      m_GoniometerMatrix(3, 3, true), m_InverseGoniometerMatrix(3, 3, true),
      m_runNumber(0), m_monitorCount(0), m_peakNumber(0),
      m_intHKL(V3D(0, 0, 0)), m_intMNP(V3D(0, 0, 0)),
      m_peakShape(std::make_shared<NoShape>()) {
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
  this->setInstrument(m_inst);
  this->setQLabFrame(QLabFrame, std::move(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
 * @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.
 */
LeanPeak::LeanPeak(const Geometry::Instrument_const_sptr &m_inst,
                   const Mantid::Kernel::V3D &QSampleFrame,
                   const Mantid::Kernel::Matrix<double> &goniometer,
                   boost::optional<double> detectorDistance)
    : m_H(0), m_K(0), m_L(0), m_intensity(0), m_sigmaIntensity(0),
      m_binCount(0), m_absorptionWeightedPathLength(0),
      m_GoniometerMatrix(goniometer), m_InverseGoniometerMatrix(goniometer),
      m_runNumber(0), m_monitorCount(0), m_peakNumber(0),
      m_intHKL(V3D(0, 0, 0)), m_intMNP(V3D(0, 0, 0)),
      m_peakShape(std::make_shared<NoShape>()) {
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
  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, std::move(detectorDistance));
}

//----------------------------------------------------------------------------------------------
/** 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
 */
LeanPeak::LeanPeak(const Geometry::Instrument_const_sptr &m_inst,
                   int m_detectorID, double m_Wavelength)
    : m_H(0), m_K(0), m_L(0), m_intensity(0), m_sigmaIntensity(0),
      m_binCount(0), m_absorptionWeightedPathLength(0),
      m_GoniometerMatrix(3, 3, true), m_InverseGoniometerMatrix(3, 3, true),
      m_runNumber(0), m_monitorCount(0), m_peakNumber(0),
      m_intHKL(V3D(0, 0, 0)), m_intMNP(V3D(0, 0, 0)),
      m_peakShape(std::make_shared<NoShape>()) {
  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
 */
LeanPeak::LeanPeak(const Geometry::Instrument_const_sptr &m_inst,
                   int m_detectorID, double m_Wavelength,
                   const Mantid::Kernel::V3D &HKL)
    : m_H(HKL[0]), m_K(HKL[1]), m_L(HKL[2]), m_intensity(0),
      m_sigmaIntensity(0), m_binCount(0), m_absorptionWeightedPathLength(0),
      m_GoniometerMatrix(3, 3, true), m_InverseGoniometerMatrix(3, 3, true),
      m_runNumber(0), m_monitorCount(0), m_peakNumber(0),
      m_intHKL(V3D(0, 0, 0)), m_intMNP(V3D(0, 0, 0)),
      m_peakShape(std::make_shared<NoShape>()) {
  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
 * @param goniometer :: a 3x3 rotation matrix
 * @return
 */
LeanPeak::LeanPeak(const Geometry::Instrument_const_sptr &m_inst,
                   int m_detectorID, double m_Wavelength,
                   const Mantid::Kernel::V3D &HKL,
                   const Mantid::Kernel::Matrix<double> &goniometer)
    : m_H(HKL[0]), m_K(HKL[1]), m_L(HKL[2]), m_intensity(0),
      m_sigmaIntensity(0), m_binCount(0), m_absorptionWeightedPathLength(0),
      m_GoniometerMatrix(goniometer), m_InverseGoniometerMatrix(goniometer),
      m_runNumber(0), m_monitorCount(0), m_peakNumber(0),
      m_intHKL(V3D(0, 0, 0)), m_intMNP(V3D(0, 0, 0)),
      m_peakShape(std::make_shared<NoShape>()) {
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
  if (fabs(m_InverseGoniometerMatrix.Invert()) < 1e-8)
    throw std::invalid_argument(
        "Peak::ctor(): Goniometer matrix must non-singular.");
  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 scattering :: fake detector position using scattering angle
 * @param m_Wavelength :: incident neutron wavelength, in Angstroms
 * @return
 */
LeanPeak::LeanPeak(const Geometry::Instrument_const_sptr &m_inst,
                   double scattering, double m_Wavelength)
    : m_H(0), m_K(0), m_L(0), m_intensity(0), m_sigmaIntensity(0),
      m_binCount(0), m_absorptionWeightedPathLength(0),
      m_GoniometerMatrix(3, 3, true), m_InverseGoniometerMatrix(3, 3, true),
      m_runNumber(0), m_monitorCount(0), m_row(-1), m_col(-1),
      m_intHKL(V3D(0, 0, 0)), m_intMNP(V3D(0, 0, 0)),
      m_peakShape(std::make_shared<NoShape>()) {
  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
 */
LeanPeak::LeanPeak(const LeanPeak &other)
    : 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),
      m_absorptionWeightedPathLength(other.m_absorptionWeightedPathLength),
      m_GoniometerMatrix(other.m_GoniometerMatrix),
      m_InverseGoniometerMatrix(other.m_InverseGoniometerMatrix),
      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_peakNumber(other.m_peakNumber), m_intHKL(other.m_intHKL),
      m_intMNP(other.m_intMNP), m_detIDs(other.m_detIDs),
      m_peakShape(other.m_peakShape->clone()), convention(other.convention) {}

//----------------------------------------------------------------------------------------------
/** Constructor making a LeanPeak from IPeak interface
 *
 * @param ipeak :: const reference to an IPeak object
 * @return
 */
LeanPeak::LeanPeak(const Geometry::IPeak &ipeak)
    : IPeak(ipeak), m_detectorID(ipeak.getDetectorID()), m_H(ipeak.getH()),
      m_K(ipeak.getK()), m_L(ipeak.getL()), m_intensity(ipeak.getIntensity()),
      m_sigmaIntensity(ipeak.getSigmaIntensity()),
      m_binCount(ipeak.getBinCount()),
      m_initialEnergy(ipeak.getInitialEnergy()),
      m_finalEnergy(ipeak.getFinalEnergy()),
      m_absorptionWeightedPathLength(ipeak.getAbsorptionWeightedPathLength()),
      m_GoniometerMatrix(ipeak.getGoniometerMatrix()),
      m_InverseGoniometerMatrix(ipeak.getGoniometerMatrix()),
      m_runNumber(ipeak.getRunNumber()),
      m_monitorCount(ipeak.getMonitorCount()), m_row(ipeak.getRow()),
      m_col(ipeak.getCol()), m_peakNumber(ipeak.getPeakNumber()),
      m_intHKL(ipeak.getIntHKL()), m_intMNP(ipeak.getIntMNP()),
      m_peakShape(std::make_shared<NoShape>()) {
  convention = Kernel::ConfigService::Instance().getString("Q.convention");
  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 auto *peak = dynamic_cast<const LeanPeak *>(&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 LeanPeak::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;
}

//----------------------------------------------------------------------------------------------
/** 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 LeanPeak::setDetectorID(int id) {
  if (!m_inst)
    throw std::runtime_error(
        "LeanPeak::setInstrument(): No instrument is set!");
  this->m_det = m_inst->getDetector(id);
  if (!m_det)
    throw std::runtime_error(
        "LeanPeak::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.
  m_row = -1;
  m_col = -1;

  // 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.
  m_row = Strings::endsWithInt(m_det->getName());

  if (!parent)
    return;
  m_bankName = parent->getName();

  // Find the COLUMN by looking at the string name of the parent. E.g. "tube003"
  // gives column 3.
  m_col = Strings::endsWithInt(parent->getName());

  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 =
      std::dynamic_pointer_cast<const Instrument>(parent);
  if (instrument)
    return;
  // Use the grand-parent whenever possible
  m_bankName = parent->getName();
  // For CORELLI, one level above sixteenpack
  if (m_bankName == "sixteenpack") {
    parent = parent->getParent();
    m_bankName = parent->getName();
  }

  // Special for rectangular detectors: find the row and column.
  RectangularDetector_const_sptr retDet =
      std::dynamic_pointer_cast<const RectangularDetector>(parent);
  if (!retDet)
    return;
  std::pair<int, int> xy = retDet->getXYForDetectorID(m_detectorID);
  m_row = xy.second;
  m_col = xy.first;
}

//----------------------------------------------------------------------------------------------
/** Get the ID of the detector at the center of the peak  */
int LeanPeak::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 LeanPeak::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 LeanPeak::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> &LeanPeak::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 LeanPeak::setInstrument(const Geometry::Instrument_const_sptr &inst) {
  m_inst = inst;
  if (!inst)
    throw std::runtime_error(
        "LeanPeak::setInstrument(): No instrument is set!");

  // Cache some positions
  const Geometry::IComponent_const_sptr sourceObj = m_inst->getSource();
  if (sourceObj == nullptr)
    throw Exception::InstrumentDefinitionError(
        "LeanPeak::setInstrument(): Failed "
        "to get source component from "
        "instrument");
  const Geometry::IComponent_const_sptr sampleObj = m_inst->getSample();
  if (sampleObj == nullptr)
    throw Exception::InstrumentDefinitionError(
        "LeanPeak::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 LeanPeak::getDetector() const { return m_det; }

/** Return a shared ptr to the instrument for this peak. */
Geometry::Instrument_const_sptr LeanPeak::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 LeanPeak::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;
}

// -------------------------------------------------------------------------------------
/** Calculate the time of flight (in microseconds) of the neutrons for this
 * peak,
 * using the geometry of the detector  */
double LeanPeak::getTOF() const {
  // First, get the neutron traveling distances
  double L1 = this->getL1();
  double L2 = this->getL2();
  // Energy in J of the neutron
  double Ei = PhysicalConstants::meV * m_initialEnergy;
  double Ef = PhysicalConstants::meV * m_finalEnergy;
  // 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 LeanPeak::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 LeanPeak::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 LeanPeak::getDSpacing() const {
  // The detector is at 2 theta scattering angle
  V3D beamDir = samplePos - sourcePos;
  V3D detDir = detPos - samplePos;

  double two_theta;
  try {
    two_theta = detDir.angle(beamDir);
  } catch (std::runtime_error &) {
    two_theta = 0.;
  }

  // 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) /
         sqrt(m_initialEnergy + m_finalEnergy -
              2.0 * sqrt(m_initialEnergy * m_finalEnergy) * cos(two_theta));
}

//----------------------------------------------------------------------------------------------
/** 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 LeanPeak::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
  double ei = PhysicalConstants::meV * m_initialEnergy;
  // 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 LeanPeak::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.
 *        Used to give a valid TOF. You do NOT need to explicitly set this.
 */
void LeanPeak::setQSampleFrame(const Mantid::Kernel::V3D &QSampleFrame,
                               boost::optional<double> detectorDistance) {
  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 qLab :: 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).
 * @param detectorDistance :: distance between the sample and the detector. If
 *this is provided. Then we do not
 * ray trace to find the intersecing detector.
 */
void LeanPeak::setQLabFrame(const Mantid::Kernel::V3D &qLab,
                            boost::optional<double> detectorDistance) {
  if (!this->m_inst) {
    throw std::invalid_argument("Setting QLab without an instrument would lead "
                                "to an inconsistent state for the LeanPeak");
  }
  // Clear out the detector = we can't know them
  m_detectorID = -1;
  detPos = V3D();
  m_det = IDetector_sptr();
  m_row = -1;
  m_col = -1;
  m_bankName = "None";

  /* The q-vector direction of the peak is = goniometer * ub * hkl_vector
   * The incident neutron wavevector is along the beam direction, ki = 1/wl
   * (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)
   */
  const double norm_q = qLab.norm();
  if (norm_q == 0.0)
    throw std::invalid_argument("LeanPeak::setQLabFrame(): Q cannot be 0,0,0.");

  std::shared_ptr<const ReferenceFrame> refFrame =
      this->m_inst->getReferenceFrame();
  const V3D refBeamDir = refFrame->vecPointingAlongBeam();
  // Default for ki-kf has -q
  const double qSign = (convention != "Crystallography") ? 1.0 : -1.0;
  const double qBeam = qLab.scalar_prod(refBeamDir) * qSign;

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

  const double one_over_wl = (norm_q * norm_q) / (2.0 * qBeam);
  const double wl = (2.0 * M_PI) / one_over_wl;
  if (wl < 0.0) {
    std::ostringstream mess;
    mess << "LeanPeak::setQLabFrame(): Wavelength found was negative (" << wl
         << " Ang)! This Q is not physical.";
    throw std::invalid_argument(mess.str());
  }

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

  V3D detectorDir = -qLab * qSign;
  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 : " +
                  qLab.toString());

      detPos = getVirtualDetectorPosition(detectorDir);
    }
  }
}

V3D LeanPeak::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
  }
  const auto object = std::dynamic_pointer_cast<const ObjComponent>(component);
  const auto distance =
      object->shape()->distance(Geometry::Track(samplePos, detectorDir));
  return detectorDir * distance;
}

/** 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 LeanPeak::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 LeanPeak::findDetector(const InstrumentRayTracer &tracer) {
  // Scattered beam direction
  const V3D beam = normalize(detPos - samplePos);

  return findDetector(beam, tracer);
}

/**
 * @brief LeanPeak::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 LeanPeak::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()) {
      const auto 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;
        gapDir[i] = gap;
        V3D beam1 = beam + gapDir;
        tracer.traceFromSample(normalize(beam1));
        IDetector_const_sptr det1 = tracer.getDetectorResult();
        V3D beam2 = beam - gapDir;
        tracer.traceFromSample(normalize(beam2));
        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;
        }
      }
    }
  }
  return found;
}

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

/** Set the run number that measured this peak
 * @param m_runNumber :: the run number   */
void LeanPeak::setRunNumber(int m_runNumber) {
  this->m_runNumber = m_runNumber;
}

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

/** Set the monitor count for this peak
 * @param m_monitorCount :: the monitor count */
void LeanPeak::setMonitorCount(double m_monitorCount) {
  this->m_monitorCount = m_monitorCount;
}

//----------------------------------------------------------------------------------------------
/** Get the final neutron energy in meV */
double LeanPeak::getFinalEnergy() const { return m_finalEnergy; }

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

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

//----------------------------------------------------------------------------------------------
/** Get the H index of the peak */
double LeanPeak::getH() const { return m_H; }

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

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

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

/** Return True if the peak has been indexed */
bool LeanPeak::isIndexed() const {
  if (m_H == 0. && m_K == 0. && m_L == 0.)
    return false;
  return true;
}

/** Return the int HKL vector */
Mantid::Kernel::V3D LeanPeak::getIntHKL() const { return m_intHKL; }

/** Return the int MNP vector */
V3D LeanPeak::getIntMNP() const { return m_intMNP; }

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

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

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

/** Set the BankName of this peak
 * @param m_bankName :: index to set   */
void LeanPeak::setBankName(std::string m_bankName) {
  this->m_bankName = std::move(m_bankName);
}

/** Set all three H,K,L indices of the peak */
void LeanPeak::setHKL(double H, double K, double L) {
  m_H = H;
  m_K = K;
  m_L = L;
}

/** Set all HKL
 *
 * @param HKL :: vector with x,y,z -> h,k,l
 */
void LeanPeak::setHKL(const Mantid::Kernel::V3D &HKL) {
  m_H = HKL.X();
  m_K = HKL.Y();
  m_L = HKL.Z();
}

/** Set int HKL
 *
 * @param HKL :: vector with integer x,y,z -> h,k,l
 */
void LeanPeak::setIntHKL(const V3D &HKL) {
  m_intHKL = V3D(std::round(HKL[0]), std::round(HKL[1]), std::round(HKL[2]));
}

/** Sets the modulated peak structure number
 * @param MNP :: modulated peak structure value
 */
void LeanPeak::setIntMNP(const V3D &MNP) {
  m_intMNP = V3D(std::round(MNP[0]), std::round(MNP[1]), std::round(MNP[2]));
}

/** Set sample position
 *
 * @ doubles x,y,z-> samplePos(x), samplePos(y), samplePos(z)
 */
void LeanPeak::setSamplePos(double samX, double samY, double samZ) {

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

/** Set sample position
 *
 * @param XYZ :: vector x,y,z-> samplePos(x), samplePos(y), samplePos(z)
 */
void LeanPeak::setSamplePos(const Mantid::Kernel::V3D &XYZ) {

  this->samplePos[0] = XYZ[0];
  this->samplePos[1] = XYZ[1];
  this->samplePos[2] = XYZ[2];
}
//----------------------------------------------------------------------------------------------
/** Return the # of counts in the bin at its peak*/
double LeanPeak::getBinCount() const { return m_binCount; }

/** Return the integrated peak intensity */
double LeanPeak::getIntensity() const { return m_intensity; }

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

/** Return the peak intensity divided by the error in the intensity */
double LeanPeak::getIntensityOverSigma() const {
  const auto result = m_intensity / m_sigmaIntensity;
  return (std::isinf(result)) ? 0.0 : result;
}

/** Set the integrated peak intensity
 * @param m_intensity :: intensity value   */
void LeanPeak::setIntensity(double m_intensity) {
  this->m_intensity = m_intensity;
}

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

/** Set the error on the integrated peak intensity
 * @param m_sigmaIntensity :: intensity error value   */
void LeanPeak::setSigmaIntensity(double m_sigmaIntensity) {
  this->m_sigmaIntensity = m_sigmaIntensity;
}

/** Set the final energy
 * @param m_finalEnergy :: final energy in meV   */
void LeanPeak::setFinalEnergy(double m_finalEnergy) {
  this->m_finalEnergy = m_finalEnergy;
}

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

// -------------------------------------------------------------------------------------
/** Get the goniometer rotation matrix at which this peak was measured. */
Mantid::Kernel::Matrix<double> LeanPeak::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*/
void LeanPeak::setGoniometerMatrix(
    const Mantid::Kernel::Matrix<double> &goniometerMatrix) {
  if ((goniometerMatrix.numCols() != 3) || (goniometerMatrix.numRows() != 3))
    throw std::invalid_argument(
        "LeanPeak::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("LeanPeak::setGoniometerMatrix(): Goniometer "
                                "matrix must be non-singular.");
}

// -------------------------------------------------------------------------------------
/** 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.
 */
std::string LeanPeak::getBankName() const { return m_bankName; }

// -------------------------------------------------------------------------------------
/** For RectangularDetectors only, returns the row (y) of the pixel of the
 * detector.
 * Returns -1 if it could not find it. */
int LeanPeak::getRow() const { return m_row; }

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

// -------------------------------------------------------------------------------------
/**Returns the unique peak number
 * Returns -1 if it could not find it. */
int LeanPeak::getPeakNumber() const { return m_peakNumber; }

// -------------------------------------------------------------------------------------
/** For RectangularDetectors only, sets the row (y) of the pixel of the
 * detector.
 * @param m_row :: row value   */
void LeanPeak::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 LeanPeak::setCol(int m_col) { this->m_col = m_col; }

// -------------------------------------------------------------------------------------
/** Sets the unique peak number
 * @param m_peakNumber :: unique peak number value   */
void LeanPeak::setPeakNumber(int m_peakNumber) {
  this->m_peakNumber = m_peakNumber;
}

// -------------------------------------------------------------------------------------
/** Return the detector position vector */
Mantid::Kernel::V3D LeanPeak::getDetPos() const { return detPos; }

// -------------------------------------------------------------------------------------
/** Return the sample position vector */
Mantid::Kernel::V3D LeanPeak::getSamplePos() const { return samplePos; }

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

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

// -------------------------------------------------------------------------------------
/** Helper function for displaying/sorting peaks
 *
 * @param name :: name of the column in the table workspace. The matching is
 * case-insensitive.
 * @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 LeanPeak::getValueByColName(std::string name) const {
  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")