Mantid
Loading...
Searching...
No Matches
CreateCalFileByNames.cpp
Go to the documentation of this file.
1// Mantid Repository : https://github.com/mantidproject/mantid
2//
3// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
4// NScD Oak Ridge National Laboratory, European Spallation Source,
5// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6// SPDX - License - Identifier: GPL - 3.0 +
7//----------------------------------------------------------------------
8// Includes
9//----------------------------------------------------------------------
16
17#include <boost/algorithm/string/detail/classification.hpp>
18#include <boost/algorithm/string/split.hpp>
19#include <boost/algorithm/string/trim.hpp>
20
21#include <fstream>
22#include <queue>
23
24using namespace Mantid::API;
25using namespace Mantid::Kernel;
26
27namespace Mantid::Algorithms {
28
29// Register the class into the algorithm factory
30DECLARE_ALGORITHM(CreateCalFileByNames)
31
32using namespace Kernel;
34using API::Progress;
36
41 declareProperty(std::make_unique<WorkspaceProperty<>>("InstrumentWorkspace", "", Direction::Input,
42 std::make_shared<InstrumentValidator>()),
43 "A workspace that contains a reference to the instrument of interest. "
44 "You can use LoadEmptyInstrument to create such a workspace.");
45 declareProperty(std::make_unique<FileProperty>("GroupingFileName", "", FileProperty::Save, ".cal"),
46 "The name of the output CalFile");
47 declareProperty("GroupNames", "",
48 "A string of the instrument component names to use as separate groups. "
49 "/ or , can be used to separate multiple groups.");
50}
51
61 MatrixWorkspace_const_sptr ws = getProperty("InstrumentWorkspace");
62
63 // Get the instrument.
64 Instrument_const_sptr inst = ws->getInstrument();
65
66 // Get the names of groups
67 std::string groupsname = getProperty("GroupNames");
68 groups = groupsname;
69
70 // Split the names of the group and insert in a vector, throw if group empty
71 std::vector<std::string> vgroups;
72 boost::split(vgroups, groupsname, boost::algorithm::detail::is_any_ofF<char>(",/*"));
73 if (vgroups.empty()) {
74 g_log.error("Could not determine group names. Group names should be "
75 "separated by / or ,");
76 throw std::runtime_error("Could not determine group names. Group names "
77 "should be separated by / or ,");
78 }
79
80 // Assign incremental number to each group
81 std::map<std::string, int> group_map;
82 int index = 0;
83 for (auto &vgroup : vgroups) {
84 boost::trim(vgroup);
85 group_map[vgroup] = ++index;
86 }
87
88 // Not needed anymore
89 vgroups.clear();
90
91 // Find Detectors that belong to groups
92 using sptr_ICompAss = std::shared_ptr<const Geometry::ICompAssembly>;
93 using sptr_IComp = std::shared_ptr<const Geometry::IComponent>;
94 using sptr_IDet = std::shared_ptr<const Geometry::IDetector>;
95 std::queue<std::pair<sptr_ICompAss, int>> assemblies;
96 sptr_ICompAss current = std::dynamic_pointer_cast<const Geometry::ICompAssembly>(inst);
97 sptr_IDet currentDet;
98 sptr_IComp currentIComp;
99 sptr_ICompAss currentchild;
100
101 int top_group, child_group;
102
103 if (current.get()) {
104 top_group = group_map[current->getName()]; // Return 0 if not in map
105 assemblies.emplace(current, top_group);
106 }
107
108 std::string filename = getProperty("GroupingFilename");
109
110 // Check if a template cal file is given
111 bool overwrite = groupingFileDoesExist(filename);
112
113 int number = 0;
114 Progress prog(this, 0.0, 0.8, assemblies.size());
115 while (!assemblies.empty()) // Travel the tree from the instrument point
116 {
117 current = assemblies.front().first;
118 top_group = assemblies.front().second;
119 assemblies.pop();
120 int nchilds = current->nelements();
121 if (nchilds != 0) {
122 for (int i = 0; i < nchilds; ++i) {
123 currentIComp = (*(current.get()))[i]; // Get child
124 currentDet = std::dynamic_pointer_cast<const Geometry::IDetector>(currentIComp);
125 if (currentDet.get()) // Is detector
126 {
127 if (overwrite) // Map will contains udet as the key
128 instrcalib[currentDet->getID()] = std::make_pair(number++, top_group);
129 else // Map will contains the entry number as the key
130 instrcalib[number++] = std::make_pair(currentDet->getID(), top_group);
131 } else // Is an assembly, push in the queue
132 {
133 currentchild = std::dynamic_pointer_cast<const Geometry::ICompAssembly>(currentIComp);
134 if (currentchild.get()) {
135 child_group = group_map[currentchild->getName()];
136 if (child_group == 0)
137 child_group = top_group;
138 assemblies.emplace(currentchild, child_group);
139 }
140 }
141 }
142 }
143 prog.report();
144 }
145 // Write the results in a file
146 saveGroupingFile(filename, overwrite);
147 progress(0.2);
148}
149
150bool CreateCalFileByNames::groupingFileDoesExist(const std::string &filename) const {
151 std::ifstream file(filename.c_str());
152 // Check if the file already exists
153 if (!file)
154 return false;
155 file.close();
156 std::ostringstream mess;
157 mess << "Calibration file " << filename << " already exist. Only grouping will be modified";
158 g_log.information(mess.str());
159 return true;
160}
161
163void CreateCalFileByNames::saveGroupingFile(const std::string &filename, bool overwrite) const {
164 std::ostringstream message;
165 std::fstream outfile;
166 std::fstream infile;
167 if (!overwrite) // Open the file directly
168 {
169 outfile.open(filename.c_str(), std::ios::out);
170 if (!outfile.is_open()) {
171 message << "Can't open Calibration File: " << filename;
172 g_log.error(message.str());
173 throw std::runtime_error(message.str());
174 }
175 } else {
176 infile.open(filename.c_str(), std::ios::in);
177 std::string newfilename = filename + "2";
178 outfile.open(newfilename.c_str(), std::ios::out);
179 if (!infile.is_open()) {
180 message << "Can't open input Calibration File: " << filename;
181 g_log.error(message.str());
182 throw std::runtime_error(message.str());
183 }
184 if (!outfile.is_open()) {
185 message << "Can't open new Calibration File: " << newfilename;
186 g_log.error(message.str());
187 throw std::runtime_error(message.str());
188 }
189 }
190
191 // Write the headers
192 writeHeaders(outfile, filename, overwrite);
193
194 if (overwrite) {
195 int number, udet, select, group;
196 double offset;
197
198 std::string str;
199 while (getline(infile, str)) {
200 if (str.empty() || str[0] == '#') // Skip the headers
201 continue;
202 std::istringstream istr(str);
203 istr >> number >> udet >> offset >> select >> group;
204 auto it = instrcalib.find(udet);
205 if (it == instrcalib.end()) // Not found, don't assign a group
206 group = 0;
207 else
208 group = ((*it).second).second; // If found then assign new group
209 // write out
210 writeCalEntry(outfile, number, udet, offset, select, group);
211 }
212 } else //
213 {
214 for (const auto &value : instrcalib)
215 writeCalEntry(outfile, value.first, (value.second).first, 0.0, 1, (value.second).second);
216 }
217
218 // Closing
219 outfile.close();
220 if (overwrite)
221 infile.close();
222}
223
225void CreateCalFileByNames::writeCalEntry(std::ostream &os, int number, int udet, double offset, int select, int group) {
226 os << std::fixed << std::setw(9) << number << std::fixed << std::setw(15) << udet << std::fixed
227 << std::setprecision(7) << std::setw(15) << offset << std::fixed << std::setw(8) << select << std::fixed
228 << std::setw(8) << group << "\n";
229}
230
232void CreateCalFileByNames::writeHeaders(std::ostream &os, const std::string &filename, bool overwrite) const {
233 os << "# Diffraction focusing calibration file created by Mantid"
234 << "\n";
235 os << "# Detectors have been grouped using assembly names:" << groups << "\n";
236 if (overwrite) {
237 os << "# Template file " << filename << " has been used"
238 << "\n";
239 os << "# Only grouping has been changed, offset from template file have "
240 "been copied"
241 << "\n";
242 } else
243 os << "# No template file, all offsets set to 0.0 and select to 1"
244 << "\n";
245
246 os << "# Number UDET offset select group"
247 << "\n";
248}
249
250} // namespace Mantid::Algorithms
#define DECLARE_ALGORITHM(classname)
Definition Algorithm.h:538
double value
The value of the point.
Definition FitMW.cpp:51
std::map< DeltaEMode::Type, std::string > index
void declareProperty(std::unique_ptr< Kernel::Property > p, const std::string &doc="") override
Add a property to the list of managed properties.
TypedValue getProperty(const std::string &name) const override
Get the value of a property.
Kernel::Logger & g_log
Definition Algorithm.h:422
void progress(double p, const std::string &msg="", double estimatedTime=0.0, int progressPrecision=0)
Sends ProgressNotification.
A specialized class for dealing with file properties.
@ Save
to specify a file to write to, the file may or may not exist
Helper class for reporting progress from algorithms.
Definition Progress.h:25
A property class for workspaces.
void saveGroupingFile(const std::string &, bool overwrite) const
Creates and saves the output file.
void writeHeaders(std::ostream &os, const std::string &filename, bool overwrite) const
Writes out the header to the output file.
std::string groups
The names of the groups.
bool groupingFileDoesExist(const std::string &filename) const
Determine whether the grouping file already exists.
instrcalmap instrcalib
Calibration map used if the *.cal file exist.
static void writeCalEntry(std::ostream &os, int number, int udet, double offset, int select, int group)
Writes a single calibration line to the output file.
void init() override
Initialisation code.
void error(const std::string &msg)
Logs at error level.
Definition Logger.cpp:108
void information(const std::string &msg)
Logs at information level.
Definition Logger.cpp:136
void report()
Increments the loop counter by 1, then sends the progress notification on behalf of its algorithm.
std::shared_ptr< const MatrixWorkspace > MatrixWorkspace_const_sptr
shared pointer to the matrix workspace base class (const version)
std::shared_ptr< const Instrument > Instrument_const_sptr
Shared pointer to an const instrument object.
@ Input
An input workspace.
Definition Property.h:53