FitPowderDiffPeaks.cpp 118 KB
Newer Older
1
#include "MantidCurveFitting/Algorithms/FitPowderDiffPeaks.h"
2
3
4

#include "MantidKernel/ListValidator.h"
#include "MantidKernel/ArrayProperty.h"
5
6
#include "MantidKernel/Statistics.h"
#include "MantidKernel/Statistics.h"
7
8

#include "MantidAPI/TableRow.h"
9
#include "MantidAPI/Column.h"
10
11
12
13
14
15
16
17
#include "MantidAPI/FunctionDomain1D.h"
#include "MantidAPI/FunctionValues.h"
#include "MantidAPI/IFunction.h"
#include "MantidAPI/IPeakFunction.h"
#include "MantidAPI/ParameterTie.h"
#include "MantidAPI/ConstraintFactory.h"
#include "MantidAPI/FunctionFactory.h"
#include "MantidAPI/TextAxis.h"
18
#include "MantidAPI/WorkspaceFactory.h"
19

20
#include "MantidCurveFitting/Algorithms/Fit.h"
21
#include "MantidCurveFitting/Constraints/BoundaryConstraint.h"
22
23
24
25
26
27
#include "MantidCurveFitting/Functions/BackgroundFunction.h"
#include "MantidCurveFitting/Functions/ThermalNeutronDtoTOFFunction.h"
#include "MantidCurveFitting/Functions/Polynomial.h"
#include "MantidCurveFitting/Functions/Gaussian.h"
#include "MantidCurveFitting/Functions/BackToBackExponential.h"
#include "MantidCurveFitting/Functions/ThermalNeutronBk2BkExpConvPVoigt.h"
28
#include "MantidCurveFitting/FuncMinimizers/DampingMinimizer.h"
29
#include "MantidCurveFitting/CostFunctions/CostFuncFitting.h"
Zhou, Wenduo's avatar
Zhou, Wenduo committed
30

31
32
33
34
35
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>

#include <fstream>

36
37
38
#include <gsl/gsl_sf_erf.h>
#include <cmath>

39
40
41
42
43
44
/// Factor on FWHM for fitting a peak
#define PEAKFITRANGEFACTOR 5.0

/// Factor on FWHM for defining a peak's range
#define PEAKBOUNDARYFACTOR 2.5

45
46
/// Factor on FWHM for excluding peak to fit background
#define EXCLUDEPEAKRANGEFACTOR 8.0
47
48
/// Factor on FWHM to fit a peak
#define WINDOWSIZE 3.0
49
50
51
52
53

using namespace Mantid;
using namespace Mantid::API;
using namespace Mantid::Kernel;
using namespace Mantid::DataObjects;
54
using namespace Mantid::CurveFitting::Functions;
55
using namespace Mantid::CurveFitting::Constraints;
56
57
58

using namespace std;

59
60
namespace Mantid {
namespace CurveFitting {
61
namespace Algorithms {
62
63
64
65
66
67

DECLARE_ALGORITHM(FitPowderDiffPeaks)

//----------------------------------------------------------------------------------------------
/** Constructor
 */
68
69
70
71
72
73
74
75
FitPowderDiffPeaks::FitPowderDiffPeaks()
    : m_wsIndex(-1), m_tofMin(0.), m_tofMax(0.), m_useGivenTOFh(false),
      m_confidentInInstrumentParameters(false), m_minimumHKL(),
      m_numPeaksLowerToMin(-1), m_indexGoodFitPeaks(), m_chi2GoodFitPeaks(),
      m_fitMode(ROBUSTFIT), m_genPeakStartingValue(HKLCALCULATION),
      m_rightmostPeakHKL(), m_rightmostPeakLeftBound(0.),
      m_rightmostPeakRightBound(0.), m_minPeakHeight(0.), m_unitCell(),
      m_fitPeakBackgroundComposite(false) {}
76
77
78
79
80
81
82
83
84
85
86

//----------------------------------------------------------------------------------------------
/** Destructor
 */
FitPowderDiffPeaks::~FitPowderDiffPeaks() {}

//----------------------------------------------------------------------------------------------
/** Parameter declaration
 */
void FitPowderDiffPeaks::init() {
  // Input data workspace
87
  declareProperty(Kernel::make_unique<WorkspaceProperty<MatrixWorkspace>>(
88
89
90
91
                      "InputWorkspace", "Anonymous", Direction::Input),
                  "Input workspace for data (diffraction pattern). ");

  // Output workspace
92
  declareProperty(Kernel::make_unique<WorkspaceProperty<Workspace2D>>(
93
94
95
96
97
                      "OutputWorkspace", "Anonymous2", Direction::Output),
                  "Output Workspace2D for the fitted peaks. ");

  // Input/output peaks table workspace
  declareProperty(
98
99
      Kernel::make_unique<WorkspaceProperty<TableWorkspace>>(
          "BraggPeakParameterWorkspace", "AnonymousPeak", Direction::Input),
100
101
102
      "TableWorkspace containg all peaks' parameters.");

  // Input and output instrument parameters table workspace
103
  declareProperty(Kernel::make_unique<WorkspaceProperty<TableWorkspace>>(
104
105
106
107
108
109
                      "InstrumentParameterWorkspace", "AnonymousInstrument",
                      Direction::InOut),
                  "TableWorkspace containg instrument's parameters.");

  // Workspace to output fitted peak parameters
  declareProperty(
110
111
112
      Kernel::make_unique<WorkspaceProperty<TableWorkspace>>(
          "OutputBraggPeakParameterWorkspace", "AnonymousOut2",
          Direction::Output),
113
114
115
116
      "Output TableWorkspace containing the fitted peak parameters for each "
      "peak.");

  // Data workspace containing fitted peak parameters
117
  declareProperty(Kernel::make_unique<WorkspaceProperty<Workspace2D>>(
118
119
120
121
122
123
                      "OutputBraggPeakParameterDataWorkspace", "ParameterData",
                      Direction::Output),
                  "Output Workspace2D containing fitted peak parameters for "
                  "further refinement.");

  // Zscore table workspace
124
125
126
127
128
  declareProperty(
      Kernel::make_unique<WorkspaceProperty<TableWorkspace>>(
          "OutputZscoreWorkspace", "ZscoreTable", Direction::Output),
      "Output TableWorkspace containing the Zscore of the fitted "
      "peak parameters. ");
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151

  // Workspace index of the
  declareProperty("WorkspaceIndex", 0,
                  "Worskpace index for the data to refine against.");

  // Range of the peaks to fit
  declareProperty("MinTOF", EMPTY_DBL(), "Minimum TOF to fit peaks.  ");
  declareProperty("MaxTOF", EMPTY_DBL(), "Maximum TOF to fit peaks.  ");

  vector<string> fitmodes(2);
  fitmodes[0] = "Robust";
  fitmodes[1] = "Confident";
  auto fitvalidator = boost::make_shared<StringListValidator>(fitmodes);
  declareProperty("FittingMode", "Robust", fitvalidator,
                  "Fitting mode such that user can determine"
                  "whether the input parameters are trustful or not.");

  // Option to calculate peak position from (HKL) and d-spacing data
  declareProperty("UseGivenPeakCentreTOF", true,
                  "Use each Bragg peak's centre in TOF given in "
                  "BraggPeakParameterWorkspace."
                  "Otherwise, calculate each peak's centre from d-spacing.");

152
  vector<string> genpeakoptions{"(HKL) & Calculation", "From Bragg Peak Table"};
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
  auto propvalidator = boost::make_shared<StringListValidator>(genpeakoptions);
  declareProperty("PeakParametersStartingValueFrom", "(HKL) & Calculation",
                  propvalidator, "Choice of how to generate starting values of "
                                 "Bragg peak profile parmeters.");

  declareProperty("MinimumPeakHeight", 0.20,
                  "Minimum peak height (with background removed) "
                  "Any peak whose maximum height under this value will be "
                  "treated as zero intensity. ");

  // Flag to calculate and trust peak parameters from instrument
  // declareProperty("ConfidentInInstrumentParameters", false, "Option to
  // calculate peak parameters from "
  //     "instrument parameters.");

  // Option to denote that peaks are related
  declareProperty(
      "PeaksCorrelated", false,
      "Flag for fact that all peaks' corresponding profile parameters "
      "are correlated by an analytical function");

  // Option for peak's HKL for minimum d-spacing
175
176
177
178
  auto arrayprop = Kernel::make_unique<ArrayProperty<int>>("MinimumHKL", "");
  declareProperty(std::move(arrayprop),
                  "Miller index of the left most peak (peak with "
                  "minimum d-spacing) to be fitted. ");
179
180
181
182
183
184
185

  // Number of the peaks to fit left to peak with minimum HKL
  declareProperty("NumberPeaksToFitBelowLowLimit", 0,
                  "Number of peaks to fit with d-spacing value "
                  "less than specified minimum. ");

  // Right most peak property
186
187
188
  auto righthklprop =
      Kernel::make_unique<ArrayProperty<int>>("RightMostPeakHKL", "");
  declareProperty(std::move(righthklprop),
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
                  "Miller index of the right most peak. "
                  "It is only required and used in RobustFit mode.");

  declareProperty("RightMostPeakLeftBound", EMPTY_DBL(),
                  "Left bound of the right most peak. "
                  "Used in RobustFit mode.");

  declareProperty("RightMostPeakRightBound", EMPTY_DBL(),
                  "Right bound of the right most peak. "
                  "Used in RobustFit mode.");

  // Fit option
  declareProperty("FitCompositePeakBackground", true,
                  "Flag to do fit to both peak and background in a composite "
                  "function as last fit step.");

  return;
}

//----------------------------------------------------------------------------------------------
/** Main execution
 */
void FitPowderDiffPeaks::exec() {
  // 1. Get input
  processInputProperties();

  // 2. Crop input workspace
  cropWorkspace(m_tofMin, m_tofMax);

  // 3. Parse input table workspace
  importInstrumentParameterFromTable(m_profileTable);

  // 4. Unit cell
  double latticesize = getParameter("LatticeConstant");
  if (latticesize == EMPTY_DBL())
    throw runtime_error(
        "Input instrument table workspace lacks LatticeConstant. "
        "Unable to complete processing.");
  m_unitCell.set(latticesize, latticesize, latticesize, 90.0, 90.0, 90.0);

  // 5. Generate peaks
  genPeaksFromTable(m_peakParamTable);

  // 6. Fit peaks & get peak centers
  m_indexGoodFitPeaks.clear();
  m_chi2GoodFitPeaks.clear();
  size_t numpts = m_dataWS->readX(m_wsIndex).size();
  m_peakData.reserve(numpts);
  for (size_t i = 0; i < numpts; ++i)
    m_peakData.push_back(0.0);

  g_log.information() << "[FitPeaks] Total Number of Peak = "
                      << m_vecPeakFunctions.size() << std::endl;
  m_peakFitChi2.resize(m_vecPeakFunctions.size(), -1.0 * DBL_MIN);
  m_goodFit.resize(m_vecPeakFunctions.size(), false);

  if (m_fitMode == ROBUSTFIT) {
    g_log.information() << "Fit (Single) Peaks In Robust Mode." << endl;
    fitPeaksRobust();
  } else if (m_fitMode == TRUSTINPUTFIT) {
    g_log.information()
        << "Fit Peaks In Trust Mode.  Possible to fit overlapped peaks."
        << endl;
    fitPeaksWithGoodStartingValues();
  } else {
    g_log.error("Unsupported fit mode!");
    throw runtime_error("Unsupported fit mode.");
  }
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
  // 5. Create Output
  // a) Create a Table workspace for peak profile
  pair<TableWorkspace_sptr, TableWorkspace_sptr> tables =
      genPeakParametersWorkspace();
  TableWorkspace_sptr outputpeaksws = tables.first;
  TableWorkspace_sptr ztablews = tables.second;
  setProperty("OutputBraggPeakParameterWorkspace", outputpeaksws);
  setProperty("OutputZscoreWorkspace", ztablews);

  // b) Create output data workspace (as a middle stage product)
  Workspace2D_sptr outdataws =
      genOutputFittedPatternWorkspace(m_peakData, m_wsIndex);
  setProperty("OutputWorkspace", outdataws);

  // c) Create data workspace for X0, A, B and S of peak with good fit
  Workspace2D_sptr peakparamvaluews = genPeakParameterDataWorkspace();
  setProperty("OutputBraggPeakParameterDataWorkspace", peakparamvaluews);

  return;
}

//----------------------------------------------------------------------------------------------
/** Process input parameters
  */
void FitPowderDiffPeaks::processInputProperties() {
  // data workspace
  m_dataWS = this->getProperty("InputWorkspace");
  m_wsIndex = this->getProperty("WorkspaceIndex");
  if (m_wsIndex < 0 ||
      m_wsIndex > static_cast<int>(m_dataWS->getNumberHistograms())) {
    stringstream errss;
    errss << "Input workspace = " << m_wsIndex << " is out of range [0, "
          << m_dataWS->getNumberHistograms();
    g_log.error(errss.str());
    throw std::invalid_argument(errss.str());
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

  // table workspaces for parameters
  m_peakParamTable = this->getProperty("BraggPeakParameterWorkspace");
  m_profileTable = this->getProperty("InstrumentParameterWorkspace");

  // fitting range
  m_tofMin = getProperty("MinTOF");
  m_tofMax = getProperty("MaxTOF");
  if (m_tofMin == EMPTY_DBL())
    m_tofMin = m_dataWS->readX(m_wsIndex)[0];
  if (m_tofMax == EMPTY_DBL())
    m_tofMax = m_dataWS->readX(m_wsIndex).back();

  m_minimumHKL = getProperty("MinimumHKL");
  m_numPeaksLowerToMin = getProperty("NumberPeaksToFitBelowLowLimit");

  // fitting algorithm option
  string fitmode = getProperty("FittingMode");
  if (fitmode.compare("Robust") == 0) {
    m_fitMode = ROBUSTFIT;
  } else if (fitmode.compare("Confident") == 0) {
    m_fitMode = TRUSTINPUTFIT;
  } else {
    throw runtime_error(
        "Input fit mode can only accept either Robust or Confident. ");
319
320
  }

321
322
323
324
325
326
327
328
329
330
331
332
333
334
  m_useGivenTOFh = getProperty("UseGivenPeakCentreTOF");
  // m_confidentInInstrumentParameters =
  // getProperty("ConfidentInInstrumentParameters");

  // peak parameter generation option
  string genpeakparamalg = getProperty("PeakParametersStartingValueFrom");
  if (genpeakparamalg.compare("(HKL) & Calculation") == 0) {
    m_genPeakStartingValue = HKLCALCULATION;
  } else if (genpeakparamalg.compare("From Bragg Peak Table") == 0) {
    m_genPeakStartingValue = FROMBRAGGTABLE;
  } else {
    throw runtime_error(
        "Input option from PeakParametersStaringValueFrom is not supported.");
  }
335

336
337
338
339
  // Right most peak information
  m_rightmostPeakHKL = getProperty("RightMostPeakHKL");
  m_rightmostPeakLeftBound = getProperty("RightMostPeakLeftBound");
  m_rightmostPeakRightBound = getProperty("RightMostPeakRightBound");
340

341
  if (m_fitMode == ROBUSTFIT) {
342
    if (m_rightmostPeakHKL.empty() || m_rightmostPeakLeftBound == EMPTY_DBL() ||
343
344
345
346
347
348
349
350
351
352
353
354
355
356
        m_rightmostPeakRightBound == EMPTY_DBL()) {
      stringstream errss;
      errss << "If fit mode is 'RobustFit', then user must specify all 3 "
               "properties of right most peak "
            << "(1) Miller Index   (given size  = " << m_rightmostPeakHKL.size()
            << "), "
            << "(2) Left boundary  (given value = " << m_rightmostPeakLeftBound
            << "), "
            << "(3) Right boundary (given value = " << m_rightmostPeakRightBound
            << "). ";
      g_log.error(errss.str());
      throw runtime_error(errss.str());
    }
  }
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
  m_minPeakHeight = getProperty("MinimumPeakHeight");

  m_fitPeakBackgroundComposite = getProperty("FitCompositePeakBackground");

  return;
}

//=================================  Fit Peaks In Robust Mode
//==================================

//----------------------------------------------------------------------------------------------
/** Fit peaks in Robust mode.
  * Prerequisite:
  * 1. There are not any peaks that overlap to others;
  * Algorithm: All peaks are fit individually
  * Challenge:
  *   1. Starting geometry parameters can be off
  *   2. Peak profile parameters cannot be trusted at all.
  */
void FitPowderDiffPeaks::fitPeaksRobust() {
  // I. Prepare
  BackToBackExponential_sptr rightpeak;
  bool isrightmost = true;
  size_t numpeaks = m_vecPeakFunctions.size();
  if (numpeaks == 0)
    throw runtime_error("There is no peak to fit!");

  vector<string> peakparnames =
      m_vecPeakFunctions[0].second.second->getParameterNames();

  // II. Create local background function.
  Polynomial_sptr backgroundfunction =
      boost::make_shared<Polynomial>(Polynomial());
  backgroundfunction->setAttributeValue("n", 1);
  backgroundfunction->initialize();

  // III. Fit peaks
  double chi2;
  double refpeakshift = 0.0;

  for (int peakindex = static_cast<int>(numpeaks) - 1; peakindex >= 0;
       --peakindex) {
    vector<int> peakhkl = m_vecPeakFunctions[peakindex].second.first;
    BackToBackExponential_sptr thispeak =
        m_vecPeakFunctions[peakindex].second.second;
403

404
    stringstream infoss;
405

406
    bool goodfit = false;
407

408
409
410
411
412
413
414
    if (isrightmost && peakhkl == m_rightmostPeakHKL) {
      // It is the specified right most peak.  Estimate background, peak height,
      // fwhm, ...
      // 1. Determine the starting value of the peak
      double peakleftbound, peakrightbound;
      peakleftbound = m_rightmostPeakLeftBound;
      peakrightbound = m_rightmostPeakRightBound;
415

416
      double predictpeakcentre = thispeak->centre();
417

418
419
420
421
422
423
424
      infoss << "[DBx102] The " << numpeaks - 1 - peakindex
             << "-th rightmost peak's miller index = " << peakhkl[0] << ", "
             << peakhkl[1] << ", " << peakhkl[2]
             << ", predicted at TOF = " << thispeak->centre()
             << ";  User specify boundary = [" << peakleftbound << ", "
             << peakrightbound << "].";
      g_log.information() << infoss.str() << endl;
425

426
427
428
429
430
      map<string, double> rightpeakparameters;
      goodfit = fitSinglePeakRobust(
          thispeak,
          boost::dynamic_pointer_cast<BackgroundFunction>(backgroundfunction),
          peakleftbound, peakrightbound, rightpeakparameters, chi2);
431

432
      m_peakFitChi2[peakindex] = chi2;
433

434
435
436
      if (!goodfit)
        throw runtime_error(
            "Failed to fit the right most peak.  Unable to process. ");
437

438
      stringstream robmsgss;
439
      for (auto &parname : peakparnames) {
440
441
442
        robmsgss << parname << " = " << thispeak->getParameter(parname) << endl;
      }
      g_log.information() << "[DB1151] Robust Fit Result:   Chi^2 = " << chi2
443
444
                          << endl
                          << robmsgss.str();
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

      rightpeak = thispeak;
      isrightmost = false;

      // iii. Reference peak shift
      refpeakshift = thispeak->centre() - predictpeakcentre;

      g_log.notice() << "[DBx332] Peak -"
                     << static_cast<int>(numpeaks) - peakindex - 1
                     << ": shifted = " << refpeakshift << endl;
    } else if (!isrightmost) {
      // All peaks but not the right most peak
      // 1. Validate inputs
      if (peakindex == static_cast<int>(numpeaks) - 1)
        throw runtime_error(
            "Impossible to have peak index as the right most peak here!");

      double predictcentre = thispeak->centre();

      // 2. Determine the peak range by observation
      double peakleftbound, peakrightbound;
      observePeakRange(thispeak, rightpeak, refpeakshift, peakleftbound,
                       peakrightbound);

      stringstream dbxss;
      dbxss << endl;
      for (int i = 0; i < 10; ++i)
        dbxss << "==";
473
474
475
      dbxss << endl
            << "[DBx323] Peak (" << peakhkl[0] << ", " << peakhkl[1] << ","
            << peakhkl[2] << ").  Centre predicted @ TOF = " << predictcentre
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
            << ".  Observed range = " << peakleftbound << ", "
            << peakrightbound;
      g_log.notice(dbxss.str());

      // 3. Fit peak
      /* Disabled and replaced by fit1PeakRobust
      goodfit = fitSinglePeakRefRight(thispeak, backgroundfunction, rightpeak,
      peakleftbound,
                                      peakrightbound, chi2);
                                      */

      map<string, double> rightpeakparameters;
      storeFunctionParameters(rightpeak, rightpeakparameters);
      goodfit = fitSinglePeakRobust(
          thispeak,
          boost::dynamic_pointer_cast<BackgroundFunction>(backgroundfunction),
          peakleftbound, peakrightbound, rightpeakparameters, chi2);

      if (goodfit) {
        // Fit successful
        m_peakFitChi2[peakindex] = chi2;
        // Update right peak and reference peak shift if peak is not trivial
        if (thispeak->height() >= m_minPeakHeight) {
          rightpeak = thispeak;
          refpeakshift = thispeak->centre() - predictcentre;
        }
502

503
504
505
506
507
508
      } else {
        // Bad fit
        m_peakFitChi2[peakindex] = -1.0;
        g_log.warning() << "Fitting peak @ " << thispeak->centre()
                        << " failed. " << endl;
      }
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
    } else {
      // It is right to the specified right most peak.  Skip to next peak
      double peakleftbound, peakrightbound;
      peakleftbound = m_rightmostPeakLeftBound;
      peakrightbound = m_rightmostPeakRightBound;

      infoss << "[DBx102] The " << numpeaks - 1 - peakindex
             << "-th rightmost peak's miller index = " << peakhkl[0] << ", "
             << peakhkl[1] << ", " << peakhkl[2]
             << ", predicted at TOF = " << thispeak->centre() << "; "
             << "User specify right most peak's miller index = "
             << m_rightmostPeakHKL[0] << ", " << m_rightmostPeakHKL[1] << ", "
             << m_rightmostPeakHKL[2] << " User specify boundary = ["
             << peakleftbound << ", " << peakrightbound << "].";
      g_log.information() << infoss.str() << endl;
      continue;
    }

  } // ENDFOR Peaks

  return;
}

//----------------------------------------------------------------------------------------------
/** Observe peak range with hint from right peak's properties
  * Assumption: the background is reasonably flat within peak range
  */
void FitPowderDiffPeaks::observePeakRange(BackToBackExponential_sptr thispeak,
                                          BackToBackExponential_sptr rightpeak,
                                          double refpeakshift,
                                          double &peakleftbound,
                                          double &peakrightbound) {
  double predictcentre = thispeak->centre();
  double rightfwhm = rightpeak->fwhm();

  // 1. Roughly determine the peak range from this peak's starting values and
  // right peak' fitted
  //    parameters values
  if (refpeakshift > 0) {
    // tend to shift to right
    peakleftbound = predictcentre - rightfwhm;
    peakrightbound = predictcentre + rightfwhm + refpeakshift;
  } else {
    // tendency to shift to left
    peakleftbound = predictcentre - rightfwhm + refpeakshift;
    peakrightbound = predictcentre + rightfwhm;
  }
  if (peakrightbound > rightpeak->centre() - 3 * rightpeak->fwhm()) {
    // the search of peak's right end shouldn't exceed the left tail of its real
    // right peak!
    // Remember this is robust mode.  Any 2 adjacent peaks should be faw enough.
    peakrightbound = rightpeak->centre() - 3 * rightpeak->fwhm();
  }
563

564
565
  // 2. Search for maximum
  const MantidVec &vecX = m_dataWS->readX(m_wsIndex);
566

567
568
569
  size_t icentre =
      findMaxValue(m_dataWS, m_wsIndex, peakleftbound, peakrightbound);
  double peakcentre = vecX[icentre];
570

571
572
573
  // 3. Narrow now the peak range
  peakleftbound = vecX[icentre] - 4.0 * rightfwhm;
  peakrightbound = vecX[icentre] + 4.0 * rightfwhm;
574

575
576
577
578
579
580
581
582
  double rightpeakleftbound = rightpeak->centre() - 3 * rightfwhm;
  if (peakrightbound > rightpeakleftbound) {
    peakrightbound = rightpeakleftbound;
    if (peakrightbound < 2.0 * rightfwhm + peakcentre)
      g_log.warning() << "Peak @ " << peakcentre
                      << "'s right boundary is too close to its right peak!"
                      << endl;
  }
583

584
585
586
587
588
589
590
591
592
593
594
595
  return;
}

//----------------------------------------------------------------------------------------------
/** Fit a single peak including its background by a robust algorithm
  * Algorithm will
  *  1. Locate Maximum
  *  2.
  *
  * Assumption:
  * 1. peak must be in the range of [input peak center - leftdev, + rightdev]
  *
596
  * Prerequisites:
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
  * ---- NONE!
  *
  * Algorithms:
  *  1. Build partial workspace for peak
  *  2. Estimate background
  *  3. Estimate peak position and height (by observing)
  *  4. Fit peak by Gaussian for more accurate peak position, height and sigma
  *
  * Peak Fit Algorithms: 4 different approaches are used.  3 of them use normal
  *minimzers such that
  * 1. Use X0 and I calculated by Gaussian, then use A, B, S from input;
  * 2. Use X0, I and S calculated by Gaussian, then use A and B from input;
  * 3. Use X0, I and S calculated by Gaussian, then use A and B from right peak;
  * 4. Use X0, I and S calculated by Gaussian, then use simulated annealing on A
  *and B;
  *
  * Arguments
  * @param peak :: A peak function.
  * @param backgroundfunction :: A background function
  * @param peakleftbound :: peak left bound
  * @param peakrightbound :: peak right bound
  * @param rightpeakparammap :: peakrightbound
  * @param finalchi2   ::  (output) chi square of the fit result
  *
  * Arguments:
  * 1. leftdev, rightdev:  search range for the peak from the estimatio
  *(theoretical)
  * Return: chi2 ... all the other parameter should be just in peak
  */
bool FitPowderDiffPeaks::fitSinglePeakRobust(
    BackToBackExponential_sptr peak, BackgroundFunction_sptr backgroundfunction,
    double peakleftbound, double peakrightbound,
    map<string, double> rightpeakparammap, double &finalchi2) {
  // 1. Build partial workspace
  Workspace2D_sptr peakws =
      buildPartialWorkspace(m_dataWS, m_wsIndex, peakleftbound, peakrightbound);
  g_log.debug() << "[DB1208] Build partial workspace for peak @ "
                << peak->centre() << " (predicted)." << endl;

  // 2. Estimate and remove background
  size_t rawdata_wsindex = 0;
  size_t estbkgd_wsindex = 2;
  size_t peak_wsindex = 1;
  estimateBackgroundCoarse(peakws, backgroundfunction, rawdata_wsindex,
                           estbkgd_wsindex, peak_wsindex);

  stringstream dbss;
  dbss << "[DBx203] Removed background peak data: " << endl;
  for (size_t i = 0; i < peakws->readX(peak_wsindex).size(); ++i)
    dbss << peakws->readX(peak_wsindex)[i] << "\t\t"
         << peakws->readY(peak_wsindex)[i] << "\t\t"
         << peakws->readE(peak_wsindex)[i] << endl;
  g_log.debug(dbss.str());

  // 3. Estimate FWHM, peak centre, and height
  double centre, fwhm, height;
  string errmsg;
  bool pass = observePeakParameters(peakws, 1, centre, height, fwhm, errmsg);
  if (!pass) {
// If estiamtion fails, quit b/c first/rightmost peak must be fitted.
#if 0
      g_log.error(errmsg);
      throw runtime_error(errmsg);
#else
    g_log.notice("Unable to observe peak parameters.  Proceed to next peak.");
    return false;
#endif
  } else if (height < m_minPeakHeight) {
    g_log.notice() << "[FLAGx409] Peak proposed @ TOF = " << peak->centre()
                   << " has a trivial "
                   << "peak height = " << height << " by observation.  Skipped."
                   << endl;
    return false;
  } else {
    g_log.information() << "[DBx201] Peak Predicted @ TOF = " << peak->centre()
                        << ", Estimated (observation) Centre = " << centre
                        << ", FWHM = " << fwhm << " Height = " << height
                        << endl;
  }
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
  // 4. Fit by Gaussian to get some starting value
  double tof_h, sigma;
  doFitGaussianPeak(peakws, peak_wsindex, centre, fwhm, fwhm, tof_h, sigma,
                    height);

  // 5. Fit by various methods
  //    Set all parameters for fit
  vector<string> peakparnames = peak->getParameterNames();
  for (size_t i = 0; i < peakparnames.size(); ++i)
    peak->unfix(i);

  //    Set up the universal starting parameter
  peak->setParameter("I", height * fwhm);
  peak->setParameter("X0", tof_h);

  size_t numsteps = 2;
  vector<string> minimizers(numsteps);
  minimizers[0] = "Simplex";
  minimizers[1] = "Levenberg-Marquardt";
  vector<size_t> maxiterations(numsteps, 10000);
  vector<double> dampfactors(numsteps, 0.0);

  //    Record the start value
  map<string, double> origparammap;
  storeFunctionParameters(peak, origparammap);

  vector<double> chi2s;
  vector<bool> goodfits;
  vector<map<string, double>> solutions;

  // a) Fit by using input peak parameters
  string peakinfoa0 =
      getFunctionInfo(boost::dynamic_pointer_cast<IFunction>(peak));
  g_log.notice() << "[DBx533A] Approach A: Starting Peak Function Information: "
711
712
                 << endl
                 << peakinfoa0 << endl;
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727

  double chi2a;
  bool fitgooda = doFit1PeakSequential(peakws, peak_wsindex, peak, minimizers,
                                       maxiterations, dampfactors, chi2a);
  map<string, double> solutiona;
  storeFunctionParameters(peak, solutiona);

  chi2s.push_back(chi2a);
  goodfits.push_back(fitgooda);
  solutions.push_back(solutiona);

  string peakinfoa1 =
      getFunctionInfo(boost::dynamic_pointer_cast<IFunction>(peak));
  g_log.notice() << "[DBx533A] Approach A:  Fit Successful = " << fitgooda
                 << ", Chi2 = " << chi2a
728
729
                 << ", Peak Function Information: " << endl
                 << peakinfoa1 << endl;
730
731
732
733
734
735
736
737

  // b) Fit by using Gaussian result (Sigma)
  restoreFunctionParameters(peak, origparammap);
  peak->setParameter("S", sigma);

  string peakinfob0 =
      getFunctionInfo(boost::dynamic_pointer_cast<IFunction>(peak));
  g_log.notice() << "[DBx533B] Approach B: Starting Peak Function Information: "
738
739
                 << endl
                 << peakinfob0 << endl;
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755

  double chi2b;
  bool fitgoodb = doFit1PeakSequential(peakws, peak_wsindex, peak, minimizers,
                                       maxiterations, dampfactors, chi2b);

  map<string, double> solutionb;
  storeFunctionParameters(peak, solutionb);

  chi2s.push_back(chi2b);
  goodfits.push_back(fitgoodb);
  solutions.push_back(solutionb);

  string peakinfob1 =
      getFunctionInfo(boost::dynamic_pointer_cast<IFunction>(peak));
  g_log.notice() << "[DBx533B] Approach 2: Fit Successful = " << fitgoodb
                 << ", Chi2 = " << chi2b
756
757
                 << ", Peak Function Information: " << endl
                 << peakinfob1 << endl;
758
759

  // c) Fit peak parameters by the value from right peak
760
  if (!rightpeakparammap.empty()) {
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
    restoreFunctionParameters(peak, rightpeakparammap);
    peak->setParameter("X0", tof_h);
    peak->setParameter("I", height * fwhm);

    string peakinfoc0 =
        getFunctionInfo(boost::dynamic_pointer_cast<IFunction>(peak));
    g_log.notice()
        << "[DBx533C] Approach C: Starting Peak Function Information: " << endl
        << peakinfoc0 << endl;

    double chi2c;
    bool fitgoodc = doFit1PeakSequential(peakws, peak_wsindex, peak, minimizers,
                                         maxiterations, dampfactors, chi2c);
    map<string, double> solutionc;
    storeFunctionParameters(peak, solutionc);

    chi2s.push_back(chi2c);
    goodfits.push_back(fitgoodc);
    solutions.push_back(solutionc);

    string peakinfoc1 =
        getFunctionInfo(boost::dynamic_pointer_cast<IFunction>(peak));
    g_log.notice() << "[DBx533C] Approach C:  Fit Successful = " << fitgoodc
                   << ", Chi2 = " << chi2c
785
786
                   << ", Peak Function Information: " << endl
                   << peakinfoc1 << endl;
787
788
789
790
791
792
  } else {
    // No right peak information: set a error entry
    chi2s.push_back(DBL_MAX);
    goodfits.push_back(false);
    solutions.push_back(rightpeakparammap);
  }
793

794
795
796
797
798
799
800
801
802
  // 6. Summarize the above 3 approach
  size_t bestapproach = goodfits.size() + 1;
  double bestchi2 = DBL_MAX;
  for (size_t i = 0; i < goodfits.size(); ++i) {
    if (goodfits[i] && chi2s[i] < bestchi2) {
      bestapproach = i;
      bestchi2 = chi2s[i];
    }
  }
803

804
805
806
807
808
809
810
811
812
813
814
815
  stringstream fitsumss;
  fitsumss << "Best fit result is obtained by approach " << bestapproach
           << " of total " << goodfits.size()
           << " approaches.  Best Chi^2 = " << bestchi2
           << ", Peak Height = " << peak->height();
  g_log.notice() << "[DB1127] " << fitsumss.str() << endl;

  bool fitgood = true;
  if (bestapproach < goodfits.size()) {
    restoreFunctionParameters(peak, solutions[bestapproach]);
  } else {
    fitgood = false;
816
817
  }

818
819
820
821
822
  // 7. Fit by Monte Carlo if previous failed
  if (!fitgood) {
    peak->setParameter("S", sigma);
    peak->setParameter("I", height * fwhm);
    peak->setParameter("X0", tof_h);
823

824
    vector<string> paramsinmc{"A", "B"};
825

826
827
    fitSinglePeakSimulatedAnnealing(peak, paramsinmc);
  }
828

829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
  // 8. Fit with background
  if (m_fitPeakBackgroundComposite) {
    // Fit peak + background
    double chi2compf;
    bool fitcompfunsuccess = doFit1PeakBackground(
        peakws, rawdata_wsindex, peak, backgroundfunction, chi2compf);
    if (fitcompfunsuccess) {
      finalchi2 = chi2compf;
    } else {
      finalchi2 = bestchi2;
      stringstream dbss;
      dbss << "Fit peak-background composite function failed! "
           << "Need to find out how this case peak value is changed from best "
              "fit.";
      g_log.warning(dbss.str());
    }
  } else {
    // Flag is turned off
    finalchi2 = bestchi2;
  }
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
  // 9. Plot function
  FunctionDomain1DVector domain(peakws->readX(0));
  plotFunction(peak, backgroundfunction, domain);

  return fitgood;
}

//----------------------------------------------------------------------------------------------
/** Fit single peak with background to raw data
  * Note 1: in a limited range (4*FWHM)
  */
bool FitPowderDiffPeaks::doFit1PeakBackground(
    Workspace2D_sptr dataws, size_t wsindex, BackToBackExponential_sptr peak,
    BackgroundFunction_sptr backgroundfunction, double &chi2) {
  // 0. Set fit parameters
  string minimzername("Levenberg-MarquardtMD");
  double startx = peak->centre() - 3.0 * peak->fwhm();
  double endx = peak->centre() + 3.0 * peak->fwhm();

  // 1. Create composite function
  CompositeFunction_sptr compfunc(new CompositeFunction);
  compfunc->addFunction(peak);
  compfunc->addFunction(backgroundfunction);

  // 2. Unfix all parameters
  vector<string> comparnames = compfunc->getParameterNames();
  for (size_t ipar = 0; ipar < comparnames.size(); ++ipar)
    compfunc->unfix(ipar);

  // 3. Fit
  string cominfoa = getFunctionInfo(compfunc);
  g_log.notice() << "[DBx533X-0] Fit All: Starting Peak Function Information: "
882
883
                 << endl
                 << cominfoa << "Fit range = " << startx << ", " << endx
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
                 << endl;

  // 3. Set
  IAlgorithm_sptr fitalg = createChildAlgorithm("Fit", -1, -1, true);
  fitalg->initialize();

  fitalg->setProperty("Function",
                      boost::dynamic_pointer_cast<API::IFunction>(compfunc));
  fitalg->setProperty("InputWorkspace", dataws);
  fitalg->setProperty("WorkspaceIndex", static_cast<int>(wsindex));
  fitalg->setProperty("Minimizer", minimzername);
  fitalg->setProperty("CostFunction", "Least squares");
  fitalg->setProperty("MaxIterations", 1000);
  fitalg->setProperty("Output", "FitPeakBackground");
  fitalg->setProperty("StartX", startx);
  fitalg->setProperty("EndX", endx);

  // 3. Execute and parse the result
  bool isexecute = fitalg->execute();
  bool fitsuccess;
  chi2 = DBL_MAX;

  if (isexecute) {
    std::string fitresult = parseFitResult(fitalg, chi2, fitsuccess);
908

909
910
911
912
913
914
915
916
917
918
919
920
921
    // Figure out result
    stringstream cominfob;
    cominfob << "[DBx533X] Fit All: Fit Successful = " << fitsuccess
             << ", Chi^2 = " << chi2 << endl;
    cominfob << "Detailed info = " << fitresult << endl;
    string fitinfo = getFunctionInfo(compfunc);
    cominfob << fitinfo;

    g_log.notice(cominfob.str());
  } else {
    g_log.notice() << "[DB1203B] Failed To Fit Peak+Background @ "
                   << peak->centre() << endl;
    fitsuccess = false;
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
  return fitsuccess;
}

//----------------------------------------------------------------------------------------------
/** Fit signle peak by Monte Carlo/simulated annealing
  */
bool FitPowderDiffPeaks::fitSinglePeakSimulatedAnnealing(
    BackToBackExponential_sptr peak, vector<string> paramtodomc) {
  UNUSED_ARG(peak);
  UNUSED_ARG(paramtodomc);
  throw runtime_error("To Be Implemented Soon!");

  /*
  // 6. Fit peak by the result from Gaussian
  pair<bool, double> fitresult;

  double varA = 1.0;
  double varB = 1.0;


  // a) Get initial chi2
  double startchi2 = DBL_MAX;
  doFit1PeakSimple(peakws, 1, peak, "Levenberg-MarquardtMD", 0, newchi2);
  g_log.debug() << "[DBx401] Peak @ TOF = " << peak->centre() << ", Starting
  Chi^2 = "
                << newchi2 << endl;

  bool continuetofit = true;
  bool goodfit;

  int count = 0;
  size_t numfittohave = 5;
  int maxnumloops = 100;
  vector<pair<double, map<string, double> > > fitparammaps;  // <chi2,
  <parameter, value> >

  map<string, double> curparammap;
  double curchi2 = startchi2;

  srand(0);
  size_t reject = 0;
  size_t count10 = 0;
  double stepratio = 1.0;
  while(continuetofit)
968
  {
969
970
971
972
973
974
975
976
    // a) Store
    storeFunctionParameters(peak, curparammap);

    // b) Monte Carlo
    double aorb = static_cast<double>(rand())/static_cast<double>(RAND_MAX)-0.5;
    double change =
  static_cast<double>(rand())/static_cast<double>(RAND_MAX)-0.5;
    if (aorb > 0)
977
    {
978
979
980
981
982
983
984
985
986
987
988
      // A
      varA = varA*(1+stepratio*change);
      if (varA <= DBL_MIN)
        varA = fabs(varA) + DBL_MIN;
    }
    else
    {
      // B
      varB = varB*(1+stepratio*change);
      if (varB <= DBL_MIN)
        varB = fabs(varB) + DBL_MIN;
989
    }
990

991
992
993
    // b) Set A and B
    peak->setParameter("A", varA);
    peak->setParameter("B", varB);
994

995
996
997
998
    // b) Fit
    g_log.debug() << "DBx329:  Proposed A = " << varA << ", B = " << varB <<
  endl;
    fitresult = doFitPeak(peakws, peak, fwhm);
999

1000
    // c) Get fit result
For faster browsing, not all history is shown. View entire blame