-
Notifications
You must be signed in to change notification settings - Fork 122
/
SCDCalibratePanels.cpp
1822 lines (1485 loc) · 71.1 KB
/
SCDCalibratePanels.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
/*WIKI*
This algorithm calibrates sets of Rectangular Detectors in one instrument.
The initial path, time offset,panel widths, panel heights, panel locations and orientation are all
adjusted so the error in q positions from the theoretical q positions is minimized. Also, there
are optimize options that take into account sample position and the need for rigid rotations.
Some features:
1) Panels can be grouped.
All panels in a group will move the same way and rotate the same way. If rigid rotations are
used, each panel is rotated about the center of the instrument, along with panel pixels rotating
around the panel's center. The height and widths of the panels in a group will
all change by the same factor
2) The user can select which quantities to keep fixed during the optimization.
3) The results can be saved to an ISAW-like DetCal file or in an xml file that can be used with the LoadParameter algorithm.
4) Results from a previous optimization can be applied before another optimization is done.
The Levenberg-Marquardt optimization algorithm is used. Later iterations may have too small of changes for the parameters to
get to another optimum value. Restarting allows for the consideration of parameter values further away and also can change
constraints for the parameter values. This is also useful when fine tuning parameters that do not influence the errors as
much as other parameters.
5) There are several output tables indicating the results of the fit
A) ResultWorkspace contains the results from fitting.
-t0 is in microseconds
-L0 is in meters
-*Xoffset,*Yoffset,and *Zoffset are in meters
-*Xrot,*Yrot, and *Zrot are in degrees. Note that Zrot is done first, then Yrot , the Xrot.
B)QErrorWorkspace contains the Error in Q values for each peak, along with other associated information about the peak
C)CovarianceInfo contains the "correlations"(*100) between each of the parameters
6) Maximum changes in the quantities that are altered during optimization are now settable.
== "A" Workflow ==
Optimizing all variables at once may not be the best option. The errors become too large, so optimization in several stages
subsets of the variables are optimized at each stage.
First: NOTE that the input PeaksWorkspace does NOT CHANGE. This means you should be able to keep trying different sets of
variables until things look good.
To work on another set of variables with the optimized first round of optimized values
#Use Preprocessinstrument to apply the previous DetCal or xml file before optimizing AND
#Change the name of the target DetCal file, in case the choice of variables is not good. Then you will not clobber the good
DetCal file. AND
#Change the name of the ResultWorkspace in the properties list. This means you will have a copy of the results from the
previous trial(s)( along with chiSq values) to compare results.
Do check the chiSquared values. If they do not decrease, you were close to a minimum and the optimization could not get back
to that minimum. It makes a large jump at the beginning.
== After Calibration ==
After calibration, you can save the workspace to Nexus (or Nexus processed) and get it back by loading in a later Mantid session.
You can copy the calibration to another workspace using the same instrument by means of the [[CopyInstrumentParameters]] algorithm.
To do so select the workspace, which you have calibrated as the InputWorkspace and the workspace you want to copy the calibration to, the OutputWorkspace.
*WIKI*/
#include "MantidCrystal/SCDCalibratePanels.h"
#include "MantidAPI/Algorithm.h"
#include "MantidAPI/ConstraintFactory.h"
#include "MantidDataObjects/PeaksWorkspace.h"
#include "MantidDataObjects/Workspace2D.h"
#include "MantidGeometry/Instrument.h"
#include "MantidGeometry/IComponent.h"
#include "MantidGeometry/Instrument/RectangularDetector.h"
#include "MantidAPI/MatrixWorkspace.h"
#include "MantidKernel/BoundedValidator.h"
#include "MantidKernel/EnabledWhenProperty.h"
#include "MantidGeometry/Instrument/ParameterMap.h"
#include "MantidKernel/V3D.h"
#include "MantidKernel/Quat.h"
#include "MantidAPI/FileProperty.h"
#include "MantidKernel/ListValidator.h"
#include "MantidAPI/Workspace.h"
#include "MantidAPI/IFunction.h"
#include "MantidAPI/FunctionFactory.h"
#include "MantidAPI/IFunction1D.h"
#include "MantidAPI/ITableWorkspace.h"
#include <boost/algorithm/string/trim.hpp>
#include <iostream>
#include <fstream>
#include <math.h>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include "MantidKernel/Property.h"
#include "MantidAPI/IFunction.h"
#include "MantidGeometry/Instrument/RectangularDetector.h"
#include "MantidGeometry/Crystal/IndexingUtils.h"
#include "MantidGeometry/Crystal/OrientedLattice.h"
using namespace Mantid::DataObjects;
using namespace Mantid::API;
using namespace std;
using namespace Mantid::Geometry;
using namespace Mantid::Kernel;
namespace Mantid
{
namespace Crystal
{
Kernel::Logger& SCDCalibratePanels::g_log = Kernel::Logger::get("SCDCalibratePanels");
DECLARE_ALGORITHM(SCDCalibratePanels)
namespace
{
const double MAX_DET_HW_SCALE = 1.15;
const double MIN_DET_HW_SCALE = 0.85;
const double RAD_TO_DEG = 180. / M_PI;
}
SCDCalibratePanels::SCDCalibratePanels():API::Algorithm()
{
// g_log.setLevel(7);
}
SCDCalibratePanels::~SCDCalibratePanels()
{
}
const std::string SCDCalibratePanels::name() const
{
return "SCDCalibratePanels";
}
int SCDCalibratePanels::version() const
{
return 1;
}
const std::string SCDCalibratePanels::category() const
{
return "Crystal";
}
/**
* Converts a Quaternion to a corresponding matrix produce Rotx*Roty*Rotz, corresponding to the order
* Mantid uses in calculating rotations
* @param Q The Quaternion. It will be normalized to represent a rotation
* @param Rotx The angle in degrees for rotating around the x-axis
* @param Roty The angle in degrees for rotating around the y-axis
* @param Rotz The angle in degrees for rotating around the z-axis
*/
void SCDCalibratePanels::Quat2RotxRotyRotz(const Quat Q, double &Rotx,double &Roty,double &Rotz)
{
Quat R(Q);
R.normalize();
V3D X(1,0,0);
V3D Y(0,1,0);
V3D Z(0,0,1);
R.rotate(X);
R.rotate(Y);
R.rotate(Z);
if (Z[ 1 ] != 0 || Z[ 2 ] != 0)
{
double tx = atan2(-Z[ 1 ], Z[ 2 ]);
double tz = atan2(-Y[ 0 ], X[ 0 ]);
double cosy = Z[ 2 ] / cos(tx);
double ty = atan2(Z[ 0 ], cosy);
Rotx = (tx * RAD_TO_DEG);
Roty = (ty * RAD_TO_DEG);
Rotz = (tz * RAD_TO_DEG);
}
else //roty = 90 0r 270 def
{
double k= 1;
if( Z[ 0 ] < 0 )
k=-1;
double roty=k*90;
double rotx=0;
double rotz= atan2(X[ 2 ],Y[ 2 ]);
Rotx = (rotx * RAD_TO_DEG);
Roty = (roty * RAD_TO_DEG);
Rotz = (rotz * RAD_TO_DEG);
}
}
/**
* Creates the Workspace that will be supplied to the SCDPanelErrors Fit function
* @param pwks The peaks workspace of indexed peaks.
* @param bankNames The bank names where all banks from Group 0 are first, Group 1 are second, etc.
* @param tolerance If h,k, and l values are not rounded, this is the indexing tolerance for a peak to be included.
* NOTE: if rounded, only indexed peaks( h,k,l values not all 0) are included.
* @param bounds The positions in bankNames vector of the start of Group * peaks
*/
DataObjects::Workspace2D_sptr SCDCalibratePanels::calcWorkspace( DataObjects::PeaksWorkspace_sptr & pwks,
vector< string>& bankNames,
double tolerance, vector< int >&bounds)
{
int N=0;
if( tolerance <= 0)
tolerance = .5;
tolerance = min< double >(.5, tolerance);
// For the fake data the values are
// X = peak index (repeated 3 times
// Y = 0. as the function evals to (Q-vec) - (UB * hkl * 2pi)
// E = the weighting as used in the cost function
Mantid::MantidVecPtr pX;
Mantid::MantidVec& xRef = pX.access();
Mantid::MantidVecPtr yvals;
Mantid::MantidVec &yvalB = yvals.access();
Mantid::MantidVecPtr errs;
Mantid::MantidVec &errB = errs.access();
bounds.clear();
bounds.push_back(0);
for (size_t k = 0; k < bankNames.size(); ++k)
{
for (int j = 0; j < pwks->getNumberPeaks(); ++j)
{
const API::IPeak& peak = pwks->getPeak((int) j);
if (std::find(bankNames.begin(), bankNames.end(), peak.getBankName()) != bankNames.end())
if (IndexingUtils::ValidIndex(peak.getHKL(), tolerance))
{
N += 3;
// 1/sigma is considered the weight for the fit
double weight = 1.; // default is even weighting
if (peak.getSigmaIntensity() > 0.) // prefer weight by sigmaI
weight = 1./peak.getSigmaIntensity();
else if (peak.getIntensity() > 0.) // next favorite weight by I
weight = 1./peak.getIntensity();
else if (peak.getBinCount() > 0.) // then by counts in peak centre
weight = 1./peak.getBinCount();
const double PEAK_INDEX = static_cast<double>(j);
for (size_t i = 0; i < 3; ++i)
{
xRef.push_back(PEAK_INDEX);
errB.push_back(weight);
}
}
}//for @ peak
bounds.push_back(N);
}//for @ bank name
yvalB.assign(xRef.size(), 0.0);
if( N < 4)//If not well indexed
return boost::shared_ptr<DataObjects::Workspace2D>(new DataObjects::Workspace2D);
MatrixWorkspace_sptr mwkspc
= API::WorkspaceFactory::Instance().create("Workspace2D",1,3*N,3*N);
mwkspc->setX(0, pX);
mwkspc->setData(0, yvals, errs);
return boost::dynamic_pointer_cast< DataObjects::Workspace2D >(mwkspc);
}
/**
* Converts the Grouping indicated by the user to an internal more usable form
* @param AllBankNames All the bang names
* @param Grouping The Grouping choice(one per bank, all together or specify)
* @param bankPrefix The prefix for the bank names
* @param bankingCode If Grouping Choice is specify, this is what the user specifies along with bankPrefix
* @param &Groups The internal form for grouping.
*/
void SCDCalibratePanels::CalculateGroups(set< string >& AllBankNames, string Grouping, string bankPrefix,
string bankingCode, vector<vector< string > > &Groups)
{
Groups.clear();
if( Grouping == "OnePanelPerGroup" )
{
for( set< string >::iterator it = AllBankNames.begin(); it != AllBankNames.end(); ++it )
{
string bankName = (*it);
vector< string > vbankName;
vbankName.push_back( bankName );
Groups.push_back( vbankName );
}
}else if( Grouping == "AllPanelsInOneGroup" )
{
vector< string > vbankName;
for( set< string >::iterator it = AllBankNames.begin(); it != AllBankNames.end(); ++it )
{
string bankName = (*it);
vbankName.push_back( bankName);
}
Groups.push_back(vbankName);
}else if( Grouping == "SpecifyGroups" )
{
boost::trim(bankingCode);
vector< string > GroupA;
boost::split(GroupA, bankingCode, boost::is_any_of("]"));
set< string > usedInts;
for( size_t Gr = 0; Gr < GroupA.size(); ++Gr )
{
string S = GroupA[ Gr ];
boost::trim(S);
if( S.empty()) break;
if (S[0]==',')
S.erase(0,1);
boost::trim(S);
if( S[0]=='[')
S.erase(0, 1);
boost::trim(S);
vector< string >GroupB;
boost::split( GroupB, S, boost::is_any_of(","));
vector< string > Group0;
for( size_t panelRange = 0; panelRange < GroupB.size(); ++panelRange )
{
string rangeOfBanks = GroupB[ panelRange ];
boost::trim(rangeOfBanks);
vector< string > StrtStopStep;
boost::split( StrtStopStep, rangeOfBanks, boost::is_any_of(":") );
if( StrtStopStep.size() > 3 )
{
g_log.error("Improper use of : in " + rangeOfBanks);
throw invalid_argument("Improper use of : in " + rangeOfBanks);
}
int start, stop ,step;
step = 1;
if( StrtStopStep.size() == 3)
{
boost::trim(StrtStopStep[2]);
step = boost::lexical_cast<int>(StrtStopStep[ 2 ]);
if( step <=0 ) step = 0;
}
start = -1;
if( !StrtStopStep.empty())
{
boost::trim(StrtStopStep[0]);
start = boost::lexical_cast<int>(StrtStopStep[ 0 ].c_str());
}
if( start <= 0)
{
g_log.error( "Improper use of : in " + rangeOfBanks );
throw invalid_argument("Improper use of : in " + rangeOfBanks );
}
stop = start;
if( StrtStopStep.size() >= 2 )
{
boost::trim(StrtStopStep[1]);
stop = boost::lexical_cast<int>(StrtStopStep[ 1 ].c_str());
if( stop <=0 ) stop = start;
}
for (long ind = start; ind <= stop; ind += step)
{
ostringstream oss (ostringstream::out);
oss<<bankPrefix<<ind;
string bankName = oss.str();
string postName = bankName.substr(bankPrefix.length());
if (AllBankNames.find(string(bankName) )!= AllBankNames.end())
if (usedInts.find(postName) == usedInts.end())
{
Group0.push_back( bankName );
usedInts.insert( postName );
}
}
}
if( !Group0.empty())
Groups.push_back( Group0 );
}
}
else
{
g_log.error("No mode " + Grouping + " defined yet");
throw invalid_argument("No mode " + Grouping + " defined yet");
}
}
/**
* Modifies the instrument to correspond to an already modified instrument
*
* @param instrument The base instrument to be modified with a parameterMap
* @param preprocessCommand Type of preprocessing file with modification information
* @param preprocessFilename The name of the file with preprocessing information
* @param timeOffset The time offset in preprocessing if used
* @param L0 The initial path length from the preprocessing file if used
* @param AllBankNames The names of all the banks of interest in this instrument
*/
boost::shared_ptr<const Instrument> SCDCalibratePanels::GetNewCalibInstrument(
boost::shared_ptr<const Instrument> instrument,
string preprocessCommand,
string preprocessFilename,
double &timeOffset,
double &L0,
vector< string > & AllBankNames)
{
if( preprocessCommand == "A)No PreProcessing")
return instrument;
bool xml =
( preprocessCommand == "C)Apply a LoadParameter.xml type file");
boost::shared_ptr<const ParameterMap> pmap0 = instrument->getParameterMap();
boost::shared_ptr<ParameterMap> pmap1( new ParameterMap());
for( vector< string >::iterator vit = AllBankNames.begin();
vit != AllBankNames.end(); ++vit )
{
string bankName = (*vit);
updateBankParams( instrument->getComponentByName(bankName), pmap1, pmap0);
}
//---------------------update params for moderator.------------------------------
boost::shared_ptr<const Instrument> newInstr(new Instrument(instrument->baseInstrument(), pmap1));
double L1, norm = 1.0;
V3D beamline, sampPos;
instrument->getInstrumentParameters(L1, beamline, norm, sampPos);
FixUpSourceParameterMap(newInstr, L0, sampPos, pmap0);
if( xml)
{
vector<int> detIDs = instrument->getDetectorIDs();
MatrixWorkspace_sptr wsM = WorkspaceFactory::Instance().create("Workspace2D", detIDs.size(),
(size_t) 100, (size_t) 100);
Workspace2D_sptr ws = boost::dynamic_pointer_cast<DataObjects::Workspace2D>(wsM);
ws->setInstrument(newInstr);
ws->populateInstrumentParameters();
boost::shared_ptr<Algorithm> loadParFile = createChildAlgorithm("LoadParameterFile");
loadParFile->initialize();
loadParFile->setProperty("Workspace", ws);
loadParFile->setProperty("Filename", preprocessFilename);
loadParFile->executeAsChildAlg();
boost::shared_ptr<const Instrument> newInstrument = ws->getInstrument();
newInstrument->getInstrumentParameters(L0, beamline, norm, sampPos);
return newInstrument;
}else
{ set<string>bankNames;
LoadISawDetCal(newInstr,bankNames,timeOffset,L0,preprocessFilename,
"bank");
return newInstr;
}
}
/**
* Calculates initial parameters for the fitting parameters
* @param bank_rect The bank(panel)
* @param instrument The instrument
* @param PreCalibinstrument The instrument with precalibrated values incorporated
* @param detWidthScale0 The ratio of base instrument to PreCalib Instrument for this panel's width
* @param detHeightScale0 The ratio of base instrument to PreCalib Instrument for this panel's height
* @param Xoffset0 The difference between base instrument and PreCalib Instrument for this panel's center X
* @param Yoffset0 The difference between base instrument and PreCalib Instrument for this panel's center Y
* @param Zoffset0 The difference between base instrument and PreCalib Instrument for this panel's center Z
* @param Xrot0 The difference between base instrument and PreCalib Instrument for this panel's Rot in X direction
* @param Yrot0 The difference between base instrument and PreCalib Instrument for this panel's Rot in Y direction
* @param Zrot0 The difference between base instrument and PreCalib Instrument for this panel's Rot in Z direction
*/
void SCDCalibratePanels::CalcInitParams( RectangularDetector_const_sptr bank_rect,
Instrument_const_sptr instrument,
Instrument_const_sptr PreCalibinstrument,
double & detWidthScale0,double &detHeightScale0,
double &Xoffset0,double &Yoffset0,double &Zoffset0,
double &Xrot0,double &Yrot0,double &Zrot0)
{
string bankName = bank_rect->getName();
RectangularDetector_const_sptr newBank =
boost::dynamic_pointer_cast<const RectangularDetector>
( PreCalibinstrument->getComponentByName( bankName) );
if( !newBank)
{
detWidthScale0 = 1;
detHeightScale0 = 1;
Xoffset0 = 0;
Yoffset0 = 0;
Zoffset0 = 0;
Xrot0 = 0;
Yrot0 = 0;
Zrot0 = 0;
g_log.notice() << "Improper PreCalibInstrument for " << bankName << endl;
return;
}
boost::shared_ptr<Geometry::ParameterMap> pmap = instrument->getParameterMap();
boost::shared_ptr<Geometry::ParameterMap> pmapPre = PreCalibinstrument->getParameterMap();
vector< V3D > RelPosI = pmap->getV3D(bankName,"pos");
vector< V3D > RelPosPre = pmapPre->getV3D(bankName,"pos");
V3D posI,
posPre;
if(!RelPosI.empty())
posI = RelPosI[ 0 ];
else
posI = bank_rect->getRelativePos();
if(!RelPosPre.empty())
posPre = RelPosPre[ 0 ];
else
posPre = newBank->getRelativePos();
V3D change = posPre -posI;
Xoffset0 = change.X();
Yoffset0 = change.Y();
Zoffset0 = change.Z();
double scalexI = 1.;
double scalexPre = 1.;
double scaleyI = 1.;
double scaleyPre = 1.;
vector< double > ScalexI = pmap->getDouble( bankName, "scalex");
vector< double > ScalexPre = pmapPre->getDouble( bankName, "scalex");
vector< double > ScaleyI = pmap->getDouble( bankName, "scaley");
vector< double > ScaleyPre = pmapPre->getDouble( bankName, "scaley");
if( !ScalexI.empty())
scalexI = ScalexI[ 0 ];
if( !ScaleyI.empty())
scaleyI = ScaleyI[ 0 ];
if(!ScalexPre.empty())
scalexPre = ScalexPre[ 0 ];
if( !ScaleyPre.empty())
scaleyPre = ScaleyPre[ 0 ];
//scaling
detWidthScale0 = scalexPre/scalexI;
detHeightScale0 = scaleyPre/scaleyI;
Quat rotI = bank_rect->getRelativeRot();
Quat rotPre = newBank->getRelativeRot();
rotI.inverse();
Quat ChgRot = rotPre*rotI;
Quat2RotxRotyRotz(ChgRot,Xrot0,Yrot0,Zrot0);
}
/**
* Tests inputs. Does the indexing correspond to the entered lattice parameters
* @param peaksWs The peaks workspace with indexed peaks
* @param a The lattice parameter a
* @param b The lattice parameter b
* @param c The lattice parameter c
* @param alpha The lattice parameter alpha
* @param beta The lattice parameter beta
* @param gamma The lattice parameter gamma
* @param tolerance The indexing tolerance
*/
bool GoodStart(const PeaksWorkspace_sptr &peaksWs, double a, double b, double c, double alpha,
double beta, double gamma, double tolerance)
{
// put together a list of indexed peaks
std::vector<V3D> hkl;
hkl.reserve(peaksWs->getNumberPeaks());
std::vector<V3D> qVecs;
qVecs.reserve(peaksWs->getNumberPeaks());
for (int i = 0; i < peaksWs->getNumberPeaks(); i++)
{
const Peak & peak = peaksWs->getPeak(i);
if (IndexingUtils::ValidIndex(peak.getHKL(), tolerance))
{
hkl.push_back(peak.getHKL());
qVecs.push_back(peak.getQSampleFrame());
}
}
// determine the lattice constants
Kernel::Matrix<double>UB(3,3);
IndexingUtils::Optimize_UB( UB, hkl,qVecs);
std::vector<double>lat(70);
IndexingUtils::GetLatticeParameters( UB, lat);
// see if the lattice constants are no worse than 25% out
if( fabs(lat[0]-a)/a >.25) return false;
if( fabs(lat[1]-b)/b >.25) return false;
if( fabs(lat[2]-c)/c >.25) return false;
if( fabs(lat[3]-alpha)/alpha >.25) return false;
if( fabs(lat[4]-beta)/beta >.25) return false;
if( fabs(lat[5]-gamma)/gamma >.25) return false;
return true;
}
namespace { // anonymous namespace
/**
* Adds a tie to the IFunction.
* @param iFunc The function to add the tie to.
* @param tie Whether or not to actually do it.
* @param parName The name of the parameter to tie.
* @param value The value to tie it to.
*/
static inline void tie(IFunction_sptr & iFunc, const bool tie, const string &parName, const double value)
{
if (!tie) return;
std::ostringstream ss;
ss << std::fixed << value;
iFunc->tie(parName, ss.str());
}
static inline void constrain(IFunction_sptr & iFunc, const string &parName,
const double min, const double max)
{
std::ostringstream ss;
ss << std::fixed << min
<< "<" << parName << "<"
<< std::fixed << max;
IConstraint * constraint = API::ConstraintFactory::Instance().createInitialized(iFunc.get(), ss.str());
iFunc->addConstraint(constraint);
}
} // end anonymous namespace
void SCDCalibratePanels::exec ()
{
PeaksWorkspace_sptr peaksWs = getProperty("PeakWorkspace");
double a = getProperty("a");
double b = getProperty("b");
double c = getProperty("c");
double alpha = getProperty("alpha");
double beta = getProperty("beta");
double gamma = getProperty("gamma");
if ((a == EMPTY_DBL() || b == EMPTY_DBL() || c == EMPTY_DBL() || alpha == EMPTY_DBL() ||
beta == EMPTY_DBL() || gamma == EMPTY_DBL()) && peaksWs->sample().hasOrientedLattice())
{
OrientedLattice latt = peaksWs->mutableSample().getOrientedLattice();
a = latt.a();
b = latt.b();
c = latt.c();
alpha = latt.alpha();
beta = latt.beta();
gamma = latt.gamma();
}
double tolerance = getProperty("tolerance");
if( !GoodStart( peaksWs, a,b,c,alpha,beta,gamma,tolerance))
{
g_log.warning()<<"**** Indexing is NOT compatible with given lattice parameters******"<<std::endl;
g_log.warning()<<" Index with conventional orientation matrix???"<<std::endl;
}
bool useL0 = getProperty("useL0");
bool useTimeOffset = getProperty("useTimeOffset");
bool use_PanelWidth = getProperty("usePanelWidth");
bool use_PanelHeight = getProperty("usePanelHeight");
bool use_PanelPosition = getProperty("usePanelPosition");
bool use_PanelOrientation = getProperty("usePanelOrientation");
double SampleXoffset = getProperty("SampleXoffset");
double SampleYoffset = getProperty("SampleYoffset");
double SampleZoffset = getProperty("SampleZoffset");
string Grouping = getProperty( "PanelGroups");
string bankPrefix = getProperty("PanelNamePrefix");
string bankingCode = getProperty("Grouping");
//----------------- Set Up Bank Name Vectors -------------------------
set< string > AllBankNames;
for( int i = 0; i < peaksWs->getNumberPeaks(); ++i)
AllBankNames.insert( peaksWs->getPeak(i).getBankName());
vector<vector< string > >Groups;
CalculateGroups( AllBankNames, Grouping, bankPrefix, bankingCode, Groups );
vector< string >banksVec;
for(auto group = Groups.begin(); group != Groups.end(); ++group )
{
for( auto bankName = group->begin(); bankName!=group->end(); ++bankName )
{
banksVec.push_back(*bankName);
}
}
//------------------ Set Up Workspace for IFitFunction Fit---------------
vector< int >bounds;
Workspace2D_sptr ws = calcWorkspace( peaksWs, banksVec,tolerance, bounds );
//----------- Initialize peaksWorkspace, initial parameter values etc.---------
boost::shared_ptr<const Instrument> instrument = peaksWs->getPeak(0).getInstrument();
double T0 = 0;
if((string) getProperty("PreProcessInstrument") == "C)Apply a LoadParameter.xml type file")
T0= getProperty("InitialTimeOffset");//!*****
double L0 = peaksWs->getPeak(0).getL1();
boost::shared_ptr<const Instrument> PreCalibinstrument =
GetNewCalibInstrument(instrument,
(string) getProperty("PreProcessInstrument"),
(string) getProperty("PreProcFilename"),
T0, L0, banksVec);
g_log.debug()<<"Initial L0,T0="<<L0<<","<<T0<<endl;
V3D samplePos = peaksWs->getPeak( 0 ).getInstrument()->getSample()->getPos();
string PeakWSName = getPropertyValue( "PeakWorkspace");
if(PeakWSName.length()<1)
{
PeakWSName = "xxx";
AnalysisDataService::Instance().addOrReplace("xxx",peaksWs );
}
int nbanksSoFar = 0;
int NGroups = (int)Groups.size();
double detWidthScale0,
detHeightScale0,
Xoffset0,
Yoffset0,
Zoffset0,
Xrot0,
Yrot0,
Zrot0;
//------------------- For each Group set up Function, --------------------------
//---------------Ties, and Constraint Properties for Fit algorithm--------------------
// set up the string for specifying groups
string BankNameString = "";
for(auto group = Groups.begin(); group !=Groups.end(); ++group)
{
if( group != Groups.begin())
BankNameString +="!";
for(auto bank = group->begin(); bank !=group->end(); ++bank)
{
if( bank != group->begin())
BankNameString +="/";
BankNameString += (*bank);
}
}
int RotGroups=0;
if( getProperty("RotateCenters"))
RotGroups=1;
int SampOffsets=0;
if( getProperty("AllowSampleShift"))
SampOffsets=1;
// first round of function setup
IFunction_sptr iFunc = FunctionFactory::Instance().createFunction("SCDPanelErrors");
iFunc->setAttributeValue("PeakWorkspaceName", PeakWSName);
iFunc->setAttributeValue("a", a);
iFunc->setAttributeValue("b", b);
iFunc->setAttributeValue("c", c);
iFunc->setAttributeValue("alpha", alpha);
iFunc->setAttributeValue("beta", beta);
iFunc->setAttributeValue("gamma", gamma);
iFunc->setAttributeValue("NGroups", NGroups);
iFunc->setAttributeValue("BankNames", BankNameString);
iFunc->setAttributeValue("startX", -1);
iFunc->setAttributeValue("endX", -1);
iFunc->setAttributeValue("RotateCenters", RotGroups);
iFunc->setAttributeValue("SampleOffsets", SampOffsets);
iFunc->setParameter("l0", L0);
iFunc->setParameter("t0", T0);
double maxXYOffset = getProperty("MaxPositionChange_meters");
int i = -1;//position in ParamResults Array.
for(auto group = Groups.begin(); group !=Groups.end(); ++group)
{
i++;
boost::shared_ptr<const RectangularDetector> bank_rect;
string paramPrefix ="f"+ boost::lexical_cast<string>(i)+"_";
string name = group->front();
boost::shared_ptr<const IComponent> bank_cmp = instrument->getComponentByName(name);
bank_rect =
boost::dynamic_pointer_cast<const RectangularDetector>( bank_cmp);
if( !bank_rect)
{
g_log.error("No Rectangular detector bank " + banksVec[ 0 ] + " in instrument");
throw invalid_argument("No Rectangular detector bank " + banksVec[ 0 ] + " in instrument");
}
// if( it1 == (*itv).begin())
CalcInitParams( bank_rect, instrument, PreCalibinstrument, detWidthScale0
,detHeightScale0, Xoffset0, Yoffset0, Zoffset0, Xrot0, Yrot0, Zrot0);
// --- set Function property ----------------------
iFunc->setParameter(paramPrefix+"detWidthScale", detWidthScale0);
iFunc->setParameter(paramPrefix+"detHeightScale", detHeightScale0);
iFunc->setParameter(paramPrefix+"Xoffset", Xoffset0);
iFunc->setParameter(paramPrefix+"Yoffset", Yoffset0);
iFunc->setParameter(paramPrefix+"Zoffset", Zoffset0);
iFunc->setParameter(paramPrefix+"Xrot", Xrot0);
iFunc->setParameter(paramPrefix+"Yrot", Yrot0);
iFunc->setParameter(paramPrefix+"Zrot", Zrot0);
int startX = bounds[ nbanksSoFar ];
int endXp1 = bounds[ nbanksSoFar + group->size() ];
if( endXp1-startX < 12)
{
g_log.error() << "Bank Group " << BankNameString << " does not have enough peaks for fitting" << endl;
throw runtime_error("Group " + BankNameString +" does not have enough peaks");
}
nbanksSoFar = nbanksSoFar + static_cast<int>(group->size());
//---------- setup ties ----------------------------------
tie(iFunc, !use_PanelWidth, paramPrefix+"detWidthScale", detWidthScale0);
tie(iFunc, !use_PanelHeight, paramPrefix+"detHeightScale", detHeightScale0);
tie(iFunc, !use_PanelPosition, paramPrefix+"Xoffset", Xoffset0);
tie(iFunc, !use_PanelPosition, paramPrefix+"Yoffset", Yoffset0);
tie(iFunc, !use_PanelPosition, paramPrefix+"Zoffset", Zoffset0);
tie(iFunc, !use_PanelOrientation, paramPrefix+"Xrot", Xrot0);
tie(iFunc, !use_PanelOrientation, paramPrefix+"Yrot", Yrot0);
tie(iFunc, !use_PanelOrientation, paramPrefix+"Zrot", Zrot0);
//--------------- setup constraints ------------------------------
if( i == 0)
{
constrain(iFunc, "l0", (MIN_DET_HW_SCALE*L0), (MAX_DET_HW_SCALE*L0 ));
constrain(iFunc, "t0", -5., 5.);
}
constrain(iFunc, paramPrefix+"detWidthScale", MIN_DET_HW_SCALE*detWidthScale0, MAX_DET_HW_SCALE*detWidthScale0);
constrain(iFunc, paramPrefix+"detHeightScale", MIN_DET_HW_SCALE*detHeightScale0, MAX_DET_HW_SCALE*detHeightScale0);
constrain(iFunc, paramPrefix+"Xoffset", -1.*maxXYOffset+Xoffset0, maxXYOffset+Xoffset0);
constrain(iFunc, paramPrefix+"Yoffset", -1.*maxXYOffset+Yoffset0, maxXYOffset+Yoffset0);
constrain(iFunc, paramPrefix+"Zoffset", -1.*maxXYOffset+Zoffset0, maxXYOffset+Zoffset0);
double MaxRotOffset = getProperty("MaxRotationChangeDegrees");
constrain(iFunc, paramPrefix+"Xrot", -1.*MaxRotOffset, MaxRotOffset);
constrain(iFunc, paramPrefix+"Yrot", -1.*MaxRotOffset, MaxRotOffset);
constrain(iFunc, paramPrefix+"Zrot", -1.*MaxRotOffset, MaxRotOffset);
}//for vector< string > in Groups
// Function supports setting the sample position even when it isn't be refined
iFunc->setAttributeValue("SampleX", samplePos.X() + SampleXoffset);
iFunc->setAttributeValue("SampleY", samplePos.Y() + SampleYoffset);
iFunc->setAttributeValue("SampleZ", samplePos.Z() + SampleZoffset);
// Constraints for sample offsets
if( getProperty("AllowSampleShift"))
{
maxXYOffset = getProperty("MaxSamplePositionChangeMeters");
constrain(iFunc, "SampleX", samplePos.X()+ SampleXoffset-maxXYOffset, samplePos.X()+ SampleXoffset+ maxXYOffset);
constrain(iFunc, "SampleY", samplePos.Y()+ SampleYoffset-maxXYOffset, samplePos.Y()+ SampleYoffset+maxXYOffset);
constrain(iFunc, "SampleZ", samplePos.Z()+ SampleZoffset-maxXYOffset, samplePos.Z()+ SampleZoffset+maxXYOffset);
}
tie(iFunc, !useL0, "l0", L0);
tie(iFunc, !useTimeOffset, "t0", T0);
//--------------------- Set up Fit Algorithm and Execute-------------------
boost::shared_ptr< Algorithm > fit_alg = createChildAlgorithm( "Fit", .2, .9, true );
if( ! fit_alg)
throw invalid_argument( "Cannot find Fit algorithm" );
fit_alg->initialize();
int Niterations = getProperty( "NumIterations");
fit_alg->setProperty( "Function", iFunc);
fit_alg->setProperty( "MaxIterations", Niterations );
fit_alg->setProperty( "InputWorkspace", ws);
fit_alg->setProperty( "Output","out");
fit_alg->setProperty("CalcErrors", false);
fit_alg->executeAsChildAlg();
g_log.debug()<<"Finished executing Fit algorithm\n";
string OutputStatus =fit_alg->getProperty("OutputStatus");
g_log.notice() <<"Output Status="<<OutputStatus<< "\n";
declareProperty(
new API::WorkspaceProperty<API::ITableWorkspace>
("OutputNormalisedCovarianceMatrix","",Kernel::Direction::Output),
"The name of the TableWorkspace in which to store the final covariance matrix" );
ITableWorkspace_sptr NormCov= fit_alg->getProperty("OutputNormalisedCovarianceMatrix");
// setProperty("OutputNormalisedCovarianceMatrix", NormCov);
AnalysisDataService::Instance().addOrReplace( string("CovarianceInfo"), NormCov);
setPropertyValue("OutputNormalisedCovarianceMatrix", string("CovarianceInfo"));
//--------------------- Get and Process Results -----------------------
double chisq = fit_alg->getProperty( "OutputChi2overDoF");
setProperty("ChiSqOverDOF", chisq);
if( chisq >1)
{
g_log.warning()<<"************* This is a large chi squared value ************\n";
g_log.warning()<<" the indexing may have been using an incorrect\n";
g_log.warning()<<" orientation matrix, instrument geometry or goniometer info\n";
}
ITableWorkspace_sptr RRes = fit_alg->getProperty( "OutputParameters");
vector< double >params;
vector< double >errs ;
vector< string >names;
double sigma= sqrt(chisq);
if( chisq < 0 || chisq != chisq)
sigma = -1;
string fieldBaseNames = ";l0;t0;detWidthScale;detHeightScale;Xoffset;Yoffset;Zoffset;Xrot;Yrot;Zrot;";
if( getProperty("AllowSampleShift"))
fieldBaseNames +="SampleX;SampleY;SampleZ;";
for( size_t prm = 0; prm < RRes->rowCount(); ++prm )
{
string namee =RRes->getRef< string >( "Name", prm );
size_t dotPos = namee.find('_');
if (dotPos >= namee.size())
dotPos = 0;
else
dotPos++;
string Field = namee.substr(dotPos);
size_t FieldNum= fieldBaseNames.find(";"+Field+";");
if( FieldNum > fieldBaseNames.size())
continue;
if( dotPos !=0)
{
int col = atoi( namee.substr( 1,dotPos).c_str());
if( col < 0 || col >=NGroups)
continue;
}
names.push_back( namee );
params.push_back( RRes->getRef< double >( "Value", prm ));
double err = RRes->getRef< double >( "Error", prm );
errs.push_back( sigma * err );
}
//------------------- Report chi^2 value --------------------
int nVars =8;// NGroups;
if( !use_PanelWidth) nVars--;
if( !use_PanelHeight)nVars--;
if( !use_PanelPosition) nVars -=3;
if( !use_PanelOrientation) nVars -=3;
nVars *= NGroups ;
nVars += 2;
if( !useL0)nVars--;
if( !useTimeOffset)nVars--;
// g_log.notice() << " nVars=" <<nVars<< endl;
int NDof = ( (int)ws->dataX( 0).size()- nVars);
setProperty("DOF",NDof);
g_log.notice() << "ChiSqoverDoF =" << chisq << " NDof =" << NDof << "\n";
map<string,double> result;
for( size_t i = 0; i < min< size_t >( params.size(), names.size() ); ++i )
{
result[ names[ i ] ] = params[ i ];
}
//--------------------- Create Result Table Workspace-------------------
this->progress(.92, "Creating Results table");
createResultWorkspace(NGroups, names, params, errs);