-
Notifications
You must be signed in to change notification settings - Fork 122
/
FitPeaks.cpp
2104 lines (1825 loc) · 90.5 KB
/
FitPeaks.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 "MantidAlgorithms/FitPeaks.h"
#include "MantidAPI/Axis.h"
#include "MantidAPI/CompositeFunction.h"
#include "MantidAPI/CostFunctionFactory.h"
#include "MantidAPI/FrameworkManager.h"
#include "MantidAPI/FuncMinimizerFactory.h"
#include "MantidAPI/FunctionFactory.h"
#include "MantidAPI/FunctionProperty.h"
#include "MantidAPI/MultiDomainFunction.h"
#include "MantidAPI/TableRow.h"
#include "MantidAPI/WorkspaceProperty.h"
#include "MantidAlgorithms/FindPeakBackground.h"
#include "MantidDataObjects/TableWorkspace.h"
#include "MantidDataObjects/Workspace2D.h"
#include "MantidDataObjects/WorkspaceCreation.h"
#include "MantidGeometry/IDetector.h"
#include "MantidGeometry/Instrument/Detector.h"
#include "MantidHistogramData/EstimatePolynomial.h"
#include "MantidHistogramData/Histogram.h"
#include "MantidHistogramData/HistogramBuilder.h"
#include "MantidHistogramData/HistogramIterator.h"
#include "MantidKernel/ArrayProperty.h"
#include "MantidKernel/BoundedValidator.h"
#include "MantidKernel/IValidator.h"
#include "MantidKernel/ListValidator.h"
#include "MantidKernel/StartsWithValidator.h"
#include "boost/algorithm/string.hpp"
#include "boost/algorithm/string/trim.hpp"
#include <limits>
#include <utility>
using namespace Mantid;
using namespace Algorithms::PeakParameterHelper;
using namespace Mantid::API;
using namespace Mantid::DataObjects;
using namespace Mantid::HistogramData;
using namespace Mantid::Kernel;
using namespace Mantid::Geometry;
using Mantid::HistogramData::Histogram;
using namespace std;
namespace Mantid {
namespace Algorithms {
namespace {
namespace PropertyNames {
const std::string INPUT_WKSP("InputWorkspace");
const std::string OUTPUT_WKSP("OutputWorkspace");
const std::string START_WKSP_INDEX("StartWorkspaceIndex");
const std::string STOP_WKSP_INDEX("StopWorkspaceIndex");
const std::string PEAK_CENTERS("PeakCenters");
const std::string PEAK_CENTERS_WKSP("PeakCentersWorkspace");
const std::string PEAK_FUNC("PeakFunction");
const std::string BACK_FUNC("BackgroundType");
const std::string FIT_WINDOW_LIST("FitWindowBoundaryList");
const std::string FIT_WINDOW_WKSP("FitPeakWindowWorkspace");
const std::string PEAK_WIDTH_PERCENT("PeakWidthPercent");
const std::string PEAK_PARAM_NAMES("PeakParameterNames");
const std::string PEAK_PARAM_VALUES("PeakParameterValues");
const std::string PEAK_PARAM_TABLE("PeakParameterValueTable");
const std::string FIT_FROM_RIGHT("FitFromRight");
const std::string MINIMIZER("Minimizer");
const std::string COST_FUNC("CostFunction");
const std::string MAX_FIT_ITER("MaxFitIterations");
const std::string BACKGROUND_Z_SCORE("FindBackgroundSigma");
const std::string HIGH_BACKGROUND("HighBackground");
const std::string POSITION_TOL("PositionTolerance");
const std::string PEAK_MIN_HEIGHT("MinimumPeakHeight");
const std::string CONSTRAIN_PEAK_POS("ConstrainPeakPositions");
const std::string OUTPUT_WKSP_MODEL("FittedPeaksWorkspace");
const std::string OUTPUT_WKSP_PARAMS("OutputPeakParametersWorkspace");
const std::string OUTPUT_WKSP_PARAM_ERRS("OutputParameterFitErrorsWorkspace");
const std::string RAW_PARAMS("RawPeakParameters");
} // namespace PropertyNames
} // namespace
namespace FitPeaksAlgorithm {
//----------------------------------------------------------------------------------------------
/// Holds all of the fitting information for a single spectrum
PeakFitResult::PeakFitResult(size_t num_peaks, size_t num_params) : m_function_parameters_number(num_params) {
// check input
if (num_peaks == 0 || num_params == 0)
throw std::runtime_error("No peak or no parameter error.");
//
m_fitted_peak_positions.resize(num_peaks, std::numeric_limits<double>::quiet_NaN());
m_costs.resize(num_peaks, DBL_MAX);
m_function_parameters_vector.resize(num_peaks);
m_function_errors_vector.resize(num_peaks);
for (size_t ipeak = 0; ipeak < num_peaks; ++ipeak) {
m_function_parameters_vector[ipeak].resize(num_params, std::numeric_limits<double>::quiet_NaN());
m_function_errors_vector[ipeak].resize(num_params, std::numeric_limits<double>::quiet_NaN());
}
return;
}
//----------------------------------------------------------------------------------------------
size_t PeakFitResult::getNumberParameters() const { return m_function_parameters_number; }
size_t PeakFitResult::getNumberPeaks() const { return m_function_parameters_vector.size(); }
//----------------------------------------------------------------------------------------------
/** get the fitting error of a particular parameter
* @param ipeak :: index of the peak in given peak position vector
* @param iparam :: index of the parameter in its corresponding peak profile
* function
* @return :: fitting error/uncertain of the specified parameter
*/
double PeakFitResult::getParameterError(size_t ipeak, size_t iparam) const {
return m_function_errors_vector[ipeak][iparam];
}
//----------------------------------------------------------------------------------------------
/** get the fitted value of a particular parameter
* @param ipeak :: index of the peak in given peak position vector
* @param iparam :: index of the parameter in its corresponding peak profile
* function
* @return :: fitted value of the specified parameter
*/
double PeakFitResult::getParameterValue(size_t ipeak, size_t iparam) const {
return m_function_parameters_vector[ipeak][iparam];
}
//----------------------------------------------------------------------------------------------
double PeakFitResult::getPeakPosition(size_t ipeak) const { return m_fitted_peak_positions[ipeak]; }
//----------------------------------------------------------------------------------------------
double PeakFitResult::getCost(size_t ipeak) const { return m_costs[ipeak]; }
//----------------------------------------------------------------------------------------------
/// set the peak fitting record/parameter for one peak
void PeakFitResult::setRecord(size_t ipeak, const double cost, const double peak_position,
const FitFunction &fit_functions) {
// check input
if (ipeak >= m_costs.size())
throw std::runtime_error("Peak index is out of range.");
// set the values
m_costs[ipeak] = cost;
// set peak position
m_fitted_peak_positions[ipeak] = peak_position;
// transfer from peak function to vector
size_t peak_num_params = fit_functions.peakfunction->nParams();
for (size_t ipar = 0; ipar < peak_num_params; ++ipar) {
// peak function
m_function_parameters_vector[ipeak][ipar] = fit_functions.peakfunction->getParameter(ipar);
m_function_errors_vector[ipeak][ipar] = fit_functions.peakfunction->getError(ipar);
}
for (size_t ipar = 0; ipar < fit_functions.bkgdfunction->nParams(); ++ipar) {
// background function
m_function_parameters_vector[ipeak][ipar + peak_num_params] = fit_functions.bkgdfunction->getParameter(ipar);
m_function_errors_vector[ipeak][ipar + peak_num_params] = fit_functions.bkgdfunction->getError(ipar);
}
}
//----------------------------------------------------------------------------------------------
/** The peak postition should be negative and indicates what went wrong
* @param ipeak :: index of the peak in user-specified peak position vector
* @param peak_position :: bad peak position indicating reason of bad fit
*/
void PeakFitResult::setBadRecord(size_t ipeak, const double peak_position) {
// check input
if (ipeak >= m_costs.size())
throw std::runtime_error("Peak index is out of range");
if (peak_position >= 0.)
throw std::runtime_error("Can only set negative postion for bad record");
// set the values
m_costs[ipeak] = DBL_MAX;
// set peak position
m_fitted_peak_positions[ipeak] = peak_position;
// transfer from peak function to vector
for (size_t ipar = 0; ipar < m_function_parameters_number; ++ipar) {
m_function_parameters_vector[ipeak][ipar] = 0.;
m_function_errors_vector[ipeak][ipar] = std::numeric_limits<double>::quiet_NaN();
}
}
} // namespace FitPeaksAlgorithm
//----------------------------------------------------------------------------------------------
FitPeaks::FitPeaks()
: m_fitPeaksFromRight(true), m_fitIterations(50), m_numPeaksToFit(0), m_minPeakHeight(20.), m_bkgdSimga(1.),
m_peakPosTolCase234(false) {}
//----------------------------------------------------------------------------------------------
/** initialize the properties
*/
void FitPeaks::init() {
declareProperty(std::make_unique<WorkspaceProperty<MatrixWorkspace>>(PropertyNames::INPUT_WKSP, "", Direction::Input),
"Name of the input workspace for peak fitting.");
declareProperty(
std::make_unique<WorkspaceProperty<MatrixWorkspace>>(PropertyNames::OUTPUT_WKSP, "", Direction::Output),
"Name of the output workspace containing peak centers for "
"fitting offset."
"The output workspace is point data."
"Each workspace index corresponds to a spectrum. "
"Each X value ranges from 0 to N-1, where N is the number of "
"peaks to fit. "
"Each Y value is the peak position obtained by peak fitting. "
"Negative value is used for error signals. "
"-1 for data is zero; -2 for maximum value is smaller than "
"specified minimum value."
"and -3 for non-converged fitting.");
// properties about fitting range and criteria
declareProperty(PropertyNames::START_WKSP_INDEX, EMPTY_INT(), "Starting workspace index for fit");
declareProperty(PropertyNames::STOP_WKSP_INDEX, EMPTY_INT(),
"Last workspace index to fit (which is included). "
"If a value larger than the workspace index of last spectrum, "
"then the workspace index of last spectrum is used.");
// properties about peak positions to fit
declareProperty(std::make_unique<ArrayProperty<double>>(PropertyNames::PEAK_CENTERS),
"List of peak centers to fit against.");
declareProperty(std::make_unique<WorkspaceProperty<MatrixWorkspace>>(PropertyNames::PEAK_CENTERS_WKSP, "",
Direction::Input, PropertyMode::Optional),
"MatrixWorkspace containing peak centers");
const std::string peakcentergrp("Peak Positions");
setPropertyGroup(PropertyNames::PEAK_CENTERS, peakcentergrp);
setPropertyGroup(PropertyNames::PEAK_CENTERS_WKSP, peakcentergrp);
// properties about peak profile
const std::vector<std::string> peakNames = FunctionFactory::Instance().getFunctionNames<API::IPeakFunction>();
declareProperty(PropertyNames::PEAK_FUNC, "Gaussian", std::make_shared<StringListValidator>(peakNames),
"Use of a BackToBackExponential profile is only reccomended if the "
"coeficients to calculate A and B are defined in the instrument "
"Parameters.xml file.");
const vector<string> bkgdtypes{"Flat", "Linear", "Quadratic"};
declareProperty(PropertyNames::BACK_FUNC, "Linear", std::make_shared<StringListValidator>(bkgdtypes),
"Type of Background.");
const std::string funcgroup("Function Types");
setPropertyGroup(PropertyNames::PEAK_FUNC, funcgroup);
setPropertyGroup(PropertyNames::BACK_FUNC, funcgroup);
// properties about peak range including fitting window and peak width
// (percentage)
declareProperty(std::make_unique<ArrayProperty<double>>(PropertyNames::FIT_WINDOW_LIST),
"List of left boundaries of the peak fitting window corresponding to "
"PeakCenters.");
declareProperty(std::make_unique<WorkspaceProperty<MatrixWorkspace>>(PropertyNames::FIT_WINDOW_WKSP, "",
Direction::Input, PropertyMode::Optional),
"MatrixWorkspace for of peak windows");
auto min = std::make_shared<BoundedValidator<double>>();
min->setLower(1e-3);
// min->setUpper(1.); TODO make this a limit
declareProperty(PropertyNames::PEAK_WIDTH_PERCENT, EMPTY_DBL(), min,
"The estimated peak width as a "
"percentage of the d-spacing "
"of the center of the peak. Value must be less than 1.");
const std::string fitrangeegrp("Peak Range Setup");
setPropertyGroup(PropertyNames::PEAK_WIDTH_PERCENT, fitrangeegrp);
setPropertyGroup(PropertyNames::FIT_WINDOW_LIST, fitrangeegrp);
setPropertyGroup(PropertyNames::FIT_WINDOW_WKSP, fitrangeegrp);
// properties about peak parameters' names and value
declareProperty(std::make_unique<ArrayProperty<std::string>>(PropertyNames::PEAK_PARAM_NAMES),
"List of peak parameters' names");
declareProperty(std::make_unique<ArrayProperty<double>>(PropertyNames::PEAK_PARAM_VALUES),
"List of peak parameters' value");
declareProperty(std::make_unique<WorkspaceProperty<TableWorkspace>>(PropertyNames::PEAK_PARAM_TABLE, "",
Direction::Input, PropertyMode::Optional),
"Name of the an optional workspace, whose each column "
"corresponds to given peak parameter names"
", and each row corresponds to a subset of spectra.");
const std::string startvaluegrp("Starting Parameters Setup");
setPropertyGroup(PropertyNames::PEAK_PARAM_NAMES, startvaluegrp);
setPropertyGroup(PropertyNames::PEAK_PARAM_VALUES, startvaluegrp);
setPropertyGroup(PropertyNames::PEAK_PARAM_TABLE, startvaluegrp);
// optimization setup
declareProperty(PropertyNames::FIT_FROM_RIGHT, true,
"Flag for the order to fit peaks. If true, peaks are fitted "
"from rightmost;"
"Otherwise peaks are fitted from leftmost.");
const std::vector<std::string> minimizerOptions = API::FuncMinimizerFactory::Instance().getKeys();
declareProperty(PropertyNames::MINIMIZER, "Levenberg-Marquardt",
Kernel::IValidator_sptr(new Kernel::StartsWithValidator(minimizerOptions)),
"Minimizer to use for fitting.");
const std::array<string, 2> costFuncOptions = {{"Least squares", "Rwp"}};
declareProperty(PropertyNames::COST_FUNC, "Least squares",
Kernel::IValidator_sptr(new Kernel::ListValidator<std::string>(costFuncOptions)), "Cost functions");
auto min_max_iter = std::make_shared<BoundedValidator<int>>();
min_max_iter->setLower(49);
declareProperty(PropertyNames::MAX_FIT_ITER, 50, min_max_iter, "Maximum number of function fitting iterations.");
const std::string optimizergrp("Optimization Setup");
setPropertyGroup(PropertyNames::MINIMIZER, optimizergrp);
setPropertyGroup(PropertyNames::COST_FUNC, optimizergrp);
// other helping information
declareProperty(PropertyNames::BACKGROUND_Z_SCORE, 1.0,
"Multiplier of standard deviations of the variance for convergence of "
"peak elimination. Default is 1.0. ");
declareProperty(PropertyNames::HIGH_BACKGROUND, true,
"Flag whether the data has high background comparing to "
"peaks' intensities. "
"For example, vanadium peaks usually have high background.");
declareProperty(std::make_unique<ArrayProperty<double>>(PropertyNames::POSITION_TOL),
"List of tolerance on fitted peak positions against given peak positions."
"If there is only one value given, then ");
declareProperty(PropertyNames::PEAK_MIN_HEIGHT, 0.,
"Minimum peak height such that all the fitted peaks with "
"height under this value will be excluded.");
declareProperty(PropertyNames::CONSTRAIN_PEAK_POS, true,
"If true peak position will be constrained by estimated positions "
"(highest Y value position) and "
"the peak width either estimted by observation or calculate.");
// additional output for reviewing
declareProperty(std::make_unique<WorkspaceProperty<MatrixWorkspace>>(PropertyNames::OUTPUT_WKSP_MODEL, "",
Direction::Output, PropertyMode::Optional),
"Name of the output matrix workspace with fitted peak. "
"This output workspace have the same dimesion as the input workspace."
"The Y values belonged to peaks to fit are replaced by fitted value. "
"Values of estimated background are used if peak fails to be fit.");
declareProperty(std::make_unique<WorkspaceProperty<API::ITableWorkspace>>(PropertyNames::OUTPUT_WKSP_PARAMS, "",
Direction::Output),
"Name of table workspace containing all fitted peak parameters.");
// Optional output table workspace for each individual parameter's fitting
// error
declareProperty(std::make_unique<WorkspaceProperty<API::ITableWorkspace>>(PropertyNames::OUTPUT_WKSP_PARAM_ERRS, "",
Direction::Output, PropertyMode::Optional),
"Name of workspace containing all fitted peak parameters' fitting error."
"It must be used along with FittedPeaksWorkspace and RawPeakParameters "
"(True)");
declareProperty(PropertyNames::RAW_PARAMS, true,
"false generates table with effective centre/width/height "
"parameters. true generates a table with peak function "
"parameters");
const std::string addoutgrp("Analysis");
setPropertyGroup(PropertyNames::OUTPUT_WKSP_PARAMS, addoutgrp);
setPropertyGroup(PropertyNames::OUTPUT_WKSP_MODEL, addoutgrp);
setPropertyGroup(PropertyNames::OUTPUT_WKSP_PARAM_ERRS, addoutgrp);
setPropertyGroup(PropertyNames::RAW_PARAMS, addoutgrp);
}
//----------------------------------------------------------------------------------------------
/** Validate inputs
*/
std::map<std::string, std::string> FitPeaks::validateInputs() {
map<std::string, std::string> issues;
// check that the peak parameters are in parallel properties
bool haveCommonPeakParameters(false);
std::vector<string> suppliedParameterNames = getProperty(PropertyNames::PEAK_PARAM_NAMES);
std::vector<double> peakParamValues = getProperty(PropertyNames::PEAK_PARAM_VALUES);
if ((!suppliedParameterNames.empty()) || (!peakParamValues.empty())) {
haveCommonPeakParameters = true;
if (suppliedParameterNames.size() != peakParamValues.size()) {
issues[PropertyNames::PEAK_PARAM_NAMES] = "must have same number of values as PeakParameterValues";
issues[PropertyNames::PEAK_PARAM_VALUES] = "must have same number of values as PeakParameterNames";
}
}
// get the information out of the table
std::string partablename = getPropertyValue(PropertyNames::PEAK_PARAM_TABLE);
if (!partablename.empty()) {
if (haveCommonPeakParameters) {
const std::string msg = "Parameter value table and initial parameter "
"name/value vectors cannot be given "
"simultanenously.";
issues[PropertyNames::PEAK_PARAM_TABLE] = msg;
issues[PropertyNames::PEAK_PARAM_NAMES] = msg;
issues[PropertyNames::PEAK_PARAM_VALUES] = msg;
} else {
m_profileStartingValueTable = getProperty(PropertyNames::PEAK_PARAM_TABLE);
suppliedParameterNames = m_profileStartingValueTable->getColumnNames();
}
}
// check that the suggested peak parameter names exist in the peak function
if (!suppliedParameterNames.empty()) {
std::string peakfunctiontype = getPropertyValue(PropertyNames::PEAK_FUNC);
m_peakFunction =
std::dynamic_pointer_cast<IPeakFunction>(API::FunctionFactory::Instance().createFunction(peakfunctiontype));
// put the names in a vector
std::vector<string> functionParameterNames;
for (size_t i = 0; i < m_peakFunction->nParams(); ++i)
functionParameterNames.emplace_back(m_peakFunction->parameterName(i));
// check that the supplied names are in the function
// it is acceptable to be missing parameters
bool failed = false;
for (const auto &name : suppliedParameterNames) {
if (std::find(functionParameterNames.begin(), functionParameterNames.end(), name) ==
functionParameterNames.end()) {
failed = true;
break;
}
}
if (failed) {
std::string msg = "Specified invalid parameter for peak function";
if (haveCommonPeakParameters)
issues[PropertyNames::PEAK_PARAM_NAMES] = msg;
else
issues[PropertyNames::PEAK_PARAM_TABLE] = msg;
}
}
// check inputs for uncertainty (fitting error)
const std::string error_table_name = getPropertyValue(PropertyNames::OUTPUT_WKSP_PARAM_ERRS);
if (!error_table_name.empty()) {
const bool use_raw_params = getProperty(PropertyNames::RAW_PARAMS);
if (!use_raw_params) {
issues[PropertyNames::OUTPUT_WKSP_PARAM_ERRS] = "Cannot be used with " + PropertyNames::RAW_PARAMS + "=False";
issues[PropertyNames::RAW_PARAMS] =
"Cannot be False with " + PropertyNames::OUTPUT_WKSP_PARAM_ERRS + " specified";
}
}
return issues;
}
//----------------------------------------------------------------------------------------------
void FitPeaks::exec() {
// process inputs
processInputs();
// create output workspace: fitted peak positions
generateOutputPeakPositionWS();
// create output workspace: fitted peaks' parameters values
generateFittedParametersValueWorkspaces();
// create output workspace: calculated from fitted peak and background
generateCalculatedPeaksWS();
// fit peaks
auto fit_results = fitPeaks();
// set the output workspaces to properites
processOutputs(fit_results);
}
//----------------------------------------------------------------------------------------------
void FitPeaks::processInputs() {
// input workspaces
m_inputMatrixWS = getProperty(PropertyNames::INPUT_WKSP);
if (m_inputMatrixWS->getAxis(0)->unit()->unitID() == "dSpacing")
m_inputIsDSpace = true;
else
m_inputIsDSpace = false;
// spectra to fit
int start_wi = getProperty(PropertyNames::START_WKSP_INDEX);
if (isEmpty(start_wi))
m_startWorkspaceIndex = 0;
else
m_startWorkspaceIndex = static_cast<size_t>(start_wi);
// last spectrum's workspace index, which is included
int stop_wi = getProperty(PropertyNames::STOP_WKSP_INDEX);
if (isEmpty(stop_wi))
m_stopWorkspaceIndex = m_inputMatrixWS->getNumberHistograms() - 1;
else {
m_stopWorkspaceIndex = static_cast<size_t>(stop_wi);
if (m_stopWorkspaceIndex > m_inputMatrixWS->getNumberHistograms() - 1)
m_stopWorkspaceIndex = m_inputMatrixWS->getNumberHistograms() - 1;
}
// optimizer, cost function and fitting scheme
m_minimizer = getPropertyValue(PropertyNames::MINIMIZER);
m_costFunction = getPropertyValue(PropertyNames::COST_FUNC);
m_fitPeaksFromRight = getProperty(PropertyNames::FIT_FROM_RIGHT);
m_constrainPeaksPosition = getProperty(PropertyNames::CONSTRAIN_PEAK_POS);
m_fitIterations = getProperty(PropertyNames::MAX_FIT_ITER);
// Peak centers, tolerance and fitting range
processInputPeakCenters();
// check
if (m_numPeaksToFit == 0)
throw std::runtime_error("number of peaks to fit is zero.");
// about how to estimate the peak width
m_peakWidthPercentage = getProperty(PropertyNames::PEAK_WIDTH_PERCENT);
if (isEmpty(m_peakWidthPercentage))
m_peakWidthPercentage = -1;
if (m_peakWidthPercentage >= 1.) // TODO
throw std::runtime_error("PeakWidthPercent must be less than 1");
g_log.debug() << "peak width/value = " << m_peakWidthPercentage << "\n";
// set up background
m_highBackground = getProperty(PropertyNames::HIGH_BACKGROUND);
m_bkgdSimga = getProperty(PropertyNames::BACKGROUND_Z_SCORE);
// Set up peak and background functions
processInputFunctions();
// about peak width and other peak parameter estimating method
if (m_peakWidthPercentage > 0.)
m_peakWidthEstimateApproach = EstimatePeakWidth::InstrumentResolution;
else if (isObservablePeakProfile((m_peakFunction->name())))
m_peakWidthEstimateApproach = EstimatePeakWidth::Observation;
else
m_peakWidthEstimateApproach = EstimatePeakWidth::NoEstimation;
// m_peakWidthEstimateApproach = EstimatePeakWidth::NoEstimation;
g_log.debug() << "Process inputs [3] peak type: " << m_peakFunction->name()
<< ", background type: " << m_bkgdFunction->name() << "\n";
processInputPeakTolerance();
processInputFitRanges();
return;
}
//----------------------------------------------------------------------------------------------
/** process inputs for peak profile and background
*/
void FitPeaks::processInputFunctions() {
// peak functions
std::string peakfunctiontype = getPropertyValue(PropertyNames::PEAK_FUNC);
m_peakFunction =
std::dynamic_pointer_cast<IPeakFunction>(API::FunctionFactory::Instance().createFunction(peakfunctiontype));
// background functions
std::string bkgdfunctiontype = getPropertyValue(PropertyNames::BACK_FUNC);
std::string bkgdname;
if (bkgdfunctiontype == "Linear")
bkgdname = "LinearBackground";
else if (bkgdfunctiontype == "Flat") {
g_log.warning("There may be problems with Flat background");
bkgdname = "FlatBackground";
} else
bkgdname = bkgdfunctiontype;
m_bkgdFunction =
std::dynamic_pointer_cast<IBackgroundFunction>(API::FunctionFactory::Instance().createFunction(bkgdname));
if (m_highBackground)
m_linearBackgroundFunction = std::dynamic_pointer_cast<IBackgroundFunction>(
API::FunctionFactory::Instance().createFunction("LinearBackground"));
else
m_linearBackgroundFunction = nullptr;
// TODO check that both parameter names and values exist
// input peak parameters
std::string partablename = getPropertyValue(PropertyNames::PEAK_PARAM_TABLE);
m_peakParamNames = getProperty(PropertyNames::PEAK_PARAM_NAMES);
m_uniformProfileStartingValue = false;
if (partablename.empty() && (!m_peakParamNames.empty())) {
// use uniform starting value of peak parameters
m_initParamValues = getProperty(PropertyNames::PEAK_PARAM_VALUES);
// convert the parameter name in string to parameter name in integer index
convertParametersNameToIndex();
// m_uniformProfileStartingValue = true;
} else if ((!partablename.empty()) && m_peakParamNames.empty()) {
// use non-uniform starting value of peak parameters
m_profileStartingValueTable = getProperty(partablename);
} else if (peakfunctiontype != "Gaussian") {
// user specifies nothing
g_log.warning("Neither parameter value table nor initial "
"parameter name/value vectors is specified. Fitting might "
"not be reliable for peak profile other than Gaussian");
}
return;
}
//----------------------------------------------------------------------------------------------
/** process and check for inputs about peak fitting range (i.e., window)
* Note: What is the output of the method?
*/
void FitPeaks::processInputFitRanges() {
// get peak fit window
std::vector<double> peakwindow = getProperty(PropertyNames::FIT_WINDOW_LIST);
std::string peakwindowname = getPropertyValue(PropertyNames::FIT_WINDOW_WKSP);
API::MatrixWorkspace_const_sptr peakwindowws = getProperty(PropertyNames::FIT_WINDOW_WKSP);
// in most case, calculate window by instrument resolution is False
m_calculateWindowInstrument = false;
if ((!peakwindow.empty()) && peakwindowname.empty()) {
// Peak windows are uniform among spectra: use vector for peak windows
m_uniformPeakWindows = true;
// check peak positions
if (!m_uniformPeakPositions)
throw std::invalid_argument("Uniform peak range/window requires uniform peak positions.");
// check size
if (peakwindow.size() != m_numPeaksToFit * 2)
throw std::invalid_argument("Peak window vector must be twice as large as number of peaks.");
// set up window to m_peakWindowVector
m_peakWindowVector.resize(m_numPeaksToFit);
for (size_t i = 0; i < m_numPeaksToFit; ++i) {
std::vector<double> peakranges(2);
peakranges[0] = peakwindow[i * 2];
peakranges[1] = peakwindow[i * 2 + 1];
// check peak window (range) against peak centers
if ((peakranges[0] < m_peakCenters[i]) && (m_peakCenters[i] < peakranges[1])) {
// pass check: set
m_peakWindowVector[i] = peakranges;
} else {
// failed
std::stringstream errss;
errss << "Peak " << i << ": user specifies an invalid range and peak center against " << peakranges[0] << " < "
<< m_peakCenters[i] << " < " << peakranges[1];
throw std::invalid_argument(errss.str());
}
} // END-FOR
// END for uniform peak window
} else if (peakwindow.empty() && peakwindowws != nullptr) {
// use matrix workspace for non-uniform peak windows
m_peakWindowWorkspace = getProperty(PropertyNames::FIT_WINDOW_WKSP);
m_uniformPeakWindows = false;
// check size
if (m_peakWindowWorkspace->getNumberHistograms() == m_inputMatrixWS->getNumberHistograms())
m_partialWindowSpectra = false;
else if (m_peakWindowWorkspace->getNumberHistograms() == (m_stopWorkspaceIndex - m_startWorkspaceIndex + 1))
m_partialWindowSpectra = true;
else
throw std::invalid_argument("Peak window workspace has unmatched number of spectra");
// check range for peak windows and peak positions
size_t window_index_start(0);
if (m_partialWindowSpectra)
window_index_start = m_startWorkspaceIndex;
size_t center_index_start(0);
if (m_partialSpectra)
center_index_start = m_startWorkspaceIndex;
// check each spectrum whether the window is defined with the correct size
for (size_t wi = 0; wi < m_peakWindowWorkspace->getNumberHistograms(); ++wi) {
// check size
if (m_peakWindowWorkspace->y(wi).size() != m_numPeaksToFit * 2) {
std::stringstream errss;
errss << "Peak window workspace index " << wi << " has incompatible number of fit windows (x2) "
<< m_peakWindowWorkspace->y(wi).size() << " with the number of peaks " << m_numPeaksToFit << " to fit.";
throw std::invalid_argument(errss.str());
}
const auto &peakWindowX = m_peakWindowWorkspace->x(wi);
// check window range against peak center
size_t window_index = window_index_start + wi;
size_t center_index = window_index - center_index_start;
const auto &peakCenterX = m_peakCenterWorkspace->x(center_index);
for (size_t ipeak = 0; ipeak < m_numPeaksToFit; ++ipeak) {
double left_w_bound = peakWindowX[ipeak * 2]; // TODO getting on y
double right_w_bound = peakWindowX[ipeak * 2 + 1];
double center = peakCenterX[ipeak];
if (!(left_w_bound < center && center < right_w_bound)) {
std::stringstream errss;
errss << "Workspace index " << wi << " has incompatible peak window (" // <<<<<<< HERE!!!!!!!!!
<< left_w_bound << ", " << right_w_bound << ") with " << ipeak << "-th expected peak's center "
<< center;
throw std::runtime_error(errss.str());
}
}
}
} else if (peakwindow.empty()) {
// no peak window is defined, then the peak window will be estimated by
// delta(D)/D
if (m_inputIsDSpace && m_peakWidthPercentage > 0)
m_calculateWindowInstrument = true;
else
throw std::invalid_argument("Without definition of peak window, the "
"input workspace must be in unit of dSpacing "
"and Delta(D)/D must be given!");
} else {
// non-supported situation
throw std::invalid_argument("One and only one of peak window array and "
"peak window workspace can be specified.");
}
return;
}
//----------------------------------------------------------------------------------------------
/** Processing peaks centers and fitting tolerance information from input. the
* parameters that are
* set including
* 1. m_peakCenters/m_peakCenterWorkspace/m_uniformPeakPositions
* (bool)/m_partialSpectra (bool)
* 2. m_peakPosTolerances (vector)
* 3. m_numPeaksToFit
*/
void FitPeaks::processInputPeakCenters() {
// peak centers
m_peakCenters = getProperty(PropertyNames::PEAK_CENTERS);
API::MatrixWorkspace_const_sptr peakcenterws = getProperty(PropertyNames::PEAK_CENTERS_WKSP);
if (!peakcenterws)
g_log.notice("Peak centers are not specified by peak center workspace");
std::string peakpswsname = getPropertyValue(PropertyNames::PEAK_CENTERS_WKSP);
if ((!m_peakCenters.empty()) && peakcenterws == nullptr) {
// peak positions are uniform among all spectra
m_uniformPeakPositions = true;
// number of peaks to fit!
m_numPeaksToFit = m_peakCenters.size();
} else if (m_peakCenters.empty() && peakcenterws != nullptr) {
// peak positions can be different among spectra
m_uniformPeakPositions = false;
m_peakCenterWorkspace = getProperty(PropertyNames::PEAK_CENTERS_WKSP);
// number of peaks to fit!
m_numPeaksToFit = m_peakCenterWorkspace->x(0).size();
g_log.debug() << "Input peak center workspace: " << m_peakCenterWorkspace->x(0).size() << ", "
<< m_peakCenterWorkspace->y(0).size() << "\n";
// check matrix worksapce for peak positions
const size_t peak_center_ws_spectra_number = m_peakCenterWorkspace->getNumberHistograms();
if (peak_center_ws_spectra_number == m_inputMatrixWS->getNumberHistograms()) {
// full spectra
m_partialSpectra = false;
} else if (peak_center_ws_spectra_number == m_stopWorkspaceIndex - m_startWorkspaceIndex + 1) {
// partial spectra
m_partialSpectra = true;
} else {
// a case indicating programming error
g_log.error() << "Peak center workspace has " << peak_center_ws_spectra_number << " spectra;"
<< "Input workspace has " << m_inputMatrixWS->getNumberHistograms() << " spectra;"
<< "User specifies to fit peaks from " << m_startWorkspaceIndex << " to " << m_stopWorkspaceIndex
<< ". They are mismatched to each other.\n";
throw std::invalid_argument("Input peak center workspace has mismatched "
"number of spectra to selected spectra to "
"fit.");
}
} else {
std::stringstream errss;
errss << "One and only one in 'PeakCenters' (vector) and "
"'PeakCentersWorkspace' shall be given. "
<< "'PeakCenters' has size " << m_peakCenters.size() << ", and name of peak center workspace "
<< "is " << peakpswsname;
throw std::invalid_argument(errss.str());
}
return;
}
//----------------------------------------------------------------------------------------------
/** Processing peak fitting tolerance information from input. The parameters
* that are
* set including
* 2. m_peakPosTolerances (vector)
*/
void FitPeaks::processInputPeakTolerance() {
// check code integrity
if (m_numPeaksToFit == 0)
throw std::runtime_error("ProcessInputPeakTolerance() must be called after "
"ProcessInputPeakCenters()");
// peak tolerance
m_peakPosTolerances = getProperty(PropertyNames::POSITION_TOL);
if (m_peakPosTolerances.empty()) {
// case 2, 3, 4
m_peakPosTolerances.clear();
m_peakPosTolCase234 = true;
} else if (m_peakPosTolerances.size() == 1) {
// only 1 uniform peak position tolerance is defined: expand to all peaks
double peak_tol = m_peakPosTolerances[0];
m_peakPosTolerances.resize(m_numPeaksToFit, peak_tol);
} else if (m_peakPosTolerances.size() != m_numPeaksToFit) {
// not uniform but number of peaks does not match
g_log.error() << "number of peak position tolerance " << m_peakPosTolerances.size()
<< " is not same as number of peaks " << m_numPeaksToFit << "\n";
throw std::runtime_error("Number of peak position tolerances and number of "
"peaks to fit are inconsistent.");
}
// minimum peak height: set default to zero
m_minPeakHeight = getProperty(PropertyNames::PEAK_MIN_HEIGHT);
if (isEmpty(m_minPeakHeight) || m_minPeakHeight < 0.)
m_minPeakHeight = 0.;
return;
}
//----------------------------------------------------------------------------------------------
/** Convert the input initial parameter name/value to parameter index/value for
* faster access
* according to the parameter name and peak profile function
* Output: m_initParamIndexes will be set up
*/
void FitPeaks::convertParametersNameToIndex() {
// get a map for peak profile parameter name and parameter index
std::map<std::string, size_t> parname_index_map;
for (size_t iparam = 0; iparam < m_peakFunction->nParams(); ++iparam)
parname_index_map.insert(std::make_pair(m_peakFunction->parameterName(iparam), iparam));
// define peak parameter names (class variable) if using table
if (m_profileStartingValueTable)
m_peakParamNames = m_profileStartingValueTable->getColumnNames();
// map the input parameter names to parameter indexes
for (const auto ¶mName : m_peakParamNames) {
auto locator = parname_index_map.find(paramName);
if (locator != parname_index_map.end()) {
m_initParamIndexes.emplace_back(locator->second);
} else {
// a parameter name that is not defined in the peak profile function. An
// out-of-range index is thus set to this
g_log.warning() << "Given peak parameter " << paramName
<< " is not an allowed parameter of peak "
"function "
<< m_peakFunction->name() << "\n";
m_initParamIndexes.emplace_back(m_peakFunction->nParams() * 10);
}
}
return;
}
//----------------------------------------------------------------------------------------------
/** main method to fit peaks among all
*/
std::vector<std::shared_ptr<FitPeaksAlgorithm::PeakFitResult>> FitPeaks::fitPeaks() {
API::Progress prog(this, 0., 1., m_stopWorkspaceIndex - m_startWorkspaceIndex);
/// Vector to record all the FitResult (only containing specified number of
/// spectra. shift is expected)
size_t num_fit_result = m_stopWorkspaceIndex - m_startWorkspaceIndex + 1;
std::vector<std::shared_ptr<FitPeaksAlgorithm::PeakFitResult>> fit_result_vector(num_fit_result);
const int nThreads = FrameworkManager::Instance().getNumOMPThreads();
size_t chunkSize = num_fit_result / nThreads;
// cppcheck-suppress syntaxError
PRAGMA_OMP(parallel for schedule(dynamic, 1) )
for (int ithread = 0; ithread < nThreads; ithread++) {
PARALLEL_START_INTERUPT_REGION
auto iws_begin = m_startWorkspaceIndex + chunkSize * static_cast<size_t>(ithread);
auto iws_end = (ithread == nThreads - 1) ? m_stopWorkspaceIndex + 1 : iws_begin + chunkSize;
// vector to store fit params for last good fit to each peak
std::vector<std::vector<double>> lastGoodPeakParameters(m_numPeaksToFit,
std::vector<double>(m_peakFunction->nParams(), 0.0));
for (auto wi = iws_begin; wi < iws_end; ++wi) {
// peaks to fit
std::vector<double> expected_peak_centers = getExpectedPeakPositions(static_cast<size_t>(wi));
// initialize output for this
size_t numfuncparams = m_peakFunction->nParams() + m_bkgdFunction->nParams();
std::shared_ptr<FitPeaksAlgorithm::PeakFitResult> fit_result =
std::make_shared<FitPeaksAlgorithm::PeakFitResult>(m_numPeaksToFit, numfuncparams);
fitSpectrumPeaks(static_cast<size_t>(wi), expected_peak_centers, fit_result, lastGoodPeakParameters);
PARALLEL_CRITICAL(FindPeaks_WriteOutput) {
writeFitResult(static_cast<size_t>(wi), expected_peak_centers, fit_result);
fit_result_vector[wi - m_startWorkspaceIndex] = fit_result;
}
prog.report();
}
PARALLEL_END_INTERUPT_REGION
}
PARALLEL_CHECK_INTERUPT_REGION
return fit_result_vector;
}
namespace {
/// Supported peak profiles for observation
std::vector<std::string> supported_peak_profiles{"Gaussian", "Lorentzian", "PseudoVoigt", "Voigt",
"BackToBackExponential"};
double numberCounts(const Histogram &histogram) {
double total = 0.;
for (const auto &value : histogram.y())
total += std::fabs(value);
return total;
}
//----------------------------------------------------------------------------------------------
/** Get number of counts in a specified range of a histogram
* @param histogram :: histogram instance
* @param xmin :: left boundary
* @param xmax :: right boundary
* @return :: counts
*/
double numberCounts(const Histogram &histogram, const double xmin, const double xmax) {
const auto &vector_x = histogram.points();
// determine left boundary
auto start_iter = vector_x.begin();
if (xmin > vector_x.front())
start_iter = std::lower_bound(vector_x.begin(), vector_x.end(), xmin);
if (start_iter == vector_x.end())
return 0.; // past the end of the data means nothing to integrate
// determine right boundary
auto stop_iter = vector_x.end();
if (xmax < vector_x.back()) // will set at end of vector if too large
stop_iter = std::lower_bound(start_iter, stop_iter, xmax);
// convert to indexes to sum over y
size_t start_index = static_cast<size_t>(start_iter - vector_x.begin());
size_t stop_index = static_cast<size_t>(stop_iter - vector_x.begin());
// integrate
double total = 0.;
for (size_t i = start_index; i < stop_index; ++i)
total += std::fabs(histogram.y()[i]);
return total;
}
} // namespace
//----------------------------------------------------------------------------------------------
/** Fit peaks across one single spectrum
*/
void FitPeaks::fitSpectrumPeaks(size_t wi, const std::vector<double> &expected_peak_centers,
const std::shared_ptr<FitPeaksAlgorithm::PeakFitResult> &fit_result,
std::vector<std::vector<double>> &lastGoodPeakParameters) {
// Spectrum contains very weak signal: do not proceed and return
if (numberCounts(m_inputMatrixWS->histogram(wi)) <= m_minPeakHeight) {
for (size_t i = 0; i < fit_result->getNumberPeaks(); ++i)
fit_result->setBadRecord(i, -1.);
return; // don't do anything
}
// Set up sub algorithm Fit for peak and background
IAlgorithm_sptr peak_fitter; // both peak and background (combo)
try {
peak_fitter = 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());
}
// Clone background function
IBackgroundFunction_sptr bkgdfunction = std::dynamic_pointer_cast<API::IBackgroundFunction>(m_bkgdFunction->clone());
// set up properties of algorithm (reference) 'Fit'
peak_fitter->setProperty("Minimizer", m_minimizer);
peak_fitter->setProperty("CostFunction", m_costFunction);
peak_fitter->setProperty("CalcErrors", true);
const double x0 = m_inputMatrixWS->histogram(wi).x().front();
const double xf = m_inputMatrixWS->histogram(wi).x().back();
// index of previous peak in same spectrum (initially invalid)
size_t prev_peak_index = m_numPeaksToFit;
bool neighborPeakSameSpectrum = false;
for (size_t fit_index = 0; fit_index < m_numPeaksToFit; ++fit_index) {
// convert fit index to peak index (in ascending order)
size_t peak_index(fit_index);
if (m_fitPeaksFromRight)
peak_index = m_numPeaksToFit - fit_index - 1;
// reset the background function
for (size_t i = 0; i < bkgdfunction->nParams(); ++i)
bkgdfunction->setParameter(i, 0.);
double expected_peak_pos = expected_peak_centers[peak_index];
// clone peak function for each peak (need to do this so can
// set center and calc any parameters from xml)
auto peakfunction = std::dynamic_pointer_cast<API::IPeakFunction>(m_peakFunction->clone());
peakfunction->setCentre(expected_peak_pos);
peakfunction->setMatrixWorkspace(m_inputMatrixWS, wi, 0.0, 0.0);
std::map<size_t, double> keep_values;
for (size_t ipar = 0; ipar < peakfunction->nParams(); ++ipar) {
if (peakfunction->isFixed(ipar)) {
// save value of these parameters which have just been calculated
// if they were set to be fixed (e.g. for the B2Bexp this would
// typically be A and B but not Sigma)
keep_values[ipar] = peakfunction->getParameter(ipar);
// let them be free to fit as these are typically refined from a
// focussed bank
peakfunction->unfix(ipar);