forked from npshub/mantid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Unit.cpp
1466 lines (1239 loc) · 51 KB
/
Unit.cpp
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 +
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include "MantidKernel/Unit.h"
#include "MantidKernel/Logger.h"
#include "MantidKernel/PhysicalConstants.h"
#include "MantidKernel/UnitFactory.h"
#include "MantidKernel/UnitLabelTypes.h"
#include <cfloat>
#include <limits>
#include <sstream>
namespace Mantid::Kernel {
namespace {
// static logger object
Logger g_log("Unit");
bool ParamPresent(const UnitParametersMap ¶ms, UnitParams param) { return params.find(param) != params.end(); }
bool ParamPresentAndSet(const UnitParametersMap *params, UnitParams param, double &var) {
auto it = params->find(param);
if (it != params->end()) {
var = it->second;
return true;
} else {
return false;
}
}
} // namespace
/**
* Default constructor
* Gives the unit an empty UnitLabel
*/
Unit::Unit() : initialized(false), l1(0), emode(0) {}
bool Unit::operator==(const Unit &u) const { return unitID() == u.unitID(); }
bool Unit::operator!=(const Unit &u) const { return !(*this == u); }
/** Is conversion by constant multiplication possible?
*
* Look to see if conversion from the unit upon which this method is called
*requires
* only multiplication by a constant and not detector information (i.e.
*distance & angle),
* in which case doing the conversion via time-of-flight is not necessary.
* @param destination :: The unit to which conversion is sought
* @param factor :: Returns the constant by which to multiply the input
*unit (if a conversion is found)
* @param power :: Returns the power to which to raise the unput unit (if
*a conversion is found)
* @return True if a 'quick conversion' exists, false otherwise
*/
bool Unit::quickConversion(const Unit &destination, double &factor, double &power) const {
// Just extract the unit's name and forward to other quickConversion method
return quickConversion(destination.unitID(), factor, power);
}
/** Is conversion by constant multiplication possible?
*
* Look to see if conversion from the unit upon which this method is called
*requires
* only multiplication by a constant and not detector information (i.e.
*distance & angle),
* in which case doing the conversion via time-of-flight is not necessary.
* @param destUnitName :: The class name of the unit to which conversion is
*sought
* @param factor :: Returns the constant by which to multiply the input
*unit (if a conversion is found)
* @param power :: Returns the power to which to raise the unput unit
*(if a conversion is found)
* @return True if a 'quick conversion' exists, false otherwise
*/
bool Unit::quickConversion(std::string destUnitName, double &factor, double &power) const {
// From the global map, try to get the map holding the conversions for this
// unit
ConversionsMap::const_iterator it = s_conversionFactors.find(unitID());
// Return false if there are no conversions entered for this unit
if (it == s_conversionFactors.end())
return false;
// See if there's a conversion listed for the requested destination unit
std::transform(destUnitName.begin(), destUnitName.end(), destUnitName.begin(), toupper);
auto iter = it->second.find(destUnitName);
// If not, return false
if (iter == it->second.end())
return false;
// Conversion found - set the conversion factors
factor = iter->second.first;
power = iter->second.second;
return true;
}
// Initialise the static map holding the 'quick conversions'
Unit::ConversionsMap Unit::s_conversionFactors = Unit::ConversionsMap();
//---------------------------------------------------------------------------------------
/** Add a 'quick conversion' from the unit class on which this method is called.
* @param to :: The destination Unit for this conversion (use name returned
* by the unit's unitID() method)
* @param factor :: The constant by which to multiply the input unit
* @param power :: The power to which to raise the input unit (defaults to 1)
*/
void Unit::addConversion(std::string to, const double &factor, const double &power) const {
std::transform(to.begin(), to.end(), to.begin(), toupper);
// Add the conversion to the map (does nothing if it's already there)
s_conversionFactors[unitID()][to] = std::make_pair(factor, power);
}
//---------------------------------------------------------------------------------------
/** Initialize the unit to perform conversion using singleToTof() and
*singleFromTof()
*
* @param _l1 :: The source-sample distance (in metres)
* @param _emode :: The energy mode (0=elastic, 1=direct geometry,
*2=indirect geometry)
* @param params :: Map containing optional parameters eg
* The sample-detector distance (in metres)
* The scattering angle (in radians)
* Fixed energy: EI (emode=1) or EF (emode=2)(in meV)
* Delta (not currently used)
*/
void Unit::initialize(const double &_l1, const int &_emode, const UnitParametersMap ¶ms) {
l1 = _l1;
validateUnitParams(_emode, params);
emode = _emode;
m_params = ¶ms;
initialized = true;
this->init();
}
void Unit::validateUnitParams(const int, const UnitParametersMap &) {}
//---------------------------------------------------------------------------------------
/** Perform the conversion to TOF on a vector of data
*/
void Unit::toTOF(std::vector<double> &xdata, std::vector<double> &ydata, const double &_l1, const int &_emode,
std::initializer_list<std::pair<const UnitParams, double>> params) {
UnitParametersMap paramsMap(params);
toTOF(xdata, ydata, _l1, _emode, paramsMap);
}
void Unit::toTOF(std::vector<double> &xdata, std::vector<double> &ydata, const double &_l1, const int &_emode,
const UnitParametersMap ¶ms) {
UNUSED_ARG(ydata);
this->initialize(_l1, _emode, params);
size_t numX = xdata.size();
for (size_t i = 0; i < numX; i++)
xdata[i] = this->singleToTOF(xdata[i]);
}
/** Convert a single value to TOF
@param xvalue
@param l1
@param emode
@param params (eg efixed or delta)
*/
double Unit::convertSingleToTOF(const double xvalue, const double &l1, const int &emode,
const UnitParametersMap ¶ms) {
this->initialize(l1, emode, params);
return this->singleToTOF(xvalue);
}
//---------------------------------------------------------------------------------------
/** Perform the conversion to TOF on a vector of data
*/
void Unit::fromTOF(std::vector<double> &xdata, std::vector<double> &ydata, const double &_l1, const int &_emode,
std::initializer_list<std::pair<const UnitParams, double>> params) {
UnitParametersMap paramsMap(params);
fromTOF(xdata, ydata, _l1, _emode, paramsMap);
}
void Unit::fromTOF(std::vector<double> &xdata, std::vector<double> &ydata, const double &_l1, const int &_emode,
const UnitParametersMap ¶ms) {
UNUSED_ARG(ydata);
this->initialize(_l1, _emode, params);
size_t numX = xdata.size();
for (size_t i = 0; i < numX; i++)
xdata[i] = this->singleFromTOF(xdata[i]);
}
/** Convert a single value from TOF
@param xvalue
@param l1
@param emode
@param params (eg efixed or delta)
*/
double Unit::convertSingleFromTOF(const double xvalue, const double &l1, const int &emode,
const UnitParametersMap ¶ms) {
this->initialize(l1, emode, params);
return this->singleFromTOF(xvalue);
}
std::pair<double, double> Unit::conversionRange() const {
double u1 = this->singleFromTOF(this->conversionTOFMin());
double u2 = this->singleFromTOF(this->conversionTOFMax());
//
return std::pair<double, double>(std::min(u1, u2), std::max(u1, u2));
}
namespace Units {
/* =============================================================================
* EMPTY
* =============================================================================
*/
DECLARE_UNIT(Empty)
const UnitLabel Empty::label() const { return Symbol::EmptyLabel; }
void Empty::init() {}
double Empty::singleToTOF(const double x) const {
UNUSED_ARG(x);
throw Kernel::Exception::NotImplementedError("Cannot convert unit " + this->unitID() + " to time of flight");
}
double Empty::singleFromTOF(const double tof) const {
UNUSED_ARG(tof);
throw Kernel::Exception::NotImplementedError("Cannot convert to unit " + this->unitID() + " from time of flight");
}
Unit *Empty::clone() const { return new Empty(*this); }
/**
* @return NaN as Label can not be obtained from TOF in any reasonable manner
*/
double Empty::conversionTOFMin() const { return std::numeric_limits<double>::quiet_NaN(); }
/**
* @return NaN as Label can not be obtained from TOF in any reasonable manner
*/
double Empty::conversionTOFMax() const { return std::numeric_limits<double>::quiet_NaN(); }
/* =============================================================================
* LABEL
* =============================================================================
*/
DECLARE_UNIT(Label)
const UnitLabel Label::label() const { return m_label; }
/// Constructor
Label::Label() : Empty(), m_caption("Quantity"), m_label(Symbol::EmptyLabel) {}
Label::Label(const std::string &caption, const std::string &label) : Empty(), m_caption(), m_label(Symbol::EmptyLabel) {
setLabel(caption, label);
}
/**
* Set a caption and a label
*/
void Label::setLabel(const std::string &cpt, const UnitLabel &lbl) {
m_caption = cpt;
m_label = lbl;
}
Unit *Label::clone() const { return new Label(*this); }
/* =============================================================================
* TIME OF FLIGHT
* =============================================================================
*/
DECLARE_UNIT(TOF)
const UnitLabel TOF::label() const { return Symbol::Microsecond; }
TOF::TOF() : Unit() {}
void TOF::init() {}
double TOF::singleToTOF(const double x) const {
// Nothing to do
return x;
}
double TOF::singleFromTOF(const double tof) const {
// Nothing to do
return tof;
}
Unit *TOF::clone() const { return new TOF(*this); }
double TOF::conversionTOFMin() const { return -DBL_MAX; }
///@return DBL_MAX as ToF convetanble to TOF for in any time range
double TOF::conversionTOFMax() const { return DBL_MAX; }
// ============================================================================================
/* WAVELENGTH
* ===================================================================================================
*
* This class makes use of the de Broglie relationship: lambda = h/p = h/mv,
*where v is (l1+l2)/tof.
*/
DECLARE_UNIT(Wavelength)
Wavelength::Wavelength()
: Unit(), efixed(0.), sfpTo(DBL_MIN), factorTo(DBL_MIN), sfpFrom(DBL_MIN), factorFrom(DBL_MIN), do_sfpFrom(false) {
const double AngstromsSquared = 1e20;
const double factor = (AngstromsSquared * PhysicalConstants::h * PhysicalConstants::h) /
(2.0 * PhysicalConstants::NeutronMass * PhysicalConstants::meV);
addConversion("Energy", factor, -2.0);
addConversion("Energy_inWavenumber", factor * PhysicalConstants::meVtoWavenumber, -2.0);
addConversion("Momentum", 2 * M_PI, -1.0);
}
const UnitLabel Wavelength::label() const { return Symbol::Angstrom; }
void Wavelength::validateUnitParams(const int emode, const UnitParametersMap ¶ms) {
if (!ParamPresent(params, UnitParams::l2)) {
throw std::runtime_error("An l2 value must be supplied in the extra "
"parameters when initialising " +
this->unitID() + " for conversion via TOF");
}
if ((emode != 0) && (!ParamPresent(params, UnitParams::efixed))) {
throw std::runtime_error("An efixed value must be supplied in the extra "
"parameters when initialising " +
this->unitID() + " for conversion via TOF");
}
}
void Wavelength::init() {
// ------------ Factors to convert TO TOF ---------------------
double l2 = 0.0;
double ltot = 0.0;
double TOFisinMicroseconds = 1e6;
double toAngstroms = 1e10;
sfpTo = 0.0;
ParamPresentAndSet(m_params, UnitParams::efixed, efixed);
ParamPresentAndSet(m_params, UnitParams::l2, l2);
if (emode == 1) {
ltot = l2;
sfpTo = (sqrt(PhysicalConstants::NeutronMass / (2.0 * PhysicalConstants::meV)) * TOFisinMicroseconds * l1) /
sqrt(efixed);
} else if (emode == 2) {
ltot = l1;
sfpTo = (sqrt(PhysicalConstants::NeutronMass / (2.0 * PhysicalConstants::meV)) * TOFisinMicroseconds * l2) /
sqrt(efixed);
} else {
ltot = l1 + l2;
}
factorTo = (PhysicalConstants::NeutronMass * (ltot)) / PhysicalConstants::h;
// Now adjustments for the scale of units used
factorTo *= TOFisinMicroseconds / toAngstroms;
// ------------ Factors to convert FROM TOF ---------------------
// Now apply the factor to the input data vector
do_sfpFrom = false;
if (efixed != DBL_MIN) {
if (emode == 1) // Direct
{
sfpFrom = (sqrt(PhysicalConstants::NeutronMass / (2.0 * PhysicalConstants::meV)) * TOFisinMicroseconds * l1) /
sqrt(efixed);
do_sfpFrom = true;
} else if (emode == 2) // Indirect
{
sfpFrom = (sqrt(PhysicalConstants::NeutronMass / (2.0 * PhysicalConstants::meV)) * TOFisinMicroseconds * l2) /
sqrt(efixed);
do_sfpFrom = true;
}
}
// Protect against divide by zero
if (ltot == 0.0)
ltot = DBL_MIN;
// First the crux of the conversion
factorFrom = PhysicalConstants::h / (PhysicalConstants::NeutronMass * (ltot));
// Now adjustments for the scale of units used
factorFrom *= toAngstroms / TOFisinMicroseconds;
}
double Wavelength::singleToTOF(const double x) const {
double tof = x * factorTo;
// If Direct or Indirect we want to correct TOF values..
if (emode == 1 || emode == 2)
tof += sfpTo;
return tof;
}
double Wavelength::singleFromTOF(const double tof) const {
double x = tof;
if (do_sfpFrom)
x -= sfpFrom;
x *= factorFrom;
return x;
}
///@return Minimal time of flight, which can be reversively converted into
/// wavelength
double Wavelength::conversionTOFMin() const {
double min_tof(0);
if (emode == 1 || emode == 2)
min_tof = sfpTo;
return min_tof;
}
///@return Maximal time of flight, which can be reversively converted into
/// wavelength
double Wavelength::conversionTOFMax() const {
double max_tof;
if (factorTo > 1) {
max_tof = (DBL_MAX - sfpTo) / factorTo;
} else {
max_tof = DBL_MAX - sfpTo / factorTo;
}
return max_tof;
}
Unit *Wavelength::clone() const { return new Wavelength(*this); }
// ============================================================================================
/* ENERGY
* ===============================================================================================
*
* Conversion uses E = 1/2 mv^2, where v is (l1+l2)/tof.
*/
DECLARE_UNIT(Energy)
const UnitLabel Energy::label() const { return Symbol::MilliElectronVolts; }
/// Constructor
Energy::Energy() : Unit(), factorTo(DBL_MIN), factorFrom(DBL_MIN) {
addConversion("Energy_inWavenumber", PhysicalConstants::meVtoWavenumber);
const double toAngstroms = 1e10;
const double factor =
toAngstroms * PhysicalConstants::h / sqrt(2.0 * PhysicalConstants::NeutronMass * PhysicalConstants::meV);
addConversion("Wavelength", factor, -0.5);
addConversion("Momentum", 2 * M_PI / factor, 0.5);
}
void Energy::validateUnitParams(const int, const UnitParametersMap ¶ms) {
if (!ParamPresent(params, UnitParams::l2)) {
throw std::runtime_error("An l2 value must be supplied in the extra "
"parameters when initialising " +
this->unitID() + " for conversion via TOF");
}
}
void Energy::init() {
double l2 = 0.0;
ParamPresentAndSet(m_params, UnitParams::l2, l2);
{
const double TOFinMicroseconds = 1e6;
factorTo = sqrt(PhysicalConstants::NeutronMass / (2.0 * PhysicalConstants::meV)) * (l1 + l2) * TOFinMicroseconds;
}
{
const double TOFisinMicroseconds = 1e-12; // The input tof number gets squared so this is (10E-6)^2
const double ltot = l1 + l2;
factorFrom =
((PhysicalConstants::NeutronMass / 2.0) * (ltot * ltot)) / (PhysicalConstants::meV * TOFisinMicroseconds);
}
}
double Energy::singleToTOF(const double x) const {
double temp = x;
if (temp == 0.0)
temp = DBL_MIN; // Protect against divide by zero
return factorTo / sqrt(temp);
}
///@return Minimal time of flight which can be reversibly converted into energy
double Energy::conversionTOFMin() const { return factorTo / sqrt(DBL_MAX); }
double Energy::conversionTOFMax() const { return sqrt(DBL_MAX); }
double Energy::singleFromTOF(const double tof) const {
double temp = tof;
if (temp == 0.0)
temp = DBL_MIN; // Protect against divide by zero
return factorFrom / (temp * temp);
}
Unit *Energy::clone() const { return new Energy(*this); }
// ============================================================================================
/* ENERGY IN UNITS OF WAVENUMBER
* ============================================================================================
*
* Conversion uses E = 1/2 mv^2, where v is (l1+l2)/tof.
*/
DECLARE_UNIT(Energy_inWavenumber)
const UnitLabel Energy_inWavenumber::label() const { return Symbol::InverseCM; }
/// Constructor
Energy_inWavenumber::Energy_inWavenumber() : Unit(), factorTo(DBL_MIN), factorFrom(DBL_MIN) {
addConversion("Energy", 1.0 / PhysicalConstants::meVtoWavenumber);
const double toAngstroms = 1e10;
const double factor =
toAngstroms * PhysicalConstants::h /
sqrt(2.0 * PhysicalConstants::NeutronMass * PhysicalConstants::meV / PhysicalConstants::meVtoWavenumber);
addConversion("Wavelength", factor, -0.5);
addConversion("Momentum", 2 * M_PI / factor, 0.5);
}
void Energy_inWavenumber::validateUnitParams(const int, const UnitParametersMap ¶ms) {
if (!ParamPresent(params, UnitParams::l2)) {
throw std::runtime_error("An l2 value must be supplied in the extra "
"parameters when initialising " +
this->unitID() + " for conversion via TOF");
}
}
void Energy_inWavenumber::init() {
double l2 = 0.0;
ParamPresentAndSet(m_params, UnitParams::l2, l2);
{
const double TOFinMicroseconds = 1e6;
factorTo =
sqrt(PhysicalConstants::NeutronMass * PhysicalConstants::meVtoWavenumber / (2.0 * PhysicalConstants::meV)) *
(l1 + l2) * TOFinMicroseconds;
}
{
const double TOFisinMicroseconds = 1e-12; // The input tof number gets squared so this is (10E-6)^2
const double ltot = l1 + l2;
factorFrom = ((PhysicalConstants::NeutronMass / 2.0) * (ltot * ltot) * PhysicalConstants::meVtoWavenumber) /
(PhysicalConstants::meV * TOFisinMicroseconds);
}
}
double Energy_inWavenumber::singleToTOF(const double x) const {
double temp = x;
if (temp <= DBL_MIN)
temp = DBL_MIN; // Protect against divide by zero and define conversion range
return factorTo / sqrt(temp);
}
///@return Minimal time which can be reversibly converted into energy in
/// wavenumner units
double Energy_inWavenumber::conversionTOFMin() const { return factorTo / sqrt(std::numeric_limits<double>::max()); }
double Energy_inWavenumber::conversionTOFMax() const { return factorTo / sqrt(std::numeric_limits<double>::max()); }
double Energy_inWavenumber::singleFromTOF(const double tof) const {
double temp = tof;
if (temp == 0.0)
temp = DBL_MIN; // Protect against divide by zero
return factorFrom / (temp * temp);
}
Unit *Energy_inWavenumber::clone() const { return new Energy_inWavenumber(*this); }
// ==================================================================================================
/* D-SPACING
* ==================================================================================================
*
* Conversion uses Bragg's Law: 2d sin(theta) = n * lambda
*/
const double CONSTANT = (PhysicalConstants::h * 1e10) / (2.0 * PhysicalConstants::NeutronMass * 1e6);
/**
* Calculate and return conversion factor from tof to d-spacing.
* @param l1
* @param l2
* @param twoTheta scattering angle
* @param offset
* @return
*/
double tofToDSpacingFactor(const double l1, const double l2, const double twoTheta, const double offset) {
if (offset <= -1.) // not physically possible, means result is negative d-spacing
{
std::stringstream msg;
msg << "Encountered offset of " << offset << " which converts data to negative d-spacing\n";
throw std::logic_error(msg.str());
}
auto sinTheta = std::sin(twoTheta / 2);
const double numerator = (1.0 + offset);
sinTheta *= (l1 + l2);
return (numerator * CONSTANT) / sinTheta;
}
DECLARE_UNIT(dSpacing)
dSpacing::dSpacing() : Unit(), toDSpacingError(""), difa(0), difc(DBL_MIN), tzero(0) {
const double factor = 2.0 * M_PI;
addConversion("MomentumTransfer", factor, -1.0);
addConversion("QSquared", (factor * factor), -2.0);
}
const UnitLabel dSpacing::label() const { return Symbol::Angstrom; }
Unit *dSpacing::clone() const { return new dSpacing(*this); }
void dSpacing::validateUnitParams(const int, const UnitParametersMap ¶ms) {
double difc = 0.;
if (ParamPresentAndSet(¶ms, UnitParams::difc, difc)) {
// check validations only applicable to fromTOF
toDSpacingError = "";
double difa = 0.;
ParamPresentAndSet(¶ms, UnitParams::difa, difa);
if ((difa == 0) && (difc == 0)) {
toDSpacingError = "Cannot convert to d spacing with DIFA=0 and DIFC=0";
};
// singleFromTOF currently assuming difc not negative
if (difc < 0.) {
toDSpacingError = "A positive difc value must be supplied in the extra parameters when "
"initialising " +
this->unitID() + " for conversion via TOF";
}
} else {
if (!ParamPresent(params, UnitParams::twoTheta) || (!ParamPresent(params, UnitParams::l2))) {
throw std::runtime_error("A difc value or L2/two theta must be supplied "
"in the extra parameters when initialising " +
this->unitID() + " for conversion via TOF");
}
}
}
void dSpacing::init() {
// First the crux of the conversion
difa = 0.;
difc = 0.;
tzero = 0.;
ParamPresentAndSet(m_params, UnitParams::difa, difa);
ParamPresentAndSet(m_params, UnitParams::tzero, tzero);
if (!ParamPresentAndSet(m_params, UnitParams::difc, difc)) {
// also support inputs as L2, two theta
double l2;
if (ParamPresentAndSet(m_params, UnitParams::l2, l2)) {
double twoTheta;
if (ParamPresentAndSet(m_params, UnitParams::twoTheta, twoTheta)) {
if (difa != 0.) {
g_log.warning("Supplied difa ignored");
difa = 0.;
}
difc = 1. / tofToDSpacingFactor(l1, l2, twoTheta, 0.);
if (tzero != 0.) {
g_log.warning("Supplied tzero ignored");
tzero = 0.;
}
}
}
}
}
double dSpacing::singleToTOF(const double x) const {
if (!isInitialized())
throw std::runtime_error("dSpacingBase::singleToTOF called before object "
"has been initialized.");
if (difa == 0.)
return difc * x + tzero;
else
return difa * x * x + difc * x + tzero;
}
/**
* DIFA * d^2 + DIFC * d + T0 - TOF = 0
*
* Use the citardauq formula to solve quadratic in order to minimise loss of precision. citardauq (quadratic spelled
* backwards) is an alternate formulation of the quadratic formula. DIFC and sqrt term are often similar and the
* "classic" quadratic formula involves calculating their difference in the numerator
*
* 2*(T0 - TOF) (T0 - TOF)
* d = ------------------------------------------- = ---------------------------------------------------
* -DIFC -+ SQRT(DIFC^2 - 4*DIFA*(T0 - TOF)) 0.5 * DIFC (-1 -+ SQRT(1 - 4*DIFA*(T0 - TOF)/DIFC^2)
*
* the variables in this formulation are the same as the quadratic formula
* a = difa square term
* b = DIFC linear term - assumed to be positive
* c = T0 - TOF constant term
*/
double dSpacing::singleFromTOF(const double tof) const {
// dealing with various edge cases
if (!isInitialized())
throw std::runtime_error("dSpacingBase::singleFromTOF called before object "
"has been initialized.");
if (!toDSpacingError.empty())
throw std::runtime_error(toDSpacingError);
// this is with the opposite sign from the equation above
// as it reduces number of individual flops
const double negativeConstantTerm = tof - tzero;
// don't need to solve a quadratic when difa==0
// this allows negative d-spacing to be returned
// which was the behavior before v6.2 was released
if (difa == 0.)
return negativeConstantTerm / difc;
// non-physical result
if (tzero > tof) {
if (difa > 0.) {
throw std::runtime_error("Cannot convert to d spacing because tzero > time-of-flight and difa is positive. "
"Quadratic doesn't have a positive root");
}
}
// citardauq formula hides non-zero root if tof==tzero
// wich means that the constantTerm == 0
if (tof == tzero) {
if (difa < 0.)
return -difc / difa;
else
return 0.;
}
// general citarqauq equation
const double sqrtTerm = 1 + 4 * difa * negativeConstantTerm / (difc * difc);
if (sqrtTerm < 0.) {
throw std::runtime_error("Cannot convert to d spacing. Quadratic doesn't have real roots");
}
// pick smallest positive root. Since difc is positive it just depends on sign of constantTerm
// Note - constantTerm is generally negative
if (negativeConstantTerm < 0)
// single positive root
return negativeConstantTerm / (0.5 * difc * (1 - sqrt(sqrtTerm)));
else
// two positive roots. pick most negative denominator to get smallest root
return negativeConstantTerm / (0.5 * difc * (1 + sqrt(sqrtTerm)));
}
double dSpacing::conversionTOFMin() const {
// quadratic only has a min if difa is positive
if (difa > 0) {
// min of the quadratic is at d=-difc/(2*difa)
return std::max(0., tzero - difc * difc / (4 * difa));
} else {
// no min so just pick value closest to zero that works
double TOFmin = singleToTOF(0.);
if (TOFmin < std::numeric_limits<double>::min()) {
TOFmin = 0.;
}
return TOFmin;
}
}
double dSpacing::conversionTOFMax() const {
// quadratic only has a max if difa is negative
if (difa < 0) {
return std::min(DBL_MAX, tzero - difc * difc / (4 * difa));
} else {
// no max so just pick value closest to DBL_MAX that works
double TOFmax = singleToTOF(DBL_MAX);
if (std::isinf(TOFmax)) {
TOFmax = DBL_MAX;
}
return TOFmax;
}
}
double dSpacing::calcTofMin(const double difc, const double difa, const double tzero, const double tofmin) {
Kernel::UnitParametersMap params{
{Kernel::UnitParams::difa, difa}, {Kernel::UnitParams::difc, difc}, {Kernel::UnitParams::tzero, tzero}};
initialize(-1., 0, params);
return std::max(conversionTOFMin(), tofmin);
}
double dSpacing::calcTofMax(const double difc, const double difa, const double tzero, const double tofmax) {
Kernel::UnitParametersMap params{
{Kernel::UnitParams::difa, difa}, {Kernel::UnitParams::difc, difc}, {Kernel::UnitParams::tzero, tzero}};
initialize(-1, 0, params);
return std::min(conversionTOFMax(), tofmax);
}
// ==================================================================================================
/* D-SPACING Perpendicular
* ==================================================================================================
*
* Conversion uses equation: dp^2 = lambda^2 - 2[Angstrom^2]*ln(cos(theta))
*/
DECLARE_UNIT(dSpacingPerpendicular)
const UnitLabel dSpacingPerpendicular::label() const { return Symbol::Angstrom; }
dSpacingPerpendicular::dSpacingPerpendicular() : Unit(), factorTo(DBL_MIN), factorFrom(DBL_MIN) {}
void dSpacingPerpendicular::validateUnitParams(const int, const UnitParametersMap ¶ms) {
if (!ParamPresent(params, UnitParams::l2)) {
throw std::runtime_error("A l2 value must be supplied in the extra parameters when "
"initialising " +
this->unitID() + " for conversion via TOF");
}
if (!ParamPresent(params, UnitParams::twoTheta)) {
throw std::runtime_error("A two theta value must be supplied in the extra parameters when "
"initialising " +
this->unitID() + " for conversion via TOF");
}
}
void dSpacingPerpendicular::init() {
double l2 = 0.0;
ParamPresentAndSet(m_params, UnitParams::l2, l2);
ParamPresentAndSet(m_params, UnitParams::twoTheta, twoTheta);
factorTo = (PhysicalConstants::NeutronMass * (l1 + l2)) / PhysicalConstants::h;
// Now adjustments for the scale of units used
const double TOFisinMicroseconds = 1e6;
const double toAngstroms = 1e10;
factorTo *= TOFisinMicroseconds / toAngstroms;
factorFrom = factorTo;
if (factorFrom == 0.0)
factorFrom = DBL_MIN; // Protect against divide by zero
double cos_theta = cos(twoTheta / 2.0);
sfpTo = 0.0;
if (cos_theta > 0)
sfpTo = 2.0 * log(cos_theta);
sfpFrom = sfpTo;
}
double dSpacingPerpendicular::singleToTOF(const double x) const {
double sqrtarg = x * x + sfpTo;
// consider very small values to be a rounding error
if (sqrtarg < 1.0e-17)
return 0.0;
return sqrt(sqrtarg) * factorTo;
}
double dSpacingPerpendicular::singleFromTOF(const double tof) const {
double temp = tof / factorFrom;
return sqrt(temp * temp - sfpFrom);
}
double dSpacingPerpendicular::conversionTOFMin() const { return sqrt(-1.0 * sfpFrom); }
double dSpacingPerpendicular::conversionTOFMax() const { return sqrt(std::numeric_limits<double>::max()) / factorFrom; }
Unit *dSpacingPerpendicular::clone() const { return new dSpacingPerpendicular(*this); }
// ================================================================================
/* MOMENTUM TRANSFER
* ================================================================================
*
* The relationship is Q = 2k sin (theta). where k is 2*pi/wavelength
*/
DECLARE_UNIT(MomentumTransfer)
const UnitLabel MomentumTransfer::label() const { return Symbol::InverseAngstrom; }
MomentumTransfer::MomentumTransfer() : Unit() {
addConversion("QSquared", 1.0, 2.0);
const double factor = 2.0 * M_PI;
addConversion("dSpacing", factor, -1.0);
}
void MomentumTransfer::validateUnitParams(const int, const UnitParametersMap ¶ms) {
double difc = 0.;
if (!ParamPresentAndSet(¶ms, UnitParams::difc, difc)) {
if (!ParamPresent(params, UnitParams::twoTheta) || (!ParamPresent(params, UnitParams::l2)))
throw std::runtime_error("A difc value or L2/two theta must be supplied "
"in the extra parameters when initialising " +
this->unitID() + " for conversion via TOF");
};
}
void MomentumTransfer::init() {
// First the crux of the conversion
difc = 0.;
if (!ParamPresentAndSet(m_params, UnitParams::difc, difc)) {
// also support inputs as L2, two theta
double l2;
if (ParamPresentAndSet(m_params, UnitParams::l2, l2)) {
double twoTheta;
if (ParamPresentAndSet(m_params, UnitParams::twoTheta, twoTheta)) {
difc = 1. / tofToDSpacingFactor(l1, l2, twoTheta, 0.);
}
}
}
}
double MomentumTransfer::singleToTOF(const double x) const { return 2. * M_PI * difc / x; }
//
double MomentumTransfer::singleFromTOF(const double tof) const { return 2. * M_PI * difc / tof; }
double MomentumTransfer::conversionTOFMin() const { return 2. * M_PI * difc / DBL_MAX; }
double MomentumTransfer::conversionTOFMax() const { return DBL_MAX; }
Unit *MomentumTransfer::clone() const { return new MomentumTransfer(*this); }
/* ===================================================================================================
* Q-SQUARED
* ===================================================================================================
*/
DECLARE_UNIT(QSquared)
const UnitLabel QSquared::label() const { return Symbol::InverseAngstromSq; }
QSquared::QSquared() : MomentumTransfer() {
addConversion("MomentumTransfer", 1.0, 0.5);
const double factor = 2.0 * M_PI;
addConversion("dSpacing", factor, -0.5);
}
double QSquared::singleToTOF(const double x) const { return MomentumTransfer::singleToTOF(sqrt(x)); }
double QSquared::singleFromTOF(const double tof) const { return pow(MomentumTransfer::singleFromTOF(tof), 2); }
double QSquared::conversionTOFMin() const { return 2 * M_PI * difc / sqrt(DBL_MAX); }
double QSquared::conversionTOFMax() const {
double tofmax = 2 * M_PI * difc / sqrt(DBL_MIN);
if (std::isinf(tofmax))
tofmax = DBL_MAX;
return tofmax;
}
Unit *QSquared::clone() const { return new QSquared(*this); }
/* ==============================================================================
* Energy Transfer
* ==============================================================================
*/
DECLARE_UNIT(DeltaE)
const UnitLabel DeltaE::label() const { return Symbol::MilliElectronVolts; }
DeltaE::DeltaE()
: Unit(), factorTo(DBL_MIN), factorFrom(DBL_MIN), t_other(DBL_MIN), t_otherFrom(DBL_MIN), unitScaling(DBL_MIN) {
addConversion("DeltaE_inWavenumber", PhysicalConstants::meVtoWavenumber, 1.);
addConversion("DeltaE_inFrequency", PhysicalConstants::meVtoFrequency, 1.);
}
void DeltaE::validateUnitParams(const int emode, const UnitParametersMap ¶ms) {
if (emode != 1 && emode != 2) {
throw std::invalid_argument("emode must be equal to 1 or 2 for energy transfer calculation");
}
// Efixed must be set to something
double efixed;
if (!ParamPresentAndSet(¶ms, UnitParams::efixed, efixed)) {
if (emode == 1) { // direct, efixed=ei
throw std::invalid_argument("efixed must be set for energy transfer calculation");
} else {
throw std::runtime_error("efixed must be set for energy transfer calculation");
}
}
if (efixed <= 0) {
throw std::runtime_error("efixed must be greater than zero");
}
if (!ParamPresent(params, UnitParams::l2)) {
throw std::runtime_error("A l2 value must be supplied in the extra parameters when "
"initialising " +
this->unitID() + " for conversion via TOF");
}
}
void DeltaE::init() {
double l2 = 0.0;
ParamPresentAndSet(m_params, UnitParams::l2, l2);
ParamPresentAndSet(m_params, UnitParams::efixed, efixed);
const double TOFinMicroseconds = 1e6;
factorTo = sqrt(PhysicalConstants::NeutronMass / (2.0 * PhysicalConstants::meV)) * TOFinMicroseconds;
if (emode == 1) {
// t_other is t1
t_other = (factorTo * l1) / sqrt(efixed);
factorTo *= l2;
} else if (emode == 2) {
// t_other is t2
t_other = (factorTo * l2) / sqrt(efixed);
factorTo *= l1;
}
//------------ from conversion ------------------
factorFrom = sqrt(PhysicalConstants::NeutronMass / (2.0 * PhysicalConstants::meV)) * TOFinMicroseconds;
if (emode == 1) {
// t_otherFrom = t1
t_otherFrom = (factorFrom * l1) / sqrt(efixed);
factorFrom = factorFrom * factorFrom * l2 * l2;
} else if (emode == 2) {
// t_otherFrom = t2
t_otherFrom = (factorFrom * l2) / sqrt(efixed);
factorFrom = factorFrom * factorFrom * l1 * l1;
}
// This will be changed for the wavenumber one
unitScaling = 1;
}
double DeltaE::singleToTOF(const double x) const {
if (emode == 1) {
const double e2 = efixed - x / unitScaling;
if (e2 <= 0.0) // This shouldn't ever happen (unless the efixed value is wrong)
return DeltaE::conversionTOFMax();
else {
// this_t = t2;
const double this_t = factorTo / sqrt(e2);
return this_t + t_other; // (t1+t2);
}
} else if (emode == 2) {
const double e1 = efixed + x / unitScaling;
if (e1 <= 0.0) // This shouldn't ever happen (unless the efixed value is wrong)
return DeltaE::conversionTOFMax();
else {
// this_t = t1;
const double this_t = factorTo / sqrt(e1);
return this_t + t_other; // (t1+t2);
}
} else {
return DeltaE::conversionTOFMax();
}
}