-
Notifications
You must be signed in to change notification settings - Fork 121
/
PoldiFitPeaks2D.cpp
1349 lines (1104 loc) · 47.1 KB
/
PoldiFitPeaks2D.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
#include "MantidSINQ/PoldiFitPeaks2D.h"
#include "MantidAPI/Axis.h"
#include "MantidAPI/FunctionDomain1D.h"
#include "MantidAPI/FunctionFactory.h"
#include "MantidAPI/ILatticeFunction.h"
#include "MantidAPI/IPawleyFunction.h"
#include "MantidAPI/IPeakFunction.h"
#include "MantidAPI/MultiDomainFunction.h"
#include "MantidAPI/TableRow.h"
#include "MantidAPI/WorkspaceFactory.h"
#include "MantidAPI/WorkspaceGroup.h"
#include "MantidDataObjects/Workspace2D.h"
#include "MantidDataObjects/TableWorkspace.h"
#include "MantidGeometry/Crystal/UnitCell.h"
#include "MantidKernel/ListValidator.h"
#include "MantidSINQ/PoldiUtilities/IPoldiFunction1D.h"
#include "MantidSINQ/PoldiUtilities/Poldi2DFunction.h"
#include "MantidSINQ/PoldiUtilities/PoldiInstrumentAdapter.h"
#include "MantidSINQ/PoldiUtilities/PoldiDeadWireDecorator.h"
#include "MantidSINQ/PoldiUtilities/PoldiDGrid.h"
#include "MantidSINQ/PoldiUtilities/PoldiSpectrumDomainFunction.h"
#include "MantidSINQ/PoldiUtilities/PoldiSpectrumLinearBackground.h"
#include "MantidSINQ/PoldiUtilities/PoldiSpectrumPawleyFunction.h"
#include "MantidSINQ/PoldiUtilities/PoldiPeakCollection.h"
#include "boost/make_shared.hpp"
namespace Mantid {
namespace Poldi {
// Register the algorithm into the AlgorithmFactory
DECLARE_ALGORITHM(PoldiFitPeaks2D)
using namespace API;
using namespace Kernel;
using namespace DataObjects;
using namespace Geometry;
/// Algorithm's name for identification. @see Algorithm::name
const std::string PoldiFitPeaks2D::name() const { return "PoldiFitPeaks2D"; }
/// Algorithm's version for identification. @see Algorithm::version
int PoldiFitPeaks2D::version() const { return 1; }
/// Algorithm's category for identification. @see Algorithm::category
const std::string PoldiFitPeaks2D::category() const { return "SINQ\\Poldi"; }
/// Very short algorithm summary. @see Algorith::summary
const std::string PoldiFitPeaks2D::summary() const {
return "Calculates a POLDI 2D-spectrum.";
}
/// Validate inputs for algorithm in case PawleyFit is used.
std::map<std::string, std::string> PoldiFitPeaks2D::validateInputs() {
std::map<std::string, std::string> errorMap;
bool isPawleyFit = getProperty("PawleyFit");
if (isPawleyFit) {
Property *refinedCellParameters =
getPointerToProperty("RefinedCellParameters");
if (refinedCellParameters->isDefault()) {
errorMap["RefinedCellParameters"] = "Workspace name for refined cell "
"parameters must be supplied for "
"PawleyFit.";
}
}
return errorMap;
}
/**
* Extracts a vector of PoldiPeakCollection objects from the input
*
* This method examines what kind of workspace has been supplied to the
* PoldiPeakWorkspace input property and tries to construct a vector
* of peak collections from this. It works with either a single TableWorkspace
* or with a WorkspaceGroups that contains several TableWorkspaces.
*
* If the workspace can not be interpreted properly, the method throws an
* std::invalid_argument exception.
*
* @return Vector with one or more PoldiPeakCollections.
*/
std::vector<PoldiPeakCollection_sptr>
PoldiFitPeaks2D::getPeakCollectionsFromInput() const {
Workspace_sptr peakWorkspace = getProperty("PoldiPeakWorkspace");
std::vector<PoldiPeakCollection_sptr> peakCollections;
// If the input workspace is a TableWorkspace, insert it into the vector and
// return it.
TableWorkspace_sptr peakTable =
boost::dynamic_pointer_cast<TableWorkspace>(peakWorkspace);
if (peakTable) {
try {
peakCollections.push_back(getPeakCollection(peakTable));
} catch (const std::runtime_error &) {
// do nothing
}
return peakCollections;
}
// If it's a WorkspaceGroup there are multiple peak tables, make a collection
// for each of them.
WorkspaceGroup_sptr peakTables =
boost::dynamic_pointer_cast<WorkspaceGroup>(peakWorkspace);
if (peakTables) {
for (size_t i = 0;
i < static_cast<size_t>(peakTables->getNumberOfEntries()); ++i) {
TableWorkspace_sptr peakTable =
boost::dynamic_pointer_cast<TableWorkspace>(peakTables->getItem(i));
if (peakTable) {
try {
peakCollections.push_back(getPeakCollection(peakTable));
} catch (const std::runtime_error &) {
// do nothing
}
}
}
return peakCollections;
}
// Otherwise throw a runtime error.
throw std::runtime_error("Cannot proceed without peak workspace.");
}
/**
* Tries to construct a PoldiPeakCollection from the supplied table.
*
* @param peakTable :: TableWorkspace with POLDI peak data.
* @return PoldiPeakCollection with the data from the table workspace.
*/
PoldiPeakCollection_sptr
PoldiFitPeaks2D::getPeakCollection(const TableWorkspace_sptr &peakTable) const {
try {
return boost::make_shared<PoldiPeakCollection>(peakTable);
} catch (...) {
throw std::runtime_error("Could not initialize peak collection.");
}
}
/// Returns an PoldiPeakCollection with normalized peaks for each input
/// collection.
std::vector<PoldiPeakCollection_sptr>
PoldiFitPeaks2D::getNormalizedPeakCollections(
const std::vector<PoldiPeakCollection_sptr> &peakCollections) const {
std::vector<PoldiPeakCollection_sptr> normalizedPeakCollections;
for (const auto &peakCollection : peakCollections) {
// First integrate peak collection, then normalize and append to vector
PoldiPeakCollection_sptr integratedPeakCollection =
getIntegratedPeakCollection(peakCollection);
normalizedPeakCollections.push_back(
getNormalizedPeakCollection(integratedPeakCollection));
}
return normalizedPeakCollections;
}
/**
* Return peak collection with integrated peaks
*
* This method takes a PoldiPeakCollection where the intensity is represented
* by the maximum. Then it takes the profile function stored in the peak
* collection, which must be the name of a registered
* IPeakFunction-implementation. The parameters height and fwhm are assigned,
* centre is set to 0 to avoid problems with the parameter transformation for
* the integration from -inf to inf. The profiles are integrated using
* a PeakFunctionIntegrator to the precision of 1e-10.
*
* The original peak collection is not modified, a new instance is created.
*
* @param rawPeakCollection :: PoldiPeakCollection
* @return PoldiPeakCollection with integrated intensities
*/
PoldiPeakCollection_sptr PoldiFitPeaks2D::getIntegratedPeakCollection(
const PoldiPeakCollection_sptr &rawPeakCollection) const {
if (!rawPeakCollection) {
throw std::invalid_argument(
"Cannot proceed with invalid PoldiPeakCollection.");
}
if (!isValidDeltaT(m_deltaT)) {
throw std::invalid_argument("Cannot proceed with invalid time bin size.");
}
if (!m_timeTransformer) {
throw std::invalid_argument(
"Cannot proceed with invalid PoldiTimeTransformer.");
}
if (rawPeakCollection->intensityType() == PoldiPeakCollection::Integral) {
/* Intensities are integral already - don't need to do anything,
* except cloning the collection, to make behavior consistent, since
* integrating also results in a new peak collection.
*/
return rawPeakCollection->clone();
}
/* If no profile function is specified, it's not possible to get integrated
* intensities at all and we try to use the one specified by the user
* instead.
*/
std::string profileFunctionName = rawPeakCollection->getProfileFunctionName();
if (!rawPeakCollection->hasProfileFunctionName()) {
profileFunctionName = getPropertyValue("PeakProfileFunction");
}
std::vector<std::string> allowedProfiles =
FunctionFactory::Instance().getFunctionNames<IPeakFunction>();
if (std::find(allowedProfiles.begin(), allowedProfiles.end(),
profileFunctionName) == allowedProfiles.end()) {
throw std::runtime_error(
"Cannot integrate peak profiles with invalid profile function.");
}
PoldiPeakCollection_sptr integratedPeakCollection =
boost::make_shared<PoldiPeakCollection>(PoldiPeakCollection::Integral);
integratedPeakCollection->setProfileFunctionName(profileFunctionName);
// Preserve unit cell, point group
assignCrystalData(integratedPeakCollection, rawPeakCollection);
for (size_t i = 0; i < rawPeakCollection->peakCount(); ++i) {
PoldiPeak_sptr peak = rawPeakCollection->peak(i);
IPeakFunction_sptr profileFunction =
boost::dynamic_pointer_cast<IPeakFunction>(
FunctionFactory::Instance().createFunction(profileFunctionName));
profileFunction->setHeight(peak->intensity());
profileFunction->setFwhm(peak->fwhm(PoldiPeak::AbsoluteD));
PoldiPeak_sptr integratedPeak = peak->clone();
integratedPeak->setIntensity(UncertainValue(profileFunction->intensity()));
integratedPeakCollection->addPeak(integratedPeak);
}
return integratedPeakCollection;
}
/**
* Normalized the intensities of the given integrated peaks
*
* This function normalizes the peak intensities according to the source
* spectrum, the number of chopper slits and the number of detector elements.
*
* @param peakCollection :: PoldiPeakCollection with integrated intensities
* @return PoldiPeakCollection with normalized intensities
*/
PoldiPeakCollection_sptr PoldiFitPeaks2D::getNormalizedPeakCollection(
const PoldiPeakCollection_sptr &peakCollection) const {
if (!peakCollection) {
throw std::invalid_argument(
"Cannot proceed with invalid PoldiPeakCollection.");
}
if (!m_timeTransformer) {
throw std::invalid_argument("Cannot proceed without PoldiTimeTransformer.");
}
PoldiPeakCollection_sptr normalizedPeakCollection =
boost::make_shared<PoldiPeakCollection>(PoldiPeakCollection::Integral);
normalizedPeakCollection->setProfileFunctionName(
peakCollection->getProfileFunctionName());
// Carry over unit cell and point group
assignCrystalData(normalizedPeakCollection, peakCollection);
for (size_t i = 0; i < peakCollection->peakCount(); ++i) {
PoldiPeak_sptr peak = peakCollection->peak(i);
double calculatedIntensity =
m_timeTransformer->calculatedTotalIntensity(peak->d());
PoldiPeak_sptr normalizedPeak = peak->clone();
normalizedPeak->setIntensity(peak->intensity() / calculatedIntensity);
normalizedPeakCollection->addPeak(normalizedPeak);
}
return normalizedPeakCollection;
}
/// Returns a vector of peak collections extracted from the function
std::vector<PoldiPeakCollection_sptr> PoldiFitPeaks2D::getCountPeakCollections(
const API::IFunction_sptr &fitFunction) {
Poldi2DFunction_sptr poldiFunction =
boost::dynamic_pointer_cast<Poldi2DFunction>(fitFunction);
if (!poldiFunction) {
throw std::runtime_error("Can only extract peaks from Poldi2DFunction.");
}
// Covariance matrix - needs to be assigned to the member functions for error
// calculation
boost::shared_ptr<const Kernel::DblMatrix> covarianceMatrix =
poldiFunction->getCovarianceMatrix();
std::vector<PoldiPeakCollection_sptr> countPeakCollections;
size_t offset = 0;
for (size_t i = 0; i < poldiFunction->nFunctions(); ++i) {
IFunction_sptr localFunction = poldiFunction->getFunction(i);
size_t nLocalParams = localFunction->nParams();
// Assign local covariance matrix.
boost::shared_ptr<Kernel::DblMatrix> localCov =
getLocalCovarianceMatrix(covarianceMatrix, offset, nLocalParams);
localFunction->setCovarianceMatrix(localCov);
try {
PoldiPeakCollection_sptr normalizedPeaks =
getPeakCollectionFromFunction(localFunction);
countPeakCollections.push_back(getCountPeakCollection(normalizedPeaks));
} catch (const std::invalid_argument &) {
// not a Poldi2DFunction - skip (the background functions)
}
offset += nLocalParams;
}
return countPeakCollections;
}
/**
* Converts normalized peak intensities to count based integral intensities
*
* This operation is the opposite of getNormalizedPeakCollection and is used
* to convert the intensities back to integral intensities.
*
* @param peakCollection :: PoldiPeakCollection with normalized intensities
* @return PoldiPeakCollection with integral intensities
*/
PoldiPeakCollection_sptr PoldiFitPeaks2D::getCountPeakCollection(
const PoldiPeakCollection_sptr &peakCollection) const {
if (!peakCollection) {
throw std::invalid_argument(
"Cannot proceed with invalid PoldiPeakCollection.");
}
if (!m_timeTransformer) {
throw std::invalid_argument("Cannot proceed without PoldiTimeTransformer.");
}
PoldiPeakCollection_sptr countPeakCollection =
boost::make_shared<PoldiPeakCollection>(PoldiPeakCollection::Integral);
countPeakCollection->setProfileFunctionName(
peakCollection->getProfileFunctionName());
// Get crystal data into new peak collection
assignCrystalData(countPeakCollection, peakCollection);
for (size_t i = 0; i < peakCollection->peakCount(); ++i) {
PoldiPeak_sptr peak = peakCollection->peak(i);
double calculatedIntensity =
m_timeTransformer->calculatedTotalIntensity(peak->d());
PoldiPeak_sptr countPeak = peak->clone();
countPeak->setIntensity(peak->intensity() * calculatedIntensity);
countPeakCollection->addPeak(countPeak);
}
return countPeakCollection;
}
/// Creates a PoldiPeak from the given profile function/hkl pair.
PoldiPeak_sptr
PoldiFitPeaks2D::getPeakFromPeakFunction(IPeakFunction_sptr profileFunction,
const V3D &hkl) {
// Use EstimatePeakErrors to calculate errors of FWHM and so on
IAlgorithm_sptr errorAlg = createChildAlgorithm("EstimatePeakErrors");
errorAlg->setProperty(
"Function", boost::dynamic_pointer_cast<IFunction>(profileFunction));
errorAlg->setPropertyValue("OutputWorkspace", "Errors");
errorAlg->execute();
double centre = profileFunction->centre();
double fwhmValue = profileFunction->fwhm();
ITableWorkspace_sptr errorTable = errorAlg->getProperty("OutputWorkspace");
double centreError = errorTable->cell<double>(0, 2);
double fwhmError = errorTable->cell<double>(2, 2);
UncertainValue d(centre, centreError);
UncertainValue fwhm(fwhmValue, fwhmError);
UncertainValue intensity;
bool useIntegratedIntensities = getProperty("OutputIntegratedIntensities");
if (useIntegratedIntensities) {
double integratedIntensity = profileFunction->intensity();
double integratedIntensityError = errorTable->cell<double>(3, 2);
intensity = UncertainValue(integratedIntensity, integratedIntensityError);
} else {
double height = profileFunction->height();
double heightError = errorTable->cell<double>(1, 2);
intensity = UncertainValue(height, heightError);
}
// Create peak with extracted parameters and supplied hkl
PoldiPeak_sptr peak =
PoldiPeak::create(MillerIndices(hkl), d, intensity, UncertainValue(1.0));
peak->setFwhm(fwhm, PoldiPeak::FwhmRelation::AbsoluteD);
return peak;
}
/**
* Constructs a proper function from a peak collection
*
* This method constructs a Poldi2DFunction depending on whether or not a
* Pawley fit is performed each peak contained in the peak collection.
*
* @param peakCollection :: PoldiPeakCollection containing peaks with integral
* intensities
* @return Poldi2DFunction with one PoldiSpectrumDomainFunction per peak
*/
Poldi2DFunction_sptr PoldiFitPeaks2D::getFunctionFromPeakCollection(
const PoldiPeakCollection_sptr &peakCollection) {
std::string profileFunctionName = getProperty("PeakProfileFunction");
bool pawleyFit = getProperty("PawleyFit");
if (pawleyFit) {
return getFunctionPawley(profileFunctionName, peakCollection);
}
// Only use ties for independent peaks.
Poldi2DFunction_sptr poldi2DFunction =
getFunctionIndividualPeaks(profileFunctionName, peakCollection);
std::string ties = getUserSpecifiedTies(poldi2DFunction);
if (!ties.empty()) {
poldi2DFunction->addTies(ties);
}
return poldi2DFunction;
}
/**
* Returns a Poldi2DFunction that encapsulates individual peaks
*
* This function takes all peaks from the supplied peak collection and
* generates an IPeakFunction of the type given in the name parameter, wraps
* them in a Poldi2DFunction and returns it.
*
* @param profileFunctionName :: Profile function name.
* @param peakCollection :: Peak collection with peaks to be used in the fit.
* @return :: A Poldi2DFunction with peak profile functions.
*/
Poldi2DFunction_sptr PoldiFitPeaks2D::getFunctionIndividualPeaks(
std::string profileFunctionName,
const PoldiPeakCollection_sptr &peakCollection) const {
auto mdFunction = boost::make_shared<Poldi2DFunction>();
for (size_t i = 0; i < peakCollection->peakCount(); ++i) {
PoldiPeak_sptr peak = peakCollection->peak(i);
boost::shared_ptr<PoldiSpectrumDomainFunction> peakFunction =
boost::dynamic_pointer_cast<PoldiSpectrumDomainFunction>(
FunctionFactory::Instance().createFunction(
"PoldiSpectrumDomainFunction"));
if (!peakFunction) {
throw std::invalid_argument(
"Cannot process null pointer poldi function.");
}
peakFunction->setDecoratedFunction(profileFunctionName);
IPeakFunction_sptr wrappedProfile =
boost::dynamic_pointer_cast<IPeakFunction>(
peakFunction->getProfileFunction());
if (wrappedProfile) {
wrappedProfile->setCentre(peak->d());
wrappedProfile->setFwhm(peak->fwhm(PoldiPeak::AbsoluteD));
wrappedProfile->setIntensity(peak->intensity());
}
mdFunction->addFunction(peakFunction);
}
return mdFunction;
}
/**
* Returns a Poldi2DFunction that encapsulates a PawleyFunction
*
* This function creates a PawleyFunction using the supplied profile function
* name and the crystal system as well as initial cell from the input
* properties of the algorithm and wraps it in a Poldi2DFunction.
*
* The cell is refined using LatticeFunction to get better starting values.
*
* Because the peak intensities are integral at this step but PawleyFunction
* expects peak heights, a profile function is created and
* setIntensity/height-methods are used to convert.
*
* @param profileFunctionName :: Profile function name for PawleyFunction.
* @param peakCollection :: Peak collection with peaks to be used in the fit.
* @return :: A Poldi2DFunction with a PawleyFunction.
*/
Poldi2DFunction_sptr PoldiFitPeaks2D::getFunctionPawley(
std::string profileFunctionName,
const PoldiPeakCollection_sptr &peakCollection) {
auto mdFunction = boost::make_shared<Poldi2DFunction>();
boost::shared_ptr<PoldiSpectrumPawleyFunction> poldiPawleyFunction =
boost::dynamic_pointer_cast<PoldiSpectrumPawleyFunction>(
FunctionFactory::Instance().createFunction(
"PoldiSpectrumPawleyFunction"));
if (!poldiPawleyFunction) {
throw std::invalid_argument("Could not create pawley function.");
}
poldiPawleyFunction->setDecoratedFunction("PawleyFunction");
IPawleyFunction_sptr pawleyFunction =
poldiPawleyFunction->getPawleyFunction();
pawleyFunction->setProfileFunction(profileFunctionName);
// Extract crystal system from peak collection
PointGroup_sptr pointGroup = peakCollection->pointGroup();
if (!pointGroup) {
throw std::invalid_argument("Can not initialize pawley function properly - "
"peaks do not have point group.");
}
std::string latticeSystem = getLatticeSystemFromPointGroup(pointGroup);
pawleyFunction->setLatticeSystem(latticeSystem);
UnitCell cell = peakCollection->unitCell();
// Extract unit cell from peak collection
pawleyFunction->setUnitCell(getRefinedStartingCell(
unitCellToStr(cell), latticeSystem, peakCollection));
IPeakFunction_sptr pFun = boost::dynamic_pointer_cast<IPeakFunction>(
FunctionFactory::Instance().createFunction(profileFunctionName));
for (size_t i = 0; i < peakCollection->peakCount(); ++i) {
PoldiPeak_sptr peak = peakCollection->peak(i);
pFun->setCentre(peak->d());
pFun->setFwhm(peak->fwhm(PoldiPeak::AbsoluteD));
pFun->setIntensity(peak->intensity());
pawleyFunction->addPeak(peak->hkl().asV3D(),
peak->fwhm(PoldiPeak::AbsoluteD), pFun->height());
}
pawleyFunction->fix(pawleyFunction->parameterIndex("f0.ZeroShift"));
mdFunction->addFunction(poldiPawleyFunction);
return mdFunction;
}
/**
* Returns the lattice system for the specified point group
*
* This function simply uses Geometry::getLatticeSystemAsString().
*
* @param pointGroup :: The point group for which to find the crystal system
* @return The crystal system for the point group
*/
std::string PoldiFitPeaks2D::getLatticeSystemFromPointGroup(
const PointGroup_sptr &pointGroup) const {
if (!pointGroup) {
throw std::invalid_argument(
"Cannot return lattice system for null PointGroup.");
}
return Geometry::getLatticeSystemAsString(pointGroup->latticeSystem());
}
/**
* Tries to refine the initial cell using the supplied peaks
*
* This method tries to refine the initial unit cell using the indexed peaks
* that are supplied in the PoldiPeakCollection. If there are unindexed peaks,
* the cell will not be refined at all, instead the unmodified initial cell
* is returned.
*
* @param initialCell :: String with the initial unit cell
* @param crystalSystem :: Crystal system name
* @param peakCollection :: Collection of bragg peaks, must be indexed
*
* @return String for refined unit cell
*/
std::string PoldiFitPeaks2D::getRefinedStartingCell(
const std::string &initialCell, const std::string &latticeSystem,
const PoldiPeakCollection_sptr &peakCollection) {
Geometry::UnitCell cell = Geometry::strToUnitCell(initialCell);
ILatticeFunction_sptr latticeFunction =
boost::dynamic_pointer_cast<ILatticeFunction>(
FunctionFactory::Instance().createFunction("LatticeFunction"));
latticeFunction->setLatticeSystem(latticeSystem);
latticeFunction->fix(latticeFunction->parameterIndex("ZeroShift"));
latticeFunction->setUnitCell(cell);
// Remove errors from d-values
PoldiPeakCollection_sptr clone = peakCollection->clone();
for (size_t i = 0; i < clone->peakCount(); ++i) {
PoldiPeak_sptr peak = clone->peak(i);
// If there are unindexed peaks, don't refine, just return the initial cell
if (peak->hkl() == MillerIndices()) {
return initialCell;
}
peak->setD(UncertainValue(peak->d().value()));
}
TableWorkspace_sptr peakTable = clone->asTableWorkspace();
IAlgorithm_sptr fit = createChildAlgorithm("Fit");
fit->setProperty("Function",
boost::static_pointer_cast<IFunction>(latticeFunction));
fit->setProperty("InputWorkspace", peakTable);
fit->setProperty("CostFunction", "Unweighted least squares");
fit->execute();
Geometry::UnitCell refinedCell = latticeFunction->getUnitCell();
return Geometry::unitCellToStr(refinedCell);
}
/**
* @brief Returns a string with ties that is passed to Fit
*
* This method uses the GlobalParameters property, which may contain a comma-
* separated list of parameter names that should be the same for all peaks.
*
* Parameters that do not exist are silently ignored, but a warning is written
* to the log so that users have a chance to find typos.
*
* @param poldiFn :: Function with some parameters.
* @return :: String to pass to the Ties-property of Fit.
*/
std::string
PoldiFitPeaks2D::getUserSpecifiedTies(const IFunction_sptr &poldiFn) {
std::string tieParameterList = getProperty("GlobalParameters");
if (!tieParameterList.empty()) {
std::vector<std::string> tieParameters;
boost::split(tieParameters, tieParameterList, boost::is_any_of(",;"));
std::vector<std::string> parameters = poldiFn->getParameterNames();
std::vector<std::string> tieComponents;
for (auto &tieParameter : tieParameters) {
if (!tieParameter.empty()) {
std::vector<std::string> matchedParameters;
for (auto ¶meter : parameters) {
if (boost::algorithm::ends_with(parameter, tieParameter)) {
matchedParameters.push_back(parameter);
}
}
switch (matchedParameters.size()) {
case 0:
g_log.warning("Function does not have a parameter called '" +
tieParameter + "', ignoring.");
break;
case 1:
g_log.warning("There is only one peak, no ties necessary.");
break;
default: {
std::string reference = matchedParameters.front();
for (auto par = matchedParameters.begin() + 1;
par != matchedParameters.end(); ++par) {
tieComponents.push_back(*par + "=" + reference);
}
break;
}
}
}
}
if (!tieComponents.empty()) {
return boost::algorithm::join(tieComponents, ",");
}
}
return "";
}
/**
* Construct a PoldiPeakCollection from a Poldi2DFunction
*
* This method performs the opposite operation of
*getFunctionFromPeakCollection.
* It takes a function, checks if it's of the proper type and turns the
* information into a PoldiPeakCollection.
*
* @param Poldi2DFunction with one PoldiSpectrumDomainFunction per peak
* @return PoldiPeakCollection containing peaks with normalized intensities
*/
PoldiPeakCollection_sptr PoldiFitPeaks2D::getPeakCollectionFromFunction(
const IFunction_sptr &fitFunction) {
Poldi2DFunction_sptr poldi2DFunction =
boost::dynamic_pointer_cast<Poldi2DFunction>(fitFunction);
if (!poldi2DFunction) {
throw std::invalid_argument(
"Cannot process function that is not a Poldi2DFunction.");
}
PoldiPeakCollection_sptr normalizedPeaks =
boost::make_shared<PoldiPeakCollection>(PoldiPeakCollection::Integral);
boost::shared_ptr<const Kernel::DblMatrix> covarianceMatrix =
poldi2DFunction->getCovarianceMatrix();
size_t offset = 0;
for (size_t i = 0; i < poldi2DFunction->nFunctions(); ++i) {
boost::shared_ptr<PoldiSpectrumPawleyFunction> poldiPawleyFunction =
boost::dynamic_pointer_cast<PoldiSpectrumPawleyFunction>(
poldi2DFunction->getFunction(i));
// If it's a Pawley function, there are several peaks in one function.
if (poldiPawleyFunction) {
IPawleyFunction_sptr pawleyFunction =
poldiPawleyFunction->getPawleyFunction();
if (pawleyFunction) {
CompositeFunction_sptr decoratedFunction =
boost::dynamic_pointer_cast<CompositeFunction>(
pawleyFunction->getDecoratedFunction());
offset = decoratedFunction->getFunction(0)->nParams();
for (size_t j = 0; j < pawleyFunction->getPeakCount(); ++j) {
IPeakFunction_sptr profileFunction =
pawleyFunction->getPeakFunction(j);
size_t nLocalParams = profileFunction->nParams();
boost::shared_ptr<Kernel::DblMatrix> localCov =
getLocalCovarianceMatrix(covarianceMatrix, offset, nLocalParams);
profileFunction->setCovarianceMatrix(localCov);
// Increment offset for next function
offset += nLocalParams;
V3D peakHKL = pawleyFunction->getPeakHKL(j);
PoldiPeak_sptr peak =
getPeakFromPeakFunction(profileFunction, peakHKL);
normalizedPeaks->addPeak(peak);
}
}
break;
}
// Otherwise, it's just one peak in this function.
boost::shared_ptr<PoldiSpectrumDomainFunction> peakFunction =
boost::dynamic_pointer_cast<PoldiSpectrumDomainFunction>(
poldi2DFunction->getFunction(i));
if (peakFunction) {
IPeakFunction_sptr profileFunction =
boost::dynamic_pointer_cast<IPeakFunction>(
peakFunction->getProfileFunction());
// Get local covariance matrix
size_t nLocalParams = profileFunction->nParams();
boost::shared_ptr<Kernel::DblMatrix> localCov =
getLocalCovarianceMatrix(covarianceMatrix, offset, nLocalParams);
profileFunction->setCovarianceMatrix(localCov);
// Increment offset for next function
offset += nLocalParams;
PoldiPeak_sptr peak =
getPeakFromPeakFunction(profileFunction, V3D(0, 0, 0));
normalizedPeaks->addPeak(peak);
}
}
return normalizedPeaks;
}
/// Assign Miller indices from one peak collection to another.
void PoldiFitPeaks2D::assignMillerIndices(const PoldiPeakCollection_sptr &from,
PoldiPeakCollection_sptr &to) const {
if (!from || !to) {
throw std::invalid_argument("Cannot process invalid peak collections.");
}
if (from->peakCount() != to->peakCount()) {
throw std::runtime_error(
"Cannot assign indices if number of peaks does not match.");
}
for (size_t i = 0; i < from->peakCount(); ++i) {
PoldiPeak_sptr fromPeak = from->peak(i);
PoldiPeak_sptr toPeak = to->peak(i);
toPeak->setHKL(fromPeak->hkl());
}
}
/// Copy crystal data from source to target collection to preserve during
/// integration etc.
void PoldiFitPeaks2D::assignCrystalData(
PoldiPeakCollection_sptr &targetCollection,
const PoldiPeakCollection_sptr &sourceCollection) const {
targetCollection->setUnitCell(sourceCollection->unitCell());
targetCollection->setPointGroup(sourceCollection->pointGroup());
}
/**
* Calculates the 1D diffractogram based on the supplied function
*
* This method takes a fit function and checks whether it implements the
* IPoldiFunction1D interface. If that's the case, it calculates the
* diffractogram based on the function.
*
* @param fitFunction :: IFunction that also implements IPoldiFunction1D.
* @param workspace :: Workspace with POLDI raw data.
* @return :: Q-based diffractogram.
*/
MatrixWorkspace_sptr PoldiFitPeaks2D::get1DSpectrum(
const IFunction_sptr &fitFunction,
const API::MatrixWorkspace_sptr &workspace) const {
// Check whether the function is of correct type
boost::shared_ptr<IPoldiFunction1D> poldiFunction =
boost::dynamic_pointer_cast<IPoldiFunction1D>(fitFunction);
if (!poldiFunction) {
throw std::invalid_argument("Can only process Poldi2DFunctions.");
}
// And that we have an instrument available
if (!m_poldiInstrument) {
throw std::runtime_error("No POLDI instrument available.");
}
PoldiAbstractDetector_sptr detector(new PoldiDeadWireDecorator(
workspace->detectorInfo(), m_poldiInstrument->detector()));
std::vector<int> indices = detector->availableElements();
// Create the grid for the diffractogram and corresponding domain/values
double lambdaMin = getProperty("LambdaMin");
double lambdaMax = getProperty("LambdaMax");
PoldiDGrid grid(detector, m_poldiInstrument->chopper(), m_deltaT,
std::make_pair(lambdaMin, lambdaMax));
FunctionDomain1DVector domain(grid.grid());
FunctionValues values(domain);
// Calculate 1D function
poldiFunction->poldiFunction1D(indices, domain, values);
// Create and return Q-based workspace with spectrum
return getQSpectrum(domain, values);
}
/// Takes a d-based domain and creates a Q-based MatrixWorkspace.
MatrixWorkspace_sptr
PoldiFitPeaks2D::getQSpectrum(const FunctionDomain1D &domain,
const FunctionValues &values) const {
// Put result into workspace, based on Q
MatrixWorkspace_sptr ws1D = WorkspaceFactory::Instance().create(
"Workspace2D", 1, domain.size(), values.size());
MantidVec &xData = ws1D->dataX(0);
MantidVec &yData = ws1D->dataY(0);
size_t offset = values.size() - 1;
for (size_t i = 0; i < values.size(); ++i) {
xData[offset - i] = Conversions::dToQ(domain[i]);
yData[offset - i] = values[i];
}
ws1D->getAxis(0)->setUnit("MomentumTransfer");
return ws1D;
}
/// Returns a TableWorkspace with refined cell parameters and error.
ITableWorkspace_sptr PoldiFitPeaks2D::getRefinedCellParameters(
const IFunction_sptr &fitFunction) const {
Poldi2DFunction_sptr poldi2DFunction =
boost::dynamic_pointer_cast<Poldi2DFunction>(fitFunction);
if (!poldi2DFunction || poldi2DFunction->nFunctions() < 1) {
throw std::invalid_argument(
"Cannot process function that is not a Poldi2DFunction.");
}
// Create a new table for lattice parameters
ITableWorkspace_sptr latticeParameterTable =
WorkspaceFactory::Instance().createTable();
latticeParameterTable->addColumn("str", "Parameter");
latticeParameterTable->addColumn("double", "Value");
latticeParameterTable->addColumn("double", "Error");
// The first function should be PoldiSpectrumPawleyFunction
boost::shared_ptr<PoldiSpectrumPawleyFunction> poldiPawleyFunction =
boost::dynamic_pointer_cast<PoldiSpectrumPawleyFunction>(
poldi2DFunction->getFunction(0));
if (!poldiPawleyFunction) {
throw std::invalid_argument("First function in Poldi2DFunction is not "
"PoldiSpectrumPawleyFunction.");
}
// Get the actual PawleyFunction to extract parameters.
IPawleyFunction_sptr pawleyFunction =
boost::dynamic_pointer_cast<IPawleyFunction>(
poldiPawleyFunction->getDecoratedFunction());
if (pawleyFunction) {
CompositeFunction_sptr pawleyParts =
boost::dynamic_pointer_cast<CompositeFunction>(
pawleyFunction->getDecoratedFunction());
// The first function in PawleyFunction contains the parameters
IFunction_sptr pawleyParameters = pawleyParts->getFunction(0);
for (size_t i = 0; i < pawleyParameters->nParams(); ++i) {
TableRow newRow = latticeParameterTable->appendRow();
newRow << pawleyParameters->parameterName(i)
<< pawleyParameters->getParameter(i)
<< pawleyParameters->getError(i);
}
}
return latticeParameterTable;
}
/**
* Performs the fit and returns the fit algorithm
*
* In this method the actual function fit/calculation is performed
* using the Fit algorithm. After execution the algorithm is returned for
* further processing.
*
* @param peakCollection :: PoldiPeakCollection
* @param matrixWorkspace :: MatrixWorkspace with POLDI instrument and correct
* dimensions
* @return Instance of Fit-algorithm, after execution
*/
IAlgorithm_sptr PoldiFitPeaks2D::calculateSpectrum(
const std::vector<PoldiPeakCollection_sptr> &peakCollections,
const MatrixWorkspace_sptr &matrixWorkspace) {
std::vector<PoldiPeakCollection_sptr> normalizedPeakCollections =
getNormalizedPeakCollections(peakCollections);
// Create a Poldi2DFunction that collects all sub-functions
auto mdFunction = boost::make_shared<Poldi2DFunction>();
// Add one Poldi2DFunction for each peak collection
for (auto &normalizedPeakCollection : normalizedPeakCollections) {
mdFunction->addFunction(
getFunctionFromPeakCollection(normalizedPeakCollection));
}
// And finally background terms
addBackgroundTerms(mdFunction);
IAlgorithm_sptr fit = createChildAlgorithm("Fit", -1, -1, true);
if (!fit) {
throw std::runtime_error("Could not initialize 'Fit'-algorithm.");
}
fit->setProperty("Function",
boost::dynamic_pointer_cast<IFunction>(mdFunction));
fit->setProperty("InputWorkspace", matrixWorkspace);
fit->setProperty("CreateOutput", true);
int maxIterations = getProperty("MaximumIterations");
fit->setProperty("MaxIterations", maxIterations);
fit->setProperty("Minimizer", "Levenberg-MarquardtMD");