-
Notifications
You must be signed in to change notification settings - Fork 121
/
SaveIsawPeaks.cpp
450 lines (390 loc) · 17 KB
/
SaveIsawPeaks.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
#include "MantidAPI/FileProperty.h"
#include "MantidAPI/InstrumentValidator.h"
#include "MantidAPI/Run.h"
#include "MantidCrystal/SaveIsawPeaks.h"
#include "MantidDataObjects/Peak.h"
#include "MantidDataObjects/PeaksWorkspace.h"
#include "MantidGeometry/Instrument/Goniometer.h"
#include "MantidGeometry/Instrument/RectangularDetector.h"
#include "MantidKernel/Strings.h"
#include "MantidKernel/Utils.h"
#include "MantidDataObjects/Workspace2D.h"
#include <fstream>
#include <Poco/File.h>
using namespace Mantid::Geometry;
using namespace Mantid::DataObjects;
using namespace Mantid::Kernel;
using namespace Mantid::API;
namespace Mantid {
namespace Crystal {
// Register the algorithm into the AlgorithmFactory
DECLARE_ALGORITHM(SaveIsawPeaks)
/** Initialize the algorithm's properties.
*/
void SaveIsawPeaks::init() {
declareProperty(make_unique<WorkspaceProperty<PeaksWorkspace>>(
"InputWorkspace", "", Direction::Input,
boost::make_shared<InstrumentValidator>()),
"An input PeaksWorkspace with an instrument.");
declareProperty("AppendFile", false, "Append to file if true.\n"
"If false, new file (default).");
const std::vector<std::string> exts{".peaks", ".integrate"};
declareProperty(Kernel::make_unique<FileProperty>("Filename", "",
FileProperty::Save, exts),
"Path to an ISAW-style peaks or integrate file to save.");
declareProperty(
make_unique<WorkspaceProperty<Workspace2D>>(
"ProfileWorkspace", "", Direction::Input, PropertyMode::Optional),
"An optional Workspace2D of profiles from integrating cylinder.");
}
/** Execute the algorithm.
*/
void SaveIsawPeaks::exec() {
// Section header
std::string header = "2 SEQN H K L COL ROW CHAN "
" L2 2_THETA AZ WL D IPK "
" INTI SIGI RFLG";
std::string filename = getPropertyValue("Filename");
PeaksWorkspace_sptr ws = getProperty("InputWorkspace");
std::vector<Peak> peaks = ws->getPeaks();
inst = ws->getInstrument();
// We cannot assume the peaks have bank type detector modules, so we have a
// string to check this
std::string bankPart = "?";
// We must sort the peaks first by run, then bank #, and save the list of
// workspace indices of it
typedef std::map<int, std::vector<size_t>> bankMap_t;
typedef std::map<int, bankMap_t> runMap_t;
std::set<int, std::less<int>> uniqueBanks;
runMap_t runMap;
for (size_t i = 0; i < peaks.size(); ++i) {
Peak &p = peaks[i];
int run = p.getRunNumber();
int bank = 0;
std::string bankName = p.getBankName();
if (bankName.size() <= 4) {
g_log.information() << "Could not interpret bank number of peak " << i
<< "(" << bankName << ")\n";
continue;
}
// Save the "bank" part once to check whether it really is a bank
if (bankPart == "?")
bankPart = bankName.substr(0, 4);
// Take out the "bank" part of the bank name and convert to an int
if (bankPart == "bank")
bankName = bankName.substr(4, bankName.size() - 4);
else if (bankPart == "WISH")
bankName = bankName.substr(9, bankName.size() - 9);
Strings::convert(bankName, bank);
// Save in the map
runMap[run][bank].push_back(i);
// Track unique bank numbers
uniqueBanks.insert(bank);
}
if (!inst)
throw std::runtime_error(
"No instrument in PeaksWorkspace. Cannot save peaks file.");
if (bankPart != "bank" && bankPart != "WISH" && bankPart != "?") {
std::ostringstream mess;
mess << "Detector module of type " << bankPart
<< " not supported in ISAWPeaks. Cannot save peaks file";
throw std::runtime_error(mess.str());
}
double l1;
V3D beamline;
double beamline_norm;
V3D samplePos;
inst->getInstrumentParameters(l1, beamline, beamline_norm, samplePos);
std::ofstream out;
bool append = getProperty("AppendFile");
// do not append if file does not exist
if (!Poco::File(filename.c_str()).exists())
append = false;
if (append) {
out.open(filename.c_str(), std::ios::app);
} else {
out.open(filename.c_str());
out << "Version: 2.0 Facility: SNS ";
out << " Instrument: " << inst->getName() << " Date: ";
// TODO: The experiment date might be more useful than the instrument date.
// For now, this allows the proper instrument to be loaded back after
// saving.
Kernel::DateAndTime expDate = inst->getValidFromDate() + 1.0;
out << expDate.toISO8601String() << '\n';
out << "6 L1 T0_SHIFT\n";
out << "7 " << std::setw(10);
out << std::setprecision(4) << std::fixed << (l1 * 100);
out << std::setw(12) << std::setprecision(3) << std::fixed;
// Time offset from property
const API::Run &run = ws->run();
double T0 = 0.0;
if (run.hasProperty("T0")) {
Kernel::Property *prop = run.getProperty("T0");
T0 = boost::lexical_cast<double, std::string>(prop->value());
if (T0 != 0) {
g_log.notice() << "T0 = " << T0 << '\n';
}
}
out << T0 << '\n';
// ============================== Save .detcal info
// =========================================
if (true) {
out << "4 DETNUM NROWS NCOLS WIDTH HEIGHT DEPTH DETD CenterX "
" CenterY CenterZ BaseX BaseY BaseZ UpX UpY "
" UpZ\n";
// Here would save each detector...
for (const auto bank : uniqueBanks) {
// Build up the bank name
std::ostringstream mess;
if (bankPart == "bank")
mess << "bank" << bank;
else if (bankPart == "WISH" && bank < 10)
mess << "WISHpanel0" << bank;
else if (bankPart == "WISH")
mess << "WISHpanel" << bank;
std::string bankName = mess.str();
// Retrieve it
boost::shared_ptr<const IComponent> det =
inst->getComponentByName(bankName);
if (inst->getName().compare("CORELLI") ==
0) // for Corelli with sixteenpack under bank
{
std::vector<Geometry::IComponent_const_sptr> children;
boost::shared_ptr<const Geometry::ICompAssembly> asmb =
boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(
inst->getComponentByName(bankName));
asmb->getChildren(children, false);
det = children[0];
}
if (det) {
// Center of the detector
V3D center = det->getPos();
// Distance to center of detector
double detd = (center - inst->getSample()->getPos()).norm();
int NCOLS, NROWS;
double xsize, ysize;
sizeBanks(bankName, NCOLS, NROWS, xsize, ysize);
// Base unit vector (along the horizontal, X axis)
int midX = NCOLS / 2;
int midY = NROWS / 2;
V3D base = findPixelPos(bankName, midX + 1, midY) -
findPixelPos(bankName, midX, midY);
base.normalize();
// Up unit vector (along the vertical, Y axis)
V3D up = findPixelPos(bankName, midX, midY + 1) -
findPixelPos(bankName, midX, midY);
up.normalize();
// Write the line
out << "5 " << std::setw(6) << std::right << bank << " "
<< std::setw(6) << std::right << NROWS << " " << std::setw(6)
<< std::right << NCOLS << " " << std::setw(7) << std::right
<< std::fixed << std::setprecision(4) << 100.0 * xsize << " "
<< std::setw(7) << std::right << std::fixed
<< std::setprecision(4) << 100.0 * ysize << " "
<< " 0.2000 " << std::setw(6) << std::right << std::fixed
<< std::setprecision(2) << 100.0 * detd << " " << std::setw(9)
<< std::right << std::fixed << std::setprecision(4)
<< 100.0 * center.X() << " " << std::setw(9) << std::right
<< std::fixed << std::setprecision(4) << 100.0 * center.Y() << " "
<< std::setw(9) << std::right << std::fixed
<< std::setprecision(4) << 100.0 * center.Z() << " "
<< std::setw(8) << std::right << std::fixed
<< std::setprecision(5) << base.X() << " " << std::setw(8)
<< std::right << std::fixed << std::setprecision(5) << base.Y()
<< " " << std::setw(8) << std::right << std::fixed
<< std::setprecision(5) << base.Z() << " " << std::setw(8)
<< std::right << std::fixed << std::setprecision(5) << up.X()
<< " " << std::setw(8) << std::right << std::fixed
<< std::setprecision(5) << up.Y() << " " << std::setw(8)
<< std::right << std::fixed << std::setprecision(5) << up.Z()
<< " \n";
} else
g_log.warning() << "Information about detector module " << bankName
<< " not found and recognised\n";
}
}
}
// HKL's are flipped by -1 because of the internal Q convention
// unless Crystallography convention
double qSign = -1.0;
if (ws->getConvention() == "Crystallography")
qSign = 1.0;
// ============================== Save all Peaks
// =========================================
// Sequence number
int seqNum = 1;
// Go in order of run numbers
runMap_t::iterator runMap_it;
for (runMap_it = runMap.begin(); runMap_it != runMap.end(); ++runMap_it) {
// Start of a new run
int run = runMap_it->first;
bankMap_t &bankMap = runMap_it->second;
bankMap_t::iterator bankMap_it;
for (bankMap_it = bankMap.begin(); bankMap_it != bankMap.end();
++bankMap_it) {
// Start of a new bank.
int bank = bankMap_it->first;
std::vector<size_t> &ids = bankMap_it->second;
if (!ids.empty()) {
// Write the bank header
out << "0 NRUN DETNUM CHI PHI OMEGA MONCNT\n";
out << "1 " << std::setw(5) << run << std::setw(7) << std::right
<< bank;
// Determine goniometer angles by calculating from the goniometer matrix
// of a peak in the list
Goniometer gon(peaks[ids[0]].getGoniometerMatrix());
std::vector<double> angles = gon.getEulerAngles("yzy");
double phi = angles[2];
double chi = angles[1];
double omega = angles[0];
out << std::setw(8) << std::fixed << std::setprecision(2) << chi << " ";
out << std::setw(8) << std::fixed << std::setprecision(2) << phi << " ";
out << std::setw(8) << std::fixed << std::setprecision(2) << omega
<< " ";
// Get the monitor count from the first peak (should all be the same for
// one run)
size_t first_peak_index = ids[0];
Peak &first_peak = peaks[first_peak_index];
double monct = first_peak.getMonitorCount();
out << std::setw(12) << static_cast<int>(monct) << '\n';
out << header << '\n';
// Go through each peak at this run / bank
for (auto wi : ids) {
Peak &p = peaks[wi];
// Sequence (run) number
out << "3" << std::setw(7) << seqNum;
// HKL's are flipped by -1 because of the internal Q convention
// unless Crystallography convention
out << std::setw(5) << Utils::round(qSign * p.getH()) << std::setw(5)
<< Utils::round(qSign * p.getK()) << std::setw(5)
<< Utils::round(qSign * p.getL());
// Row/column
out << std::setw(8) << std::fixed << std::setprecision(2)
<< static_cast<double>(p.getCol()) << " ";
out << std::setw(8) << std::fixed << std::setprecision(2)
<< static_cast<double>(p.getRow()) << " ";
out << std::setw(8) << std::fixed << std::setprecision(0)
<< p.getTOF() << " ";
out << std::setw(9) << std::fixed << std::setprecision(3)
<< (p.getL2() * 100.0) << " ";
// This is the scattered beam direction
V3D dir = p.getDetPos() - inst->getSample()->getPos();
double scattering, azimuth;
// Two-theta = polar angle = scattering angle = between +Z vector and
// the scattered beam
scattering = dir.angle(V3D(0.0, 0.0, 1.0));
// "Azimuthal" angle: project the scattered beam direction onto the XY
// plane,
// and calculate the angle between that and the +X axis (right-handed)
azimuth = atan2(dir.Y(), dir.X());
out << std::setw(9) << std::fixed << std::setprecision(5)
<< scattering << " "; // two-theta scattering
out << std::setw(9) << std::fixed << std::setprecision(5) << azimuth
<< " ";
out << std::setw(10) << std::fixed << std::setprecision(6)
<< p.getWavelength() << " ";
out << std::setw(9) << std::fixed << std::setprecision(4)
<< p.getDSpacing() << " ";
out << std::setw(8) << std::fixed << std::setprecision(0)
<< int(p.getBinCount()) << " ";
out << std::setw(10) << std::fixed << std::setprecision(2)
<< p.getIntensity() << " ";
out << std::setw(7) << std::fixed << std::setprecision(2)
<< p.getSigmaIntensity() << " ";
int thisReflag = 310;
out << std::setw(5) << thisReflag;
out << '\n';
Workspace2D_sptr wsProfile2D = getProperty("ProfileWorkspace");
if (wsProfile2D) {
out << "8";
const auto &yValues = wsProfile2D->y(wi);
for (size_t j = 0; j < yValues.size(); j++) {
out << std::setw(8) << static_cast<int>(yValues[j]);
if ((j + 1) % 10 == 0) {
out << '\n';
if (j + 1 != yValues.size())
out << "8";
}
}
}
// Count the sequence
seqNum++;
}
}
}
}
out.flush();
out.close();
}
V3D SaveIsawPeaks::findPixelPos(std::string bankName, int col, int row) {
boost::shared_ptr<const IComponent> parent =
inst->getComponentByName(bankName);
if (parent->type().compare("RectangularDetector") == 0) {
boost::shared_ptr<const RectangularDetector> RDet =
boost::dynamic_pointer_cast<const RectangularDetector>(parent);
boost::shared_ptr<Detector> pixel = RDet->getAtXY(col, row);
return pixel->getPos();
} else {
std::vector<Geometry::IComponent_const_sptr> children;
boost::shared_ptr<const Geometry::ICompAssembly> asmb =
boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(parent);
asmb->getChildren(children, false);
if (children[0]->getName().compare("sixteenpack") == 0) {
asmb = boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(
children[0]);
children.clear();
asmb->getChildren(children, false);
}
int col0 = col - 1;
// WISH detectors are in bank in this order in instrument
if (inst->getName() == "WISH")
col0 = (col % 2 == 0 ? col / 2 + 75 : (col - 1) / 2);
boost::shared_ptr<const Geometry::ICompAssembly> asmb2 =
boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(
children[col0]);
std::vector<Geometry::IComponent_const_sptr> grandchildren;
asmb2->getChildren(grandchildren, false);
Geometry::IComponent_const_sptr first = grandchildren[row - 1];
return first->getPos();
}
}
void SaveIsawPeaks::sizeBanks(std::string bankName, int &NCOLS, int &NROWS,
double &xsize, double &ysize) {
if (bankName.compare("None") == 0)
return;
boost::shared_ptr<const IComponent> parent =
inst->getComponentByName(bankName);
if (parent->type().compare("RectangularDetector") == 0) {
boost::shared_ptr<const RectangularDetector> RDet =
boost::dynamic_pointer_cast<const RectangularDetector>(parent);
NCOLS = RDet->xpixels();
NROWS = RDet->ypixels();
xsize = RDet->xsize();
ysize = RDet->ysize();
} else {
std::vector<Geometry::IComponent_const_sptr> children;
boost::shared_ptr<const Geometry::ICompAssembly> asmb =
boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(parent);
asmb->getChildren(children, false);
if (children[0]->getName().compare("sixteenpack") == 0) {
asmb = boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(
children[0]);
children.clear();
asmb->getChildren(children, false);
}
boost::shared_ptr<const Geometry::ICompAssembly> asmb2 =
boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(children[0]);
std::vector<Geometry::IComponent_const_sptr> grandchildren;
asmb2->getChildren(grandchildren, false);
NROWS = static_cast<int>(grandchildren.size());
NCOLS = static_cast<int>(children.size());
Geometry::IComponent_const_sptr first = children[0];
Geometry::IComponent_const_sptr last = children[NCOLS - 1];
xsize = first->getDistance(*last);
first = grandchildren[0];
last = grandchildren[NROWS - 1];
ysize = first->getDistance(*last);
}
}
} // namespace Mantid
} // namespace Crystal