-
Notifications
You must be signed in to change notification settings - Fork 122
/
LeBailFit.cpp
2431 lines (2112 loc) · 87.3 KB
/
LeBailFit.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 +
#include "MantidCurveFitting/Algorithms/LeBailFit.h"
#include "MantidAPI/FuncMinimizerFactory.h"
#include "MantidAPI/FunctionFactory.h"
#include "MantidAPI/TableRow.h"
#include "MantidAPI/TextAxis.h"
#include "MantidAPI/WorkspaceFactory.h"
#include "MantidCurveFitting/Algorithms/Fit.h"
#include "MantidCurveFitting/Functions/BackgroundFunction.h"
#include "MantidHistogramData/HistogramX.h"
#include "MantidHistogramData/HistogramY.h"
#include "MantidKernel/ArrayProperty.h"
#include "MantidKernel/ListValidator.h"
#include "MantidKernel/VisibleWhenProperty.h"
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>
#include <cctype>
#include <fstream>
#include <iomanip>
const int OBSDATAINDEX(0);
const int CALDATAINDEX(1);
const int DATADIFFINDEX(2);
const int CALPUREPEAKINDEX(3);
// Output workspace background at ws index 4
const int CALBKGDINDEX(4);
// Input background
const int INPUTBKGDINDEX(6);
// Output workspace: pure peak (data with background removed)
const int INPUTPUREPEAKINDEX(7);
const double NOBOUNDARYLIMIT(1.0E10);
const double EPSILON(1.0E-10);
using namespace Mantid;
using namespace Mantid::CurveFitting;
using namespace Mantid::DataObjects;
using namespace Mantid::API;
using namespace Mantid::Kernel;
using Mantid::HistogramData::HistogramX;
using Mantid::HistogramData::HistogramY;
using namespace std;
namespace Mantid {
namespace CurveFitting {
namespace Algorithms {
const Rfactor badR(DBL_MAX, DBL_MAX);
DECLARE_ALGORITHM(LeBailFit)
//----------------------------------------------------------------------------------------------
/** Constructor
*/
LeBailFit::LeBailFit()
: m_lebailFunction(), m_dataWS(), m_outputWS(), parameterWS(),
reflectionWS(), m_wsIndex(0), m_startX(DBL_MAX), m_endX(DBL_MIN),
m_inputPeakInfoVec(), m_backgroundFunction(), m_funcParameters(),
m_origFuncParameters(), m_peakType(), m_backgroundType(),
m_backgroundParameters(), m_backgroundParameterNames(), m_bkgdorder(0),
mPeakRadius(0), m_lebailFitChi2(0.), m_lebailCalChi2(0.), mMinimizer(),
m_dampingFactor(0.), m_inputParameterPhysical(false), m_fitMode(),
m_indicatePeakHeight(0.), m_MCGroups(), m_numMCGroups(0), m_bestRwp(0.),
m_bestRp(0.), m_bestParameters(), m_bestBackgroundData(), m_bestMCStep(0),
m_numMinimizeSteps(0), m_Temperature(DBL_MIN), m_useAnnealing(false),
m_walkStyle(RANDOMWALK), m_minimumPeakHeight(DBL_MAX),
m_tolerateInputDupHKL2Peaks(false), m_bkgdParameterNames(),
m_numberBkgdParameters(0), m_bkgdParameterBuffer(), m_bestBkgdParams(),
m_roundBkgd(0), m_bkgdParameterStepVec(), m_peakCentreTol(0.) {}
//----------------------------------------------------------------------------------------------
/** Declare the input properties for this algorithm
*/
void LeBailFit::init() {
// -------------- Input and output Workspaces -----------------
// Input Data Workspace
this->declareProperty(
std::make_unique<WorkspaceProperty<MatrixWorkspace>>("InputWorkspace", "",
Direction::Input),
"Input workspace containing the data to fit by LeBail algorithm.");
// Output Result Data/Model Workspace
this->declareProperty(std::make_unique<WorkspaceProperty<Workspace2D>>(
"OutputWorkspace", "", Direction::Output),
"Output workspace containing calculated pattern or "
"calculated background. ");
// Instrument profile Parameters
this->declareProperty(std::make_unique<WorkspaceProperty<TableWorkspace>>(
"InputParameterWorkspace", "", Direction::Input),
"Input table workspace containing the parameters "
"required by LeBail fit. ");
// Output instrument profile parameters
auto tablewsprop1 = std::make_unique<WorkspaceProperty<TableWorkspace>>(
"OutputParameterWorkspace", "", Direction::Output,
API::PropertyMode::Optional);
this->declareProperty(std::move(tablewsprop1),
"Input table workspace containing the "
"parameters required by LeBail fit. ");
// Single peak: Reflection (HKL) Workspace, PeaksWorkspace
this->declareProperty(
std::make_unique<WorkspaceProperty<TableWorkspace>>("InputHKLWorkspace",
"", Direction::Input),
"Input table workspace containing the list of reflections (HKL). ");
// Bragg peaks profile parameter output table workspace
auto tablewsprop2 = std::make_unique<WorkspaceProperty<TableWorkspace>>(
"OutputPeaksWorkspace", "", Direction::Output,
API::PropertyMode::Optional);
this->declareProperty(std::move(tablewsprop2),
"Optional output table workspace "
"containing all peaks' peak "
"parameters. ");
// WorkspaceIndex
this->declareProperty("WorkspaceIndex", 0,
"Workspace index of the spectrum to fit by LeBail.");
// Interested region
this->declareProperty(
std::make_unique<Kernel::ArrayProperty<double>>("FitRegion"),
"Region of data (TOF) for LeBail fit. Default is whole range. ");
// Functionality: Fit/Calculation/Background
std::vector<std::string> functions{"LeBailFit", "Calculation", "MonteCarlo",
"RefineBackground"};
auto validator = std::make_shared<Kernel::StringListValidator>(functions);
this->declareProperty("Function", "LeBailFit", validator, "Functionality");
// Peak type
vector<string> peaktypes{"ThermalNeutronBk2BkExpConvPVoigt",
"NeutronBk2BkExpConvPVoigt"};
auto peaktypevalidator = std::make_shared<StringListValidator>(peaktypes);
declareProperty("PeakType", "ThermalNeutronBk2BkExpConvPVoigt",
peaktypevalidator, "Peak profile type.");
/*------------------------ Background Related Properties
* ---------------------------------*/
// About background: Background type, input (table workspace or array)
std::vector<std::string> bkgdtype{"Polynomial", "Chebyshev",
"FullprofPolynomial"};
auto bkgdvalidator = std::make_shared<Kernel::StringListValidator>(bkgdtype);
declareProperty("BackgroundType", "Polynomial", bkgdvalidator,
"Background type");
// Input background parameters (array)
this->declareProperty(
std::make_unique<Kernel::ArrayProperty<double>>("BackgroundParameters"),
"Optional: enter a comma-separated list of background order parameters "
"from order 0. ");
// Input background parameters (tableworkspace)
auto tablewsprop3 = std::make_unique<WorkspaceProperty<TableWorkspace>>(
"BackgroundParametersWorkspace", "", Direction::InOut,
API::PropertyMode::Optional);
this->declareProperty(
std::move(tablewsprop3),
"Optional table workspace containing the fit result for background.");
// Peak Radius
this->declareProperty(
"PeakRadius", 5, "Range (multiplier relative to FWHM) for a full peak. ");
/*------------------------ Properties for Calculation Mode
* --------------------------------*/
// Output option to plot each individual peak
declareProperty("PlotIndividualPeaks", false,
"Option to output each individual peak in mode Calculation.");
setPropertySettings("PlotIndividualPeaks",
std::make_unique<VisibleWhenProperty>(
"Function", IS_EQUAL_TO, "Calculation"));
// Make each reflection visible
declareProperty("IndicationPeakHeight", 0.0,
"Heigh of peaks (reflections) if its calculated height is "
"smaller than user-defined minimum.");
setPropertySettings("IndicationPeakHeight",
std::make_unique<VisibleWhenProperty>(
"Function", IS_EQUAL_TO, "Calculation"));
// UseInputPeakHeights
declareProperty("UseInputPeakHeights", true,
"For 'Calculation' mode only, use peak heights specified in "
"ReflectionWorkspace. "
"Otherwise, calcualte peaks' heights. ");
setPropertySettings("UseInputPeakHeights",
std::make_unique<VisibleWhenProperty>(
"Function", IS_EQUAL_TO, "Calculation"));
/*--------------------------- Properties for Fitting Mode
* ---------------------------------*/
// Minimizer
std::vector<std::string> minimizerOptions =
API::FuncMinimizerFactory::Instance().getKeys(); // :Instance().getKeys();
declareProperty("Minimizer", "Levenberg-MarquardtMD",
Kernel::IValidator_sptr(
new Kernel::ListValidator<std::string>(minimizerOptions)),
"The minimizer method applied to do the fit, default is "
"Levenberg-Marquardt",
Kernel::Direction::InOut);
setPropertySettings("Minimizer", std::make_unique<VisibleWhenProperty>(
"Function", IS_EQUAL_TO, "LeBailFit"));
declareProperty("Damping", 1.0,
"Damping factor if minimizer is 'Damped Gauss-Newton'");
setPropertySettings("Damping", std::make_unique<VisibleWhenProperty>(
"Function", IS_EQUAL_TO, "LeBailFit"));
setPropertySettings("Damping", std::make_unique<VisibleWhenProperty>(
"Function", IS_EQUAL_TO, "MonteCarlo"));
declareProperty("NumberMinimizeSteps", 100,
"Number of Monte Carlo random walk steps.");
setPropertySettings("NumberMinimizeSteps",
std::make_unique<VisibleWhenProperty>(
"Function", IS_EQUAL_TO, "LeBailFit"));
setPropertySettings("NumberMinimizeSteps",
std::make_unique<VisibleWhenProperty>(
"Function", IS_EQUAL_TO, "MonteCarlo"));
setPropertySettings("NumberMinimizeSteps",
std::make_unique<VisibleWhenProperty>(
"Function", IS_EQUAL_TO, "RefineBackground"));
//----------------- Parameters for Monte Carlo Simulated Annealing
//--------------------------
auto mcwsprop = std::make_unique<WorkspaceProperty<TableWorkspace>>(
"MCSetupWorkspace", "", Direction::Input, PropertyMode::Optional);
declareProperty(std::move(mcwsprop),
"Name of table workspace containing parameters' "
"setup for Monte Carlo simualted annearling. ");
setPropertySettings("MCSetupWorkspace",
std::make_unique<VisibleWhenProperty>(
"Function", IS_EQUAL_TO, "MonteCarlo"));
declareProperty("RandomSeed", 1, "Random number seed.");
setPropertySettings("RandomSeed", std::make_unique<VisibleWhenProperty>(
"Function", IS_EQUAL_TO, "MonteCarlo"));
declareProperty("AnnealingTemperature", 1.0,
"Temperature used Monte Carlo. "
"Negative temperature is for simulated annealing. ");
setPropertySettings("AnnealingTemperature",
std::make_unique<VisibleWhenProperty>(
"Function", IS_EQUAL_TO, "MonteCarlo"));
declareProperty("UseAnnealing", true,
"Allow annealing temperature adjusted automatically.");
setPropertySettings("UseAnnealing",
std::make_unique<VisibleWhenProperty>(
"Function", IS_EQUAL_TO, "MonteCarlo"));
declareProperty("DrunkenWalk", false,
"Flag to use drunken walk algorithm. "
"Otherwise, random walk algorithm is used. ");
setPropertySettings("DrunkenWalk",
std::make_unique<VisibleWhenProperty>(
"Function", IS_EQUAL_TO, "MonteCarlo"));
declareProperty(
"MinimumPeakHeight", 0.01,
"Minimum height of a peak to be counted "
"during smoothing background by exponential smooth algorithm. ");
// Flag to allow input hkl file containing degenerated peaks
declareProperty(
"AllowDegeneratedPeaks", false,
"Flag to allow degenerated peaks in input .hkl file. "
"Otherwise, an exception will be thrown if this situation occurs.");
// Tolerance of imported peak's position comparing to data range
declareProperty("ToleranceToImportPeak", EMPTY_DBL(),
"Tolerance in TOF to import peak from Bragg "
"peaks list. If it specified, all peaks within Xmin-Tol and "
"Xmax+Tol will be imported. "
"It is used in the case that the geometry parameters are "
"close to true values. ");
}
//----------------------------------------------------------------------------------------------
/** Implement abstract Algorithm methods
*/
void LeBailFit::exec() {
// Process input properties
processInputProperties();
// Import parameters from table workspace
parseInstrumentParametersTable();
parseBraggPeaksParametersTable();
// Background function and calculation on it
processInputBackground();
// Create Le Bail function
createLeBailFunction();
// Create output workspace/workspace
createOutputDataWorkspace();
// 5. Adjust function mode according to input values
if (m_lebailFunction->isParameterValid()) {
// All peaks within range are physical and good to refine
m_inputParameterPhysical = true;
} else {
// Some peaks within range have unphysical parameters. Just calcualtion for
// reference
m_inputParameterPhysical = false;
g_log.warning()
<< "Input instrument parameters values cause some peaks to have "
"unphysical profile parameters.\n";
if (m_fitMode == FIT || m_fitMode == MONTECARLO) {
g_log.warning()
<< "Function mode FIT is disabled. Convert to Calculation mode.\n";
m_fitMode = CALCULATION;
}
}
// 7. Do calculation or fitting
m_lebailFitChi2 = -1; // Initialize
m_lebailCalChi2 = -1;
switch (m_fitMode) {
case CALCULATION:
// Calculation
g_log.notice() << "Function: Pattern Calculation.\n";
execPatternCalculation();
break;
case FIT:
// LeBail Fit
g_log.notice() << "Function: Do LeBail Fit ==> Monte Carlo.\n";
// fall through
case MONTECARLO:
// Monte carlo Le Bail refinement
g_log.notice("Function: Do LeBail Fit By Monte Carlo Random Walk.");
execRandomWalkMinimizer(m_numMinimizeSteps, m_funcParameters);
break;
case BACKGROUNDPROCESS:
// Calculating background
// FIXME : Determine later whether this functionality is kept or removed!
g_log.notice() << "Function: Refine Background (Precisely).\n";
execRefineBackground();
break;
default:
// Impossible
std::stringstream errmsg;
errmsg << "FunctionMode = " << m_fitMode << " is not supported in exec().";
g_log.error() << errmsg.str() << "\n";
throw std::runtime_error(errmsg.str());
break;
}
// 7. Output peak (table) and parameter workspace
exportBraggPeakParameterToTable();
exportInstrumentParameterToTable(m_funcParameters);
setProperty("OutputWorkspace", m_outputWS);
// 8. Final statistic
Rfactor finalR =
getRFactor(m_outputWS->y(0).rawData(), m_outputWS->y(1).rawData(),
m_outputWS->e(0).rawData());
g_log.notice() << "\nFinal R factor: Rwp = " << finalR.Rwp
<< ", Rp = " << finalR.Rp
<< ", Data points = " << m_outputWS->y(1).size()
<< ", Range = " << m_outputWS->x(0)[0] << ", "
<< m_outputWS->x(0).back() << "\n";
}
//----------------------------------------------------------------------------------------------
/** Process input background properties and do the calculation upon it
* and also calculate the input data with (input) background reduced
*/
void LeBailFit::processInputBackground() {
// FIXME - Need to think of FullprofPolynomial
// Type
m_backgroundType = getPropertyValue("BackgroundType");
// Parameters
m_backgroundParameters = getProperty("BackgroundParameters");
TableWorkspace_sptr bkgdparamws =
getProperty("BackgroundParametersWorkspace");
// Determine where the background parameters are from
if (!bkgdparamws) {
// Set up parameter name
m_backgroundParameterNames.clear();
size_t i0 = 0;
if (m_backgroundType == "FullprofPolynomial") {
// TODO - Add this special case to Wiki
m_backgroundParameterNames.emplace_back("Bkpos");
if (m_backgroundParameters[0] < m_startX ||
m_backgroundParameters[0] > m_endX)
g_log.warning(
"Bkpos is out side of data range. It MIGHT NOT BE RIGHT. ");
i0 = 1;
}
size_t numparams = m_backgroundParameters.size();
for (size_t i = i0; i < numparams; ++i) {
stringstream parss;
parss << "A" << (i - i0);
m_backgroundParameterNames.emplace_back(parss.str());
}
g_log.information() << "[Input] Use background specified with vector with "
"input vector sized "
<< numparams << ".\n";
} else {
g_log.information()
<< "[Input] Use background specified by table workspace.\n";
parseBackgroundTableWorkspace(bkgdparamws, m_backgroundParameterNames,
m_backgroundParameters);
}
// Set up background order
m_bkgdorder = static_cast<unsigned int>(m_backgroundParameterNames.size());
if (m_backgroundType == "FullprofPolynomial") {
// Consider 1 extra Bkpos
if (m_bkgdorder == 0)
throw runtime_error("FullprofPolynomial: Bkpos must be given! ");
else if (m_bkgdorder <= 7)
m_bkgdorder = 6;
else if (m_bkgdorder <= 13)
m_bkgdorder = 12;
else
throw runtime_error(
"There is something wrong to set up FullprofPolynomial. ");
} else {
// order n will have n+1 parameters
if (m_bkgdorder == 0)
throw runtime_error(
"Polynomial and Chebyshev at least be order 0 (1 parameter). ");
--m_bkgdorder;
}
}
//=================================== Pattern Calculation & Minimizing
//=======================
//----------------------------------------------------------------------------------------------
/** Calcualte LeBail diffraction pattern:
* Output spectra:
* 0: data; 1: calculated pattern; 3: difference
* 4: input pattern w/o background
* 5~5+(N-1): optional individual peak
*/
void LeBailFit::execPatternCalculation() {
// Generate domain and values vectors
const auto &vecX = m_dataWS->x(m_wsIndex).rawData();
std::vector<double> vecY(m_outputWS->y(CALDATAINDEX).size(), 0);
// Calculate diffraction pattern
Rfactor rfactor(-DBL_MAX, -DBL_MAX);
// FIXME - It should be a new ticket to turn on this option (use
// user-specified peak height)
bool useinputpeakheights = this->getProperty("UseInputPeakHeights");
if (useinputpeakheights)
g_log.warning("UseInputPeakHeights is temporarily turned off now. ");
// Set the parameters to LeBailFunction
map<string, double> profilemap = convertToDoubleMap(m_funcParameters);
m_lebailFunction->setProfileParameterValues(profilemap);
// Calculate peak intensities and diffraction pattern
vector<double> emptyvec;
bool resultphysical = calculateDiffractionPattern(
m_dataWS->x(m_wsIndex), m_dataWS->y(m_wsIndex), true, true, emptyvec,
vecY, rfactor);
m_outputWS->mutableY(CALDATAINDEX) = std::move(vecY);
// Calculate background
m_outputWS->mutableY(INPUTBKGDINDEX) =
m_lebailFunction->function(vecX, false, true);
m_outputWS->mutableY(INPUTPUREPEAKINDEX) =
m_outputWS->y(OBSDATAINDEX) - m_outputWS->y(INPUTBKGDINDEX);
// Set up output workspaces
m_outputWS->mutableY(DATADIFFINDEX) =
m_outputWS->y(OBSDATAINDEX) - m_outputWS->y(CALDATAINDEX);
// Calcualte individual peaks
bool ploteachpeak = this->getProperty("PlotIndividualPeaks");
g_log.information() << "Output individual peaks = " << ploteachpeak << ".\n";
if (ploteachpeak) {
for (size_t ipk = 0; ipk < m_lebailFunction->getNumberOfPeaks(); ++ipk) {
m_outputWS->mutableY(9 + ipk) =
m_lebailFunction->calPeak(ipk, vecX, m_outputWS->y(9 + ipk).size());
}
}
// Record for output
Parameter par_rwp;
par_rwp.name = "Rwp";
par_rwp.curvalue = rfactor.Rwp;
m_funcParameters["Rwp"] = par_rwp;
g_log.notice() << "Rwp = " << rfactor.Rwp << ", Rp = " << rfactor.Rp << "\n";
if (!resultphysical) {
g_log.warning()
<< "Input parameters are unable to generate peaks that are physical."
<< ".\n";
}
}
//==================================== Refine background
//====================================
//----------------------------------------------------------------------------------------------
/** Calculate background of the specified diffraction pattern
* by
* 1. fix the peak parameters but height;
* 2. fit only heights of the peaks in a peak-group and background coefficients
* (assumed order 2 or 3 polynomial)
* 3. remove peaks by the fitting result
*/
void LeBailFit::execRefineBackground() {
// Set up class variables for background
m_bkgdParameterNames = m_backgroundFunction->getParameterNames();
m_numberBkgdParameters = m_bkgdParameterNames.size();
m_bkgdParameterBuffer.resize(m_numberBkgdParameters);
m_bestBkgdParams.resize(m_numberBkgdParameters);
m_roundBkgd = 0;
m_bkgdParameterStepVec.resize(m_numberBkgdParameters, 0.01);
for (size_t i = 1; i < m_numberBkgdParameters; ++i) {
m_bkgdParameterStepVec[i] = m_bkgdParameterStepVec[i - 1] * 0.0001;
}
// 1. Generate domain and value
const auto &vecX = m_dataWS->x(m_wsIndex).rawData();
const auto &vecY = m_dataWS->y(m_wsIndex);
vector<double> valueVec(vecX.size(), 0);
size_t numpts = vecX.size();
API::FunctionDomain1DVector domain(vecX);
API::FunctionValues values(domain);
// 2. Calculate diffraction pattern
Rfactor currR(DBL_MAX, DBL_MAX);
m_backgroundFunction->function(domain, values);
vector<double> backgroundvalues = values.toVector();
for (size_t i = 0; i < numpts; ++i) {
m_outputWS->mutableY(INPUTPUREPEAKINDEX)[i] =
m_dataWS->y(m_wsIndex)[i] - values[i];
}
m_outputWS->setSharedE(INPUTPUREPEAKINDEX, m_dataWS->sharedE(m_wsIndex));
map<string, double> parammap = convertToDoubleMap(m_funcParameters);
m_lebailFunction->setProfileParameterValues(parammap);
calculateDiffractionPattern(m_outputWS->x(INPUTPUREPEAKINDEX),
m_outputWS->y(INPUTPUREPEAKINDEX), false, true,
backgroundvalues, valueVec, currR);
Rfactor bestR = currR;
storeBackgroundParameters(m_bestBkgdParams);
stringstream bufss;
bufss << "Starting background parameter ";
for (size_t i = 0; i < m_bestBkgdParams.size(); ++i)
bufss << "[" << i << "] = " << m_bestBkgdParams[i] << ", ";
bufss << ". Starting Rwp = " << currR.Rwp;
g_log.notice(bufss.str());
for (size_t istep = 0; istep < m_numMinimizeSteps; ++istep) {
// a) Store current setup
storeBackgroundParameters(m_bkgdParameterBuffer);
// b) Propose new values and evalulate
proposeNewBackgroundValues();
Rfactor newR(DBL_MAX, DBL_MAX);
m_backgroundFunction->function(domain, values);
backgroundvalues = values.toVector();
for (size_t i = 0; i < numpts; ++i) {
m_outputWS->mutableY(INPUTPUREPEAKINDEX)[i] =
m_dataWS->y(m_wsIndex)[i] - values[i];
}
parammap = convertToDoubleMap(m_funcParameters);
m_lebailFunction->setProfileParameterValues(parammap);
calculateDiffractionPattern(m_outputWS->x(INPUTPUREPEAKINDEX),
m_outputWS->y(INPUTPUREPEAKINDEX), false, true,
backgroundvalues, valueVec, newR);
g_log.information() << "[DBx800] New Rwp = " << newR.Rwp
<< ", Rp = " << newR.Rp << ".\n";
bool accept = acceptOrDeny(currR, newR);
// c) Process result
if (!accept) {
// Not accept. Restore original
recoverBackgroundParameters(m_bkgdParameterBuffer);
} else {
// Accept
currR = newR;
if (newR.Rwp < bestR.Rwp) {
// Is it the best?
bestR = newR;
storeBackgroundParameters(m_bestBkgdParams);
stringstream ss;
ss << "Temp best background parameter ";
for (size_t i = 0; i < m_bestBkgdParams.size(); ++i)
ss << "[" << i << "] = " << m_bestBkgdParams[i] << ", ";
g_log.information(ss.str());
}
}
// d) Progress
progress(static_cast<double>(istep) /
static_cast<double>(m_numMinimizeSteps));
}
// 3. Recover the best
recoverBackgroundParameters(m_bestBkgdParams);
stringstream bufss1;
bufss1 << "Best background parameter ";
for (size_t i = 0; i < m_bkgdParameterStepVec.size(); ++i)
bufss1 << "[" << i << "] = " << m_backgroundFunction->getParameter(i)
<< ", ";
g_log.notice(bufss1.str());
Rfactor outputR(-DBL_MAX, -DBL_MAX);
m_backgroundFunction->function(domain, values);
backgroundvalues = values.toVector();
for (size_t i = 0; i < numpts; ++i) {
m_outputWS->mutableY(INPUTPUREPEAKINDEX)[i] =
m_dataWS->y(m_wsIndex)[i] - values[i];
}
parammap = convertToDoubleMap(m_funcParameters);
m_lebailFunction->setProfileParameterValues(parammap);
calculateDiffractionPattern(m_outputWS->x(INPUTPUREPEAKINDEX),
m_outputWS->y(INPUTPUREPEAKINDEX), false, true,
backgroundvalues, valueVec, outputR);
g_log.notice() << "[RefineBackground] Best Rwp = " << bestR.Rwp
<< ", vs. recovered best Rwp = " << outputR.Rwp << ".\n";
// 4. Add data (0: experimental, 1: calcualted, 2: difference)
auto &vecY1 = m_outputWS->mutableY(1);
auto &vecY2 = m_outputWS->mutableY(2);
for (size_t i = 0; i < numpts; ++i) {
vecY1[i] = valueVec[i] + backgroundvalues[i];
vecY2[i] = vecY[i] - (valueVec[i] + backgroundvalues[i]);
}
// (3: peak without background, 4: input background)
// m_backgroundFunction->function(domain, values);
m_outputWS->mutableY(CALBKGDINDEX) = std::move(backgroundvalues);
m_outputWS->mutableY(CALPUREPEAKINDEX) = std::move(valueVec);
// 5. Output background to table workspace
auto outtablews = std::make_shared<TableWorkspace>();
outtablews->addColumn("str", "Name");
outtablews->addColumn("double", "Value");
outtablews->addColumn("double", "Error");
for (const auto &parname : m_bkgdParameterNames) {
double parvalue = m_backgroundFunction->getParameter(parname);
TableRow newrow = outtablews->appendRow();
newrow << parname << parvalue << 1.0;
}
setProperty("BackgroundParametersWorkspace", outtablews);
}
//----------------------------------------------------------------------------------------------
/** Store/buffer current background parameters
* @param bkgdparamvec :: vector to save the background parameters whose order
* is same in background function
*/
void LeBailFit::storeBackgroundParameters(vector<double> &bkgdparamvec) {
for (size_t i = 0; i < m_numberBkgdParameters; ++i) {
bkgdparamvec[i] = m_backgroundFunction->getParameter(i);
}
}
/** Restore/recover the buffered background parameters to m_background function
* @param bkgdparamvec :: vector holding the background parameters whose order
* is same in background function
*/
void LeBailFit::recoverBackgroundParameters(
const vector<double> &bkgdparamvec) {
for (size_t i = 0; i < m_numberBkgdParameters; ++i) {
m_backgroundFunction->setParameter(i, bkgdparamvec[i]);
}
}
/** Propose new background parameters
*/
void LeBailFit::proposeNewBackgroundValues() {
int iparam = m_roundBkgd % static_cast<int>(m_numberBkgdParameters);
double currvalue =
m_backgroundFunction->getParameter(static_cast<int>(iparam));
double r =
2 * (static_cast<double>(rand()) / static_cast<double>(RAND_MAX) - 0.5);
double newvalue = currvalue + r * m_bkgdParameterStepVec[iparam];
g_log.information() << "[DBx804] Background " << iparam
<< " propose new value = " << newvalue << " from "
<< currvalue << ".\n";
m_backgroundFunction->setParameter(static_cast<size_t>(iparam), newvalue);
++m_roundBkgd;
}
//=================================== Set up the Le Bail Fit
//================================
//----------------------------------------------------------------------------------------------
/** Create LeBailFunction, including creating Le Bail function, add peaks and
* background
*/
void LeBailFit::createLeBailFunction() {
// Generate Le Bail function
m_lebailFunction =
std::make_shared<LeBailFunction>(LeBailFunction(m_peakType));
// Set up profile parameters
if (m_funcParameters.empty())
throw runtime_error("Function parameters must be set up by this point.");
map<string, double> pardblmap = convertToDoubleMap(m_funcParameters);
m_lebailFunction->setProfileParameterValues(pardblmap);
// Add peaks
if (!isEmpty(m_peakCentreTol)) {
const auto &vecx = m_dataWS->x(m_wsIndex);
m_lebailFunction->setPeakCentreTolerance(m_peakCentreTol, vecx.front(),
vecx.back());
}
vector<vector<int>> vecHKL;
vector<pair<vector<int>, double>>::iterator piter;
for (piter = m_inputPeakInfoVec.begin(); piter != m_inputPeakInfoVec.end();
++piter)
vecHKL.emplace_back(piter->first);
m_lebailFunction->addPeaks(vecHKL);
// Add background
m_lebailFunction->addBackgroundFunction(
m_backgroundType, m_bkgdorder, m_backgroundParameterNames,
m_backgroundParameters, m_startX, m_endX);
}
//----------------------------------------------------------------------------------------------
/** Crop workspace if user required
* @param inpws : input workspace to crop
* @param wsindex: workspace index of the data to fit against
*/
API::MatrixWorkspace_sptr
LeBailFit::cropWorkspace(const API::MatrixWorkspace_sptr &inpws,
size_t wsindex) {
// Process input property 'FitRegion' for range of data to fit/calculate
std::vector<double> fitrange = this->getProperty("FitRegion");
double tof_min, tof_max;
if (fitrange.empty()) {
tof_min = inpws->x(wsindex)[0];
tof_max = inpws->x(wsindex).back();
} else if (fitrange.size() == 2) {
tof_min = fitrange[0];
tof_max = fitrange[1];
} else {
g_log.warning() << "Input FitRegion has more than 2 entries. Using "
"default in stread.\n";
tof_min = inpws->x(wsindex)[0];
tof_max = inpws->x(wsindex).back();
}
// Crop workspace
API::IAlgorithm_sptr cropalg =
this->createChildAlgorithm("CropWorkspace", -1, -1, true);
cropalg->initialize();
cropalg->setProperty("InputWorkspace", inpws);
cropalg->setPropertyValue("OutputWorkspace", "MyData");
cropalg->setProperty("XMin", tof_min);
cropalg->setProperty("XMax", tof_max);
bool cropstatus = cropalg->execute();
if (!cropstatus) {
std::stringstream errmsg;
errmsg << "DBx309 Cropping workspace unsuccessful. Fatal Error. Quit!";
g_log.error() << errmsg.str() << "\n";
throw std::runtime_error(errmsg.str());
}
API::MatrixWorkspace_sptr cropws = cropalg->getProperty("OutputWorkspace");
if (!cropws) {
g_log.error("Unable to retrieve a Workspace2D object from ChildAlgorithm "
"CropWorkspace");
throw runtime_error("Unable to retrieve a Workspace2D object from "
"ChildAlgorithm CropWorkspace");
} else {
g_log.debug() << "DBx307: Cropped Workspace... Range From "
<< cropws->x(wsindex)[0] << " To "
<< cropws->x(wsindex).back() << " of size "
<< cropws->x(wsindex).size() << "\n";
}
return cropws;
}
//================================= Import/Parse and Output
//===================================
//----------------------------------------------------------------------------------------------
/** Process input properties to class variables and do some initial check
*/
void LeBailFit::processInputProperties() {
// Peak type
m_peakType = getPropertyValue("PeakType");
// 1. Get input and perform some check
// a) Import data workspace and related, do crop
API::MatrixWorkspace_sptr inpWS = this->getProperty("InputWorkspace");
int tempindex = this->getProperty("WorkspaceIndex");
m_wsIndex = size_t(tempindex);
if (m_wsIndex >= inpWS->getNumberHistograms()) {
// throw if workspace index is not correct
stringstream errss;
errss << "Input WorkspaceIndex " << tempindex << " is out of boundary [0, "
<< inpWS->getNumberHistograms() << "). ";
g_log.error(errss.str());
throw runtime_error(errss.str());
}
m_dataWS = this->cropWorkspace(inpWS, m_wsIndex);
m_startX = m_dataWS->x(0).front();
m_endX = m_dataWS->x(0).back();
// b) Minimizer
std::string minim = getProperty("Minimizer");
mMinimizer = minim;
// c) Peak parameters and related.
parameterWS = this->getProperty("InputParameterWorkspace");
reflectionWS = this->getProperty("InputHKLWorkspace");
mPeakRadius = this->getProperty("PeakRadius");
// d) Determine Functionality (function mode)
std::string function = this->getProperty("Function");
m_fitMode = FIT; // Default: LeBailFit
if (function == "Calculation") {
// peak calculation
m_fitMode = CALCULATION;
} else if (function == "CalculateBackground") {
// automatic background points selection
m_fitMode = BACKGROUNDPROCESS;
} else if (function == "MonteCarlo") {
// Monte Carlo random walk refinement
m_fitMode = MONTECARLO;
} else if (function == "LeBailFit") {
// Le Bail Fit mode
m_fitMode = FIT;
} else if (function == "RefineBackground") {
// Refine background mode
m_fitMode = BACKGROUNDPROCESS;
} else {
stringstream errss;
errss << "Function mode " << function
<< " is not supported by LeBailFit().";
g_log.error(errss.str());
throw invalid_argument(errss.str());
}
m_dampingFactor = getProperty("Damping");
tempindex = getProperty("NumberMinimizeSteps");
if (tempindex > 0)
m_numMinimizeSteps = static_cast<size_t>(tempindex);
else {
m_numMinimizeSteps = 0;
stringstream errss;
errss << "Input number of random walk steps (" << m_numMinimizeSteps
<< ") cannot be less and equal to zero.";
g_log.error(errss.str());
throw invalid_argument(errss.str());
}
m_minimumPeakHeight = getProperty("MinimumPeakHeight");
m_indicatePeakHeight = getProperty("IndicationPeakHeight");
// Tolerate duplicated input peak or not?
m_tolerateInputDupHKL2Peaks = getProperty("AllowDegeneratedPeaks");
// Tolerance in peak positions to import peak
m_peakCentreTol = getProperty("ToleranceToImportPeak");
}
//----------------------------------------------------------------------------------------------
/** Parse the input TableWorkspace to some maps for easy access
* Output : m_functionParameters
*/
void LeBailFit::parseInstrumentParametersTable() {
// 1. Check column orders
if (parameterWS->columnCount() < 3) {
g_log.error() << "Input parameter table workspace does not have enough "
"number of columns. "
<< " Number of columns (Input =" << parameterWS->columnCount()
<< ") >= 3 as required.\n";
throw std::invalid_argument("Input parameter workspace is wrong. ");
} else {
g_log.information()
<< "[DB] Starting to parse instrument parameter table workspace "
<< parameterWS->getName() << ".\n";
}
// 2. Import data to maps
size_t numrows = parameterWS->rowCount();
std::vector<std::string> colnames = parameterWS->getColumnNames();
size_t numcols = colnames.size();
std::map<std::string, double> tempdblmap;
std::map<std::string, std::string> tempstrmap;
std::map<std::string, double>::iterator dbliter;
std::map<string, string>::iterator striter;
std::string colname;
double dblvalue;
std::string strvalue;
for (size_t ir = 0; ir < numrows; ++ir) {
// a) Clear the map
tempdblmap.clear();
tempstrmap.clear();
// b) Get the row
API::TableRow trow = parameterWS->getRow(ir);
// c) Parse each term
for (size_t icol = 0; icol < numcols; ++icol) {
colname = colnames[icol];
if (colname != "FitOrTie" && colname != "Name") {
// double data
g_log.debug() << "Col-name = " << colname << ", ";
trow >> dblvalue;
g_log.debug() << "Value = " << dblvalue << ".\n";
;
tempdblmap.emplace(colname, dblvalue);
} else {
// string data
g_log.debug() << "Col-name = " << colname << ", ";
trow >> strvalue;
strvalue.erase(std::find_if(strvalue.rbegin(), strvalue.rend(),
std::not_fn(::isspace))
.base(),
strvalue.end());
g_log.debug() << "Value = " << strvalue << ".\n";
tempstrmap.emplace(colname, strvalue);
}
}
// d) Construct a Parameter instance
Parameter newparameter;
// i. name
striter = tempstrmap.find("Name");
if (striter != tempstrmap.end()) {
newparameter.name = striter->second;
} else {
std::stringstream errmsg;
errmsg << "Parameter (table) workspace " << parameterWS->getName()
<< " does not contain column 'Name'. It is not a valid input. "
"Quit ";
g_log.error() << errmsg.str() << "\n";
throw std::invalid_argument(errmsg.str());
}
// ii. fit
striter = tempstrmap.find("FitOrTie");
if (striter != tempstrmap.end()) {
std::string fitortie = striter->second;
bool tofit = true;
if (fitortie.length() > 0) {
char fc = fitortie.c_str()[0];
if (fc == 't' || fc == 'T') {
tofit = false;
}
}
newparameter.fit = tofit;
} else {
std::stringstream errmsg;
errmsg << "Parameter (table) workspace " << parameterWS->getName()