-
Notifications
You must be signed in to change notification settings - Fork 122
/
FitPeak.cpp
1651 lines (1401 loc) · 58 KB
/
FitPeak.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
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include "MantidAlgorithms/FitPeak.h"
#include "MantidAPI/CompositeFunction.h"
#include "MantidAPI/CostFunctionFactory.h"
#include "MantidAPI/FunctionProperty.h"
#include "MantidAPI/FunctionFactory.h"
#include "MantidAPI/FuncMinimizerFactory.h"
#include "MantidAPI/MatrixWorkspace.h"
#include "MantidAPI/WorkspaceFactory.h"
#include "MantidAPI/WorkspaceProperty.h"
#include "MantidAPI/TableRow.h"
#include "MantidKernel/ListValidator.h"
#include "MantidKernel/IValidator.h"
#include "MantidKernel/StartsWithValidator.h"
#include "MantidDataObjects/TableWorkspace.h"
#include "MantidKernel/ArrayProperty.h"
#include "MantidKernel/BoundedValidator.h"
#include "MantidAPI/MultiDomainFunction.h"
#include "boost/algorithm/string.hpp"
#include "boost/algorithm/string/trim.hpp"
using namespace Mantid;
using namespace Mantid::API;
using namespace Mantid::DataObjects;
using namespace Mantid::Kernel;
using Mantid::HistogramData::HistogramX;
using Mantid::HistogramData::HistogramY;
using namespace std;
const double MAGICNUMBER = 2.0;
namespace Mantid {
namespace Algorithms {
//----------------------------------------------------------------------------------------------
/** Constructor for FitOneSinglePeak
*/
FitOneSinglePeak::FitOneSinglePeak()
: API::Algorithm(), m_fitMethodSet(false), m_peakRangeSet(false),
m_peakWidthSet(false), m_peakWindowSet(false),
m_usePeakPositionTolerance(false), m_peakFunc(), m_bkgdFunc(), m_dataWS(),
m_wsIndex(0), m_minFitX(0.), m_maxFitX(0.), i_minFitX(0), i_maxFitX(0),
m_minPeakX(0.), m_maxPeakX(0.), i_minPeakX(0), i_maxPeakX(0),
m_bestPeakFunc(), m_bestBkgdFunc(), m_bkupPeakFunc(), m_bkupBkgdFunc(),
m_fitErrorPeakFunc(), m_fitErrorBkgdFunc(),
m_minimizer("Levenberg-MarquardtMD"), m_costFunction(), m_vecFWHM(),
m_peakPositionTolerance(0.), m_userPeakCentre(0.), m_bestRwp(0.),
m_finalGoodnessValue(0.), m_numFitCalls(0), m_sstream("") {}
//----------------------------------------------------------------------------------------------
/** Set workspaces
*/
void FitOneSinglePeak::setWorskpace(API::MatrixWorkspace_sptr dataws,
size_t wsindex) {
if (dataws) {
m_dataWS = dataws;
} else {
throw runtime_error("Input dataws is null. ");
}
if (wsindex < m_dataWS->getNumberHistograms()) {
m_wsIndex = wsindex;
} else {
throw runtime_error("Input workspace index is out of range.");
}
}
//----------------------------------------------------------------------------------------------
/** Set peaks
*/
void FitOneSinglePeak::setFunctions(IPeakFunction_sptr peakfunc,
IBackgroundFunction_sptr bkgdfunc) {
if (peakfunc)
m_peakFunc = peakfunc;
if (bkgdfunc)
m_bkgdFunc = bkgdfunc;
}
//----------------------------------------------------------------------------------------------
/** Set fit range
* */
void FitOneSinglePeak::setFitWindow(double leftwindow, double rightwindow) {
m_minFitX = leftwindow;
m_maxFitX = rightwindow;
auto &vecX = m_dataWS->x(m_wsIndex);
i_minFitX = getIndex(vecX, m_minFitX);
i_maxFitX = getIndex(vecX, m_maxFitX);
m_peakWindowSet = true;
}
//----------------------------------------------------------------------------------------------
/** Set the range of peak, which served as
* (1) range of valid peak centre
* (2) removing peak for fitting background
* @param xpeakleft :: position (x-value) of the left end of peak
* @param xpeakright :: position (x-value) of the right end of peak
*/
void FitOneSinglePeak::setPeakRange(double xpeakleft, double xpeakright) {
m_minPeakX = xpeakleft;
m_maxPeakX = xpeakright;
auto &vecX = m_dataWS->x(m_wsIndex);
i_minPeakX = getIndex(vecX, m_minPeakX);
i_maxPeakX = getIndex(vecX, m_maxPeakX);
m_peakRangeSet = true;
}
//----------------------------------------------------------------------------------------------
/** Set up fitting method other than default
* @param minimizer :: GSL minimizer (string)
* @param costfunction :: string of the name of the cost function
*/
void FitOneSinglePeak::setFittingMethod(std::string minimizer,
std::string costfunction) {
m_minimizer = minimizer;
if (costfunction == "Chi-Square") {
m_costFunction = "Least squares";
} else if (costfunction == "Rwp") {
m_costFunction = "Rwp";
} else if (costfunction == "Least squares") {
m_costFunction = costfunction;
} else {
stringstream errss;
errss << "FitOneSinglePeak: cost function " << costfunction
<< " is not supported. ";
throw runtime_error(errss.str());
}
m_fitMethodSet = true;
}
//----------------------------------------------------------------------------------------------
/** Set FWHM of the peak by guessing.
* Result is stored to m_vecFWHM
* @param usrwidth :: peak FWHM given by user (in input peak function)
* @param minfwhm :: minimim FWHM in unit of pixel
* @param maxfwhm :: maximum FWHM in unit of pixel
* @param stepsize :: step of FWHM in unit of pixel
* @param fitwithsteppedfwhm :: boolean flag whether setting a series of FWHM
* to guess with
*/
void FitOneSinglePeak::setupGuessedFWHM(double usrwidth, int minfwhm,
int maxfwhm, int stepsize,
bool fitwithsteppedfwhm) {
m_vecFWHM.clear();
// From user specified guess value
if (usrwidth <= 0) {
// Set up default FWHM if user does not give reasonable peak width
m_sstream << "Client inputs user-defined peak width = " << usrwidth
<< "; Automatically reset to 4 as default."
<< "\n";
if (!fitwithsteppedfwhm) {
fitwithsteppedfwhm = true;
minfwhm = 4;
maxfwhm = 4;
stepsize = 1;
} else {
if (minfwhm > 4) {
minfwhm = 4;
}
if (maxfwhm < minfwhm)
maxfwhm = 4;
}
} else {
m_vecFWHM.push_back(usrwidth);
m_sstream << "Add user defined FWHM = " << usrwidth << "\n";
}
m_peakWidthSet = true;
// From user specified minimum value to maximim value
if (!fitwithsteppedfwhm) {
if (m_vecFWHM.empty())
throw runtime_error("Logic error in setup guessed FWHM. ");
m_sstream << "No FWHM is not guessed by stepped FWHM. "
<< "\n";
return;
}
auto &vecX = m_dataWS->x(m_wsIndex);
int i_centre = static_cast<int>(getIndex(vecX, m_peakFunc->centre()));
int i_maxindex = static_cast<int>(vecX.size()) - 1;
m_sstream << "FWHM to guess. Range = " << minfwhm << ", " << maxfwhm
<< "; Step = " << stepsize << "\n";
if (stepsize == 0 || maxfwhm < minfwhm)
throw runtime_error("FWHM is not given right.");
for (int iwidth = minfwhm; iwidth <= maxfwhm; iwidth += stepsize) {
// There are 3 possible situation: peak at left edge, peak in proper range,
// peak at righ edge
int ileftside = i_centre - iwidth / 2;
if (ileftside < 0)
ileftside = 0;
int irightside = i_centre + iwidth / 2;
if (irightside > i_maxindex)
irightside = i_maxindex;
double in_fwhm = vecX[irightside] - vecX[ileftside];
if (in_fwhm < 1.0E-20) {
m_sstream << "It is impossible to have zero peak width as iCentre = "
<< i_centre << ", iWidth = " << iwidth << "\n"
<< "More information: Spectrum = " << m_wsIndex
<< "; Range of X is " << vecX.front() << ", " << vecX.back()
<< "; Peak centre = " << vecX[i_centre] << "\n";
} else {
m_sstream << "Setup: i_width = " << iwidth << ", i_left = " << ileftside
<< ", i_right = " << irightside << ", FWHM = " << in_fwhm
<< ", i_centre = " << i_centre << ".\n";
}
m_vecFWHM.push_back(in_fwhm);
}
}
//----------------------------------------------------------------------------------------------
/** Set fitted peak parameters' criterial including
* (a) peak position tolerance to the given one, which is more restricted than
* peak range
* @param usepeakpostol :: boolean as the flag to have this restriction
* @param peakpostol :: double as the tolerance of the peak position
*/
void FitOneSinglePeak::setFitPeakCriteria(bool usepeakpostol,
double peakpostol) {
m_usePeakPositionTolerance = usepeakpostol;
if (usepeakpostol) {
m_peakPositionTolerance = fabs(peakpostol);
if (peakpostol < 1.0E-13)
g_log.warning("Peak position tolerance is very tight. ");
}
}
//----------------------------------------------------------------------------------------------
/** Check whether the class object is ready to fit peak
*/
bool FitOneSinglePeak::hasSetupToFitPeak(std::string &errmsg) {
errmsg = "";
if (!m_fitMethodSet)
errmsg += "Fitting method ";
if (!m_peakRangeSet)
errmsg += "Peak range ";
if (!m_peakWidthSet)
errmsg += "Peak width ";
if (!m_peakFunc)
errmsg += "Peak function ";
if (!m_bkgdFunc)
errmsg += "Background function ";
if (!m_dataWS)
errmsg += "Data workspace ";
if (errmsg.size() > 0) {
errmsg = "These parameters have not been set for fitting peak: " + errmsg;
return false;
}
return true;
}
//----------------------------------------------------------------------------------------------
/** Get debug message
*/
std::string FitOneSinglePeak::getDebugMessage() { return m_sstream.str(); }
//----------------------------------------------------------------------------------------------
/** Fit peak with simple schemem
*/
bool FitOneSinglePeak::simpleFit() {
m_numFitCalls = 0;
string errmsg;
if (!hasSetupToFitPeak(errmsg)) {
g_log.error(errmsg);
throw runtime_error("Object has not been set up completely to fit peak.");
}
// Initialize refinement state parameters
m_bestRwp = DBL_MAX;
// Set up a composite function
CompositeFunction_sptr compfunc = boost::make_shared<CompositeFunction>();
compfunc->addFunction(m_peakFunc);
compfunc->addFunction(m_bkgdFunc);
m_sstream << "One-Step-Fit Function: " << compfunc->asString() << "\n";
// Store starting setup
m_bkupPeakFunc = backup(m_peakFunc);
m_bkupBkgdFunc = backup(m_bkgdFunc);
// Fit with different starting values of peak width
size_t numfits = m_vecFWHM.size();
Progress progress(this, 0, 1, numfits);
for (size_t i = 0; i < numfits; ++i) {
// set FWHM
m_sstream << "[SingleStepFit] FWHM = " << m_vecFWHM[i] << "\n";
m_peakFunc->setFwhm(m_vecFWHM[i]);
// fit and process result
double goodndess =
fitFunctionSD(compfunc, m_dataWS, m_wsIndex, m_minFitX, m_maxFitX);
processNStoreFitResult(goodndess, true);
// restore the function parameters
if (i != numfits - 1) {
pop(m_bkupPeakFunc, m_peakFunc);
pop(m_bkupBkgdFunc, m_bkgdFunc);
}
progress.report();
}
// Retrieve the best result stored
pop(m_bestPeakFunc, m_peakFunc);
pop(m_bestBkgdFunc, m_bkgdFunc);
m_finalGoodnessValue = m_bestRwp;
m_sstream << "One-Step-Fit Best (Chi^2 = " << m_bestRwp
<< ") Fitted Function: " << compfunc->asString() << "\n"
<< "Number of calls of Fit = " << m_numFitCalls << "\n";
return false;
}
//----------------------------------------------------------------------------------------------
/** Generate a new temporary workspace for removed background peak
*/
API::MatrixWorkspace_sptr FitOneSinglePeak::genFitWindowWS() {
auto &vecY = m_dataWS->y(m_wsIndex);
size_t size = i_maxFitX - i_minFitX + 1;
size_t ysize = size;
size_t ishift = i_maxFitX + 1;
if (ishift >= vecY.size())
ysize = vecY.size() - i_minFitX;
MatrixWorkspace_sptr purePeakWS =
WorkspaceFactory::Instance().create("Workspace2D", 1, size, ysize);
auto &vecX = m_dataWS->x(m_wsIndex);
auto &vecE = m_dataWS->e(m_wsIndex);
auto &dataX = purePeakWS->mutableX(0);
auto &dataY = purePeakWS->mutableY(0);
auto &dataE = purePeakWS->mutableE(0);
dataX.assign(vecX.cbegin() + i_minFitX, vecX.cbegin() + i_maxFitX + 1);
if (ishift < vecY.size()) {
dataY.assign(vecY.cbegin() + i_minFitX, vecY.cbegin() + i_maxFitX + 1);
dataE.assign(vecE.cbegin() + i_minFitX, vecE.cbegin() + i_maxFitX + 1);
} else {
dataY.assign(vecY.cbegin() + i_minFitX, vecY.cend());
dataE.assign(vecE.cbegin() + i_minFitX, vecE.cend());
}
return purePeakWS;
}
//----------------------------------------------------------------------------------------------
/** Estimate the peak height from a set of data containing pure peaks
*/
double FitOneSinglePeak::estimatePeakHeight(
API::IPeakFunction_const_sptr peakfunc, MatrixWorkspace_sptr dataws,
size_t wsindex, size_t ixmin, size_t ixmax) {
// Get current peak height: from current peak centre (previously setup)
double peakcentre = peakfunc->centre();
vector<double> svvec(1, peakcentre);
FunctionDomain1DVector svdomain(svvec);
FunctionValues svvalues(svdomain);
peakfunc->function(svdomain, svvalues);
double curpeakheight = svvalues[0];
auto &vecX = dataws->x(wsindex);
auto &vecY = dataws->y(wsindex);
double ymax = vecY[ixmin + 1];
size_t iymax = ixmin + 1;
for (size_t i = ixmin + 2; i < ixmax; ++i) {
double tempy = vecY[i];
if (tempy > ymax) {
ymax = tempy;
iymax = i;
}
}
m_sstream << "Estimate-Peak-Height: Current peak height = " << curpeakheight
<< ". Estimate-Peak-Height: Maximum Y value between " << vecX[ixmin]
<< " and " << vecX[ixmax] << " is " << ymax
<< " at X = " << vecX[iymax] << ".\n";
// Compute peak height (not the maximum peak intensity)
double estheight = ymax / curpeakheight * peakfunc->height();
return estheight;
}
//----------------------------------------------------------------------------------------------
/** Make a pure peak WS in the fit window region from m_background_function
* @param purePeakWS :: workspace containing pure peak (w/ background removed)
*/
void FitOneSinglePeak::removeBackground(MatrixWorkspace_sptr purePeakWS) {
// Calculate background
// FIXME - This can be costly to use FunctionDomain and FunctionValue
auto &vecX = purePeakWS->x(0);
FunctionDomain1DVector domain(MantidVec(vecX.begin(), vecX.end()));
FunctionValues bkgdvalues(domain);
m_bkgdFunc->function(domain, bkgdvalues);
// Calculate pure background and put weight on peak if using Rwp
purePeakWS->mutableE(0).assign(purePeakWS->y(0).size(), 1.0);
size_t i = 0;
std::transform(purePeakWS->y(0).cbegin(), purePeakWS->y(0).cend(),
purePeakWS->mutableY(0).begin(), [=](const double &y) mutable {
double newY = y - bkgdvalues[i++];
return std::max(0.0, newY);
});
}
//----------------------------------------------------------------------------------------------
/** Fit peak function (only. so must be pure peak).
* In this function, the fit result will be examined if fit is 'successful' in
* order to rule out
* some fit with unphysical result.
* @return :: chi-square/Rwp
*/
double FitOneSinglePeak::fitPeakFunction(API::IPeakFunction_sptr peakfunc,
MatrixWorkspace_sptr dataws,
size_t wsindex, double startx,
double endx) {
// Check validity and debug output
if (!peakfunc)
throw std::runtime_error(
"fitPeakFunction's input peakfunc has not been initialized.");
m_sstream << "Function (to fit): " << peakfunc->asString() << " From "
<< startx << " to " << endx << ".\n";
double goodness = fitFunctionSD(peakfunc, dataws, wsindex, startx, endx);
return goodness;
}
//-----------------------------------------------------------------------
//----------------------
/** Fit peak with high background
* Procedure:
* 1. Fit background
* 2. Create a new workspace with limited region
*/
void FitOneSinglePeak::highBkgdFit() {
m_numFitCalls = 0;
// Check and initialization
string errmsg;
if (!hasSetupToFitPeak(errmsg)) {
g_log.error(errmsg);
throw runtime_error("Object has not been set up completely to fit peak.");
} else {
m_sstream << "F1158: Well-setup and good to go!\n";
}
m_bestRwp = DBL_MAX;
// Fit background
if (i_minFitX == i_minPeakX || i_maxPeakX == i_maxFitX) {
// User's input peak range cannot be trusted. Data might be noisy
stringstream outss;
outss << "User specified peak range cannot be trusted! Because peak range "
"overlap fit window. "
<< "Number of data points in fitting window = "
<< i_maxFitX - i_minFitX
<< ". A UNRELIABLE algorithm is used to guess peak range. ";
g_log.warning(outss.str());
size_t numpts = i_maxFitX - i_minFitX;
size_t shift = static_cast<size_t>(static_cast<double>(numpts) / 6.);
i_minPeakX += shift;
auto Xdata = m_dataWS->x(m_wsIndex);
if (i_minPeakX >= Xdata.size())
i_minPeakX = Xdata.size() - 1;
m_minPeakX = Xdata[i_minPeakX];
if (i_maxPeakX < shift) {
i_maxPeakX = 0;
} else {
i_maxPeakX -= shift;
}
m_maxPeakX = Xdata[i_maxPeakX];
}
m_bkgdFunc = fitBackground(m_bkgdFunc);
// Generate partial workspace within given fit window
MatrixWorkspace_sptr purePeakWS = genFitWindowWS();
// Remove background to make a pure peak
removeBackground(purePeakWS);
// Estimate the peak height
double est_peakheight = estimatePeakHeight(m_peakFunc, purePeakWS, 0, 0,
purePeakWS->x(0).size() - 1);
m_peakFunc->setHeight(est_peakheight);
// Store starting setup
m_bkupPeakFunc = backup(m_peakFunc);
Progress progress(this, 0, 1, m_vecFWHM.size());
// Fit with different starting values of peak width
for (size_t i = 0; i < m_vecFWHM.size(); ++i) {
// Restore
if (i > 0)
pop(m_bkupPeakFunc, m_peakFunc);
// Set FWHM
m_peakFunc->setFwhm(m_vecFWHM[i]);
m_sstream << "Round " << i << " of " << m_vecFWHM.size()
<< ". Using proposed FWHM = " << m_vecFWHM[i] << "\n";
// Fit
double rwp =
fitPeakFunction(m_peakFunc, purePeakWS, 0, m_minFitX, m_maxFitX);
m_sstream << "Fit peak function cost = " << rwp << "\n";
// Store result
processNStoreFitResult(rwp, false);
progress.report();
}
// Get best fitting peak function and Make a combo fit
pop(m_bestPeakFunc, m_peakFunc);
// Fit the composite function as final
double compcost = fitCompositeFunction(m_peakFunc, m_bkgdFunc, m_dataWS,
m_wsIndex, m_minFitX, m_maxFitX);
m_bestRwp = compcost;
m_sstream << "MultStep-Fit: Best Fitted Peak: " << m_peakFunc->asString()
<< ". Final " << m_costFunction << " = " << compcost << "\n"
<< "Number of calls on Fit = " << m_numFitCalls << "\n";
}
//----------------------------------------------------------------------------------------------
/** Push/store a fit result (function) to storage
* @param func :: function to get parameter values stored
* @returns :: map to store function parameter's names and value
*/
std::map<std::string, double>
FitOneSinglePeak::backup(IFunction_const_sptr func) {
std::map<std::string, double> funcparammap;
// Set up
vector<string> funcparnames = func->getParameterNames();
size_t nParam = funcparnames.size();
for (size_t i = 0; i < nParam; ++i) {
double parvalue = func->getParameter(i);
funcparammap.emplace(funcparnames[i], parvalue);
}
return funcparammap;
}
//----------------------------------------------------------------------------------------------
/** Push/store function parameters' error resulted from fitting
* @param func :: function to get parameter values stored
* @returns :: map to store function parameter's names and fitting
* error
*/
std::map<std::string, double>
FitOneSinglePeak::storeFunctionError(const IFunction_const_sptr &func) {
// output map
std::map<std::string, double> paramerrormap;
// Get function error and store in output map
vector<string> funcparnames = func->getParameterNames();
size_t nParam = funcparnames.size();
for (size_t i = 0; i < nParam; ++i) {
double parerror = func->getError(i);
paramerrormap.emplace(funcparnames[i], parerror);
}
return paramerrormap;
}
//----------------------------------------------------------------------------------------------
/** Restore the parameters value to a function from a string/double map
*/
void FitOneSinglePeak::pop(const std::map<std::string, double> &funcparammap,
API::IFunction_sptr func) {
std::map<std::string, double>::const_iterator miter;
for (miter = funcparammap.begin(); miter != funcparammap.end(); ++miter) {
string parname = miter->first;
double parvalue = miter->second;
func->setParameter(parname, parvalue);
}
}
//----------------------------------------------------------------------------------------------
/** Calcualte chi-square for single domain data
* @brief FitOneSinglePeak::calChiSquareSD
* @param fitfunc
* @param dataws
* @param wsindex
* @param xmin
* @param xmax
* @return
*/
double FitOneSinglePeak::calChiSquareSD(IFunction_sptr fitfunc,
MatrixWorkspace_sptr dataws,
size_t wsindex, double xmin,
double xmax) {
// Set up sub algorithm fit
IAlgorithm_sptr fit;
try {
fit = createChildAlgorithm("CalculateChiSquared", -1, -1, false);
} catch (Exception::NotFoundError &) {
std::stringstream errss;
errss << "The FitPeak algorithm requires the CurveFitting library";
g_log.error(errss.str());
throw std::runtime_error(errss.str());
}
// Set the properties
fit->setProperty("Function", fitfunc);
fit->setProperty("InputWorkspace", dataws);
fit->setProperty("WorkspaceIndex", static_cast<int>(wsindex));
fit->setProperty("StartX", xmin);
fit->setProperty("EndX", xmax);
fit->executeAsChildAlg();
if (!fit->isExecuted()) {
g_log.error("Fit for background is not executed. ");
throw std::runtime_error("Fit for background is not executed. ");
}
// Retrieve result
const double chi2 = fit->getProperty("ChiSquaredWeightedDividedByNData");
return chi2;
}
//----------------------------------------------------------------------------------------------
/** Fit function in single domain
* @exception :: (1) Fit cannot be called. (2) Fit.isExecuted is false (cannot
* be executed)
* @return :: chi^2 or Rwp depending on input. If fit is not SUCCESSFUL,
* return DBL_MAX
*/
double FitOneSinglePeak::fitFunctionSD(IFunction_sptr fitfunc,
MatrixWorkspace_sptr dataws,
size_t wsindex, double xmin,
double xmax) {
// Set up sub algorithm fit
IAlgorithm_sptr fit;
try {
fit = createChildAlgorithm("Fit", -1, -1, false);
} catch (Exception::NotFoundError &) {
std::stringstream errss;
errss << "The FitPeak algorithm requires the CurveFitting library";
g_log.error(errss.str());
throw std::runtime_error(errss.str());
}
// Set the properties
fit->setProperty("Function", fitfunc);
fit->setProperty("InputWorkspace", dataws);
fit->setProperty("WorkspaceIndex", static_cast<int>(wsindex));
fit->setProperty("MaxIterations", 50); // magic number
fit->setProperty("StartX", xmin);
fit->setProperty("EndX", xmax);
fit->setProperty("Minimizer", m_minimizer);
fit->setProperty("CostFunction", m_costFunction);
fit->setProperty("CalcErrors", true);
// Execute fit and get result of fitting background
m_sstream << "FitSingleDomain: " << fit->asString() << ".\n";
fit->executeAsChildAlg();
if (!fit->isExecuted()) {
g_log.error("Fit for background is not executed. ");
throw std::runtime_error("Fit for background is not executed. ");
}
++m_numFitCalls;
// Retrieve result
std::string fitStatus = fit->getProperty("OutputStatus");
double chi2 = EMPTY_DBL();
if (fitStatus == "success") {
chi2 = fit->getProperty("OutputChi2overDoF");
fitfunc = fit->getProperty("Function");
}
// Debug information
m_sstream << "[F1201] FitSingleDomain Fitted-Function " << fitfunc->asString()
<< ": Fit-status = " << fitStatus << ", chi^2 = " << chi2 << ".\n";
return chi2;
}
//----------------------------------------------------------------------------------------------
/** Fit function in multi-domain
* @param fitfunc :: function to fit
* @param dataws :: matrix workspace to fit with
* @param wsindex :: workspace index of the spectrum in matrix workspace
* @param vec_xmin :: minimin values of domains
* @param vec_xmax :: maximim values of domains
*/
double FitOneSinglePeak::fitFunctionMD(IFunction_sptr fitfunc,
MatrixWorkspace_sptr dataws,
size_t wsindex, vector<double> vec_xmin,
vector<double> vec_xmax) {
// Validate
if (vec_xmin.size() != vec_xmax.size())
throw runtime_error("Sizes of xmin and xmax (vectors) are not equal. ");
// Set up sub algorithm fit
IAlgorithm_sptr fit;
try {
fit = createChildAlgorithm("Fit", -1, -1, true);
} catch (Exception::NotFoundError &) {
std::stringstream errss;
errss << "The FitPeak algorithm requires the CurveFitting library";
g_log.error(errss.str());
throw std::runtime_error(errss.str());
}
// This use multi-domain; but does not know how to set up
boost::shared_ptr<MultiDomainFunction> funcmd =
boost::make_shared<MultiDomainFunction>();
// Set function first
funcmd->addFunction(fitfunc);
// set domain for function with index 0 covering both sides
funcmd->clearDomainIndices();
std::vector<size_t> ii(2);
ii[0] = 0;
ii[1] = 1;
funcmd->setDomainIndices(0, ii);
// Set the properties
fit->setProperty("Function", boost::dynamic_pointer_cast<IFunction>(funcmd));
fit->setProperty("InputWorkspace", dataws);
fit->setProperty("WorkspaceIndex", static_cast<int>(wsindex));
fit->setProperty("StartX", vec_xmin[0]);
fit->setProperty("EndX", vec_xmax[0]);
fit->setProperty("InputWorkspace_1", dataws);
fit->setProperty("WorkspaceIndex_1", static_cast<int>(wsindex));
fit->setProperty("StartX_1", vec_xmin[1]);
fit->setProperty("EndX_1", vec_xmax[1]);
fit->setProperty("MaxIterations", 50);
fit->setProperty("Minimizer", m_minimizer);
fit->setProperty("CostFunction", "Least squares");
m_sstream << "FitMultiDomain: Funcion " << funcmd->name() << ": "
<< "Range: (" << vec_xmin[0] << ", " << vec_xmax[0] << ") and ("
<< vec_xmin[1] << ", " << vec_xmax[1] << "); " << funcmd->asString()
<< "\n";
// Execute
fit->execute();
if (!fit->isExecuted()) {
throw runtime_error("Fit is not executed on multi-domain function/data. ");
}
++m_numFitCalls;
// Retrieve result
std::string fitStatus = fit->getProperty("OutputStatus");
m_sstream << "[DB] Multi-domain fit status: " << fitStatus << ".\n";
double chi2 = EMPTY_DBL();
if (fitStatus == "success") {
chi2 = fit->getProperty("OutputChi2overDoF");
m_sstream << "FitMultidomain: Successfully-Fitted Function "
<< fitfunc->asString() << ", Chi^2 = " << chi2 << "\n";
}
return chi2;
}
//----------------------------------------------------------------------------------------------
/** Fit peak function and background function as composite function
* @param peakfunc :: peak function to fit
* @param bkgdfunc :: background function to fit
* @param dataws :: matrix workspace to fit with
* @param wsindex :: workspace index of the spectrum in matrix workspace
* @param startx :: minimum x value of the fitting window
* @param endx :: maximum x value of the fitting window
* @return :: Rwp/chi2
*/
double FitOneSinglePeak::fitCompositeFunction(
API::IPeakFunction_sptr peakfunc, API::IBackgroundFunction_sptr bkgdfunc,
API::MatrixWorkspace_sptr dataws, size_t wsindex, double startx,
double endx) {
// Construct composit function
boost::shared_ptr<CompositeFunction> compfunc =
boost::make_shared<CompositeFunction>();
compfunc->addFunction(peakfunc);
compfunc->addFunction(bkgdfunc);
// Do calculation for starting chi^2/Rwp: as the assumption that the input the
// so far the best Rwp
// FIXME - This is not a good practise...
double backRwp = calChiSquareSD(bkgdfunc, dataws, wsindex, startx, endx);
m_sstream << "Background: Pre-fit Goodness = " << backRwp << "\n";
m_bestRwp = calChiSquareSD(compfunc, dataws, wsindex, startx, endx);
m_sstream << "Peak+Background: Pre-fit Goodness = " << m_bestRwp << "\n";
auto bkuppeakmap = backup(peakfunc);
auto bkupbkgdmap = backup(bkgdfunc);
m_fitErrorPeakFunc = storeFunctionError(peakfunc);
m_fitErrorBkgdFunc = storeFunctionError(bkgdfunc);
// Fit
double goodness = fitFunctionSD(compfunc, dataws, wsindex, startx, endx);
string errorreason;
// Check fit result
goodness = checkFittedPeak(peakfunc, goodness, errorreason);
if (errorreason.size() > 0)
m_sstream << "Error reason of fit peak+background composite: "
<< errorreason << "\n";
double goodness_final = DBL_MAX;
if (goodness <= m_bestRwp && goodness <= backRwp) {
// Fit for composite function renders a better result
goodness_final = goodness;
processNStoreFitResult(goodness_final, true);
} else if (goodness > m_bestRwp && m_bestRwp < DBL_MAX &&
m_bestRwp <= backRwp) {
// A worse result is got. Revert to original function parameters
m_sstream << "Fit peak/background composite function FAILS to render a "
"better solution. "
<< "Input cost function value = " << m_bestRwp
<< ", output cost function value = " << goodness << "\n";
pop(bkuppeakmap, peakfunc);
pop(bkupbkgdmap, bkgdfunc);
goodness_final = m_bestRwp;
} else {
m_sstream << "Fit peak-background function fails in all approaches! \n";
}
return goodness_final;
}
//----------------------------------------------------------------------------------------------
/** Check the fitted peak value to see whether it is valid
* @return :: Rwp/chi2
*/
double FitOneSinglePeak::checkFittedPeak(IPeakFunction_sptr peakfunc,
double costfuncvalue,
std::string &errorreason) {
if (costfuncvalue < DBL_MAX) {
// Fit is successful. Check whether the fit result is physical
stringstream errorss;
double peakcentre = peakfunc->centre();
if (peakcentre < m_minPeakX || peakcentre > m_maxPeakX) {
errorss << "Peak centre (at " << peakcentre
<< " ) is out of specified range )" << m_minPeakX << ", "
<< m_maxPeakX << "). ";
costfuncvalue = DBL_MAX;
}
double peakheight = peakfunc->height();
if (peakheight < 0) {
errorss << "Peak height (" << peakheight << ") is negative. ";
costfuncvalue = DBL_MAX;
}
double peakfwhm = peakfunc->fwhm();
if (peakfwhm > (m_maxFitX - m_minFitX) * MAGICNUMBER) {
errorss << "Peak width is unreasonably wide. ";
costfuncvalue = DBL_MAX;
}
errorreason = errorss.str();
} else {
// Fit is not successful
errorreason = "Fit() on peak function is NOT successful.";
}
return costfuncvalue;
}
//----------------------------------------------------------------------------------------------
/** Fit background of a given peak in a given range
* @param bkgdfunc :: background function to fit
* @return :: background function fitted
*/
API::IBackgroundFunction_sptr
FitOneSinglePeak::fitBackground(API::IBackgroundFunction_sptr bkgdfunc) {
// Back up background function
m_bkupBkgdFunc = backup(bkgdfunc);
// Fit in multiple domain
vector<double> vec_xmin(2);
vector<double> vec_xmax(2);
vec_xmin[0] = m_minFitX;
vec_xmin[1] = m_maxPeakX;
vec_xmax[0] = m_minPeakX;
vec_xmax[1] = m_maxFitX;
double chi2 = fitFunctionMD(boost::dynamic_pointer_cast<IFunction>(bkgdfunc),
m_dataWS, m_wsIndex, vec_xmin, vec_xmax);
// Process fit result
if (chi2 < DBL_MAX - 1) {
// Store fitting result
m_bestBkgdFunc = backup(bkgdfunc);
m_fitErrorBkgdFunc = storeFunctionError(bkgdfunc);
} else {
// Restore background function
pop(m_bkupBkgdFunc, bkgdfunc);
}
return bkgdfunc;
}
//----------------------------------------------------------------------------------------------
/** Process and store fitting reuslt
* @param rwp :: Rwp of the fitted function to the data
* @param storebkgd :: flag to store the background function value or not
*/
void FitOneSinglePeak::processNStoreFitResult(double rwp, bool storebkgd) {
bool fitsuccess = true;
string failreason;
if (rwp < DBL_MAX) {
// A valid Rwp returned from Fit
// Check non-negative height
double f_height = m_peakFunc->height();
if (f_height <= 0.) {
rwp = DBL_MAX;
failreason += "Negative peak height. ";
fitsuccess = false;
}
// Check peak position
double f_centre = m_peakFunc->centre();
if (m_usePeakPositionTolerance) {
// Peak position criteria is on position tolerance
if (fabs(f_centre - m_userPeakCentre) > m_peakPositionTolerance) {
rwp = DBL_MAX;
failreason = "Peak centre out of tolerance. ";
fitsuccess = false;
}
} else if (f_centre < m_minPeakX || f_centre > m_maxPeakX) {
rwp = DBL_MAX;
failreason += "Peak centre out of input peak range ";
m_sstream << "Peak centre " << f_centre
<< " is out of peak range: " << m_minPeakX << ", " << m_maxPeakX
<< "\n";
fitsuccess = false;
}
} // RWP fine
else {
failreason = "(Single-step) Fit returns a DBL_MAX.";
fitsuccess = false;
}
m_sstream << "Process fit result: "
<< "Rwp = " << rwp << ", best Rwp = " << m_bestRwp
<< ", Fit success = " << fitsuccess << ". ";
// Store result if
if (rwp < m_bestRwp && fitsuccess) {
m_bestPeakFunc = backup(m_peakFunc);
m_fitErrorPeakFunc = storeFunctionError(m_peakFunc);
if (storebkgd) {
m_bestBkgdFunc = backup(m_bkgdFunc);
m_fitErrorBkgdFunc = storeFunctionError(m_bkgdFunc);
}
m_bestRwp = rwp;
m_sstream << "Store result and new Best RWP = " << m_bestRwp << ".\n";
} else if (!fitsuccess) {
m_sstream << "Reason of fit's failure: " << failreason << "\n";
}
}
//----------------------------------------------------------------------------------------------
/** Get the cost function value of the best fit