27#include <Poco/DOM/DOMParser.h>
28#include <Poco/DOM/Element.h>
29#include <Poco/DOM/NodeFilter.h>
30#include <Poco/DOM/NodeIterator.h>
31#include <Poco/DOM/NodeList.h>
32#include <Poco/Exception.h>
34#include <boost/algorithm/string.hpp>
36using Poco::XML::DOMParser;
38using Poco::XML::NodeFilter;
39using Poco::XML::NodeIterator;
40using Poco::XML::NodeList;
61void convertToVector(
const std::vector<T> &singles,
const std::vector<T> &ranges, std::vector<T> &tot_singles) {
64 size_t n_total(singles.size() + tot_singles.size());
65 for (
size_t i = 0; i < ranges.size(); i += 2) {
66 n_total += ranges[i + 1] - ranges[i] + 1;
70 tot_singles.reserve(n_total);
72 tot_singles.insert(tot_singles.end(), singles.begin(), singles.end());
74 for (
size_t i = 0; i < ranges.size(); i += 2) {
75 for (T obj_id = ranges[i]; obj_id < ranges[i + 1] + 1; ++obj_id) {
76 tot_singles.emplace_back(obj_id);
89template <
typename T>
void parseRangeText(
const std::string &inputstr, std::vector<T> &singles, std::vector<T> &pairs) {
91 std::vector<std::string> rawstrings;
92 boost::split(rawstrings, inputstr, boost::is_any_of(
","), boost::token_compress_on);
94 for (
auto &rawstring : rawstrings) {
96 boost::trim(rawstring);
97 bool containDash(
true);
98 if (rawstring.find_first_of(
'-') == std::string::npos) {
104 std::vector<std::string> ptemp;
105 boost::split(ptemp, rawstring, boost::is_any_of(
"-"), boost::token_compress_on);
106 if (ptemp.size() != 2) {
107 std::string
error =
"Range string " + rawstring +
" has a wrong format!";
108 throw std::invalid_argument(
error);
111 auto intstart = boost::lexical_cast<T>(ptemp[0]);
112 auto intend = boost::lexical_cast<T>(ptemp[1]);
113 if (intstart >= intend) {
114 std::string
error =
"Range string " + rawstring +
" has wrong order of detectors ID!";
115 throw std::invalid_argument(
error);
117 pairs.emplace_back(intstart);
118 pairs.emplace_back(intend);
121 auto itemp = boost::lexical_cast<T>(rawstring);
122 singles.emplace_back(itemp);
135void parseISISStringToVector(
const std::string &ins, std::vector<Mantid::specnum_t> &ranges) {
137 std::vector<string> splitstrings;
138 boost::split(splitstrings, ins, boost::is_any_of(
" "), boost::token_compress_on);
141 bool tocontinue =
true;
145 if (
index == splitstrings.size() - 1) {
150 vector<string> temps;
151 boost::split(temps, splitstrings[
index], boost::is_any_of(
"-"), boost::token_compress_on);
152 if (splitstrings[
index] ==
"-" || temps.size() == 1) {
155 }
else if (temps.size() == 2) {
157 temps.insert(temps.begin() + 1,
"-");
158 splitstrings.erase(splitstrings.begin() +
index);
159 for (
size_t ic = 0; ic < 3; ic++) {
160 if (!temps[ic].empty()) {
161 splitstrings.insert(splitstrings.begin() +
index, temps[ic]);
167 std::string err =
"String " + splitstrings[
index] +
" has too many '-'";
168 throw std::invalid_argument(err);
171 if (
index >= splitstrings.size())
181 ranges.emplace_back(boost::lexical_cast<Mantid::specnum_t>(splitstrings[
index]));
184 if (
index == splitstrings.size() - 1 || splitstrings[
index + 1] !=
"-") {
186 ranges.emplace_back(boost::lexical_cast<Mantid::specnum_t>(splitstrings[
index]));
190 ranges.emplace_back(boost::lexical_cast<Mantid::specnum_t>(splitstrings[
index + 2]));
194 if (
index >= splitstrings.size())
203void loadISISMaskFile(
const std::string &isisfilename, std::vector<Mantid::specnum_t> &spectraMasks) {
205 std::vector<Mantid::specnum_t> ranges;
208 ifs.open(isisfilename, std::ios::in);
209 if (!ifs.is_open()) {
210 throw std::invalid_argument(
"Cannot open ISIS mask file" + isisfilename);
213 std::string isisline;
214 while (getline(ifs, isisline)) {
215 boost::trim(isisline);
218 if (isisline.empty())
222 if (isisline.c_str()[0] <
'0' || isisline.c_str()[0] >
'9')
226 parseISISStringToVector(isisline, ranges);
230 std::vector<Mantid::specnum_t> dummy;
231 convertToVector(dummy, ranges, spectraMasks);
245 "The name of the instrument to apply the mask.");
247 const std::vector<std::string> maskExts{
".xml",
".msk"};
248 declareProperty(std::make_unique<FileProperty>(
"InputFile",
"",
FileProperty::Load, maskExts),
249 "Masking file for masking. Supported file format is XML and "
253 "The name of the workspace wich defines instrument and spectra, "
254 "used as the source of the spectra-detector map for the mask to load. "
255 "The instrument, attached to this workspace has to be the same as the "
256 "one specified by 'Instrument' property");
260 "Output Masking Workspace");
270 const std::string instrumentname =
getProperty(
"Instrument");
279 auto t_inst_name =
m_maskWS->getInstrument()->getName();
280 auto r_inst_name =
m_sourceMapWS->getInstrument()->getName();
281 if (t_inst_name != r_inst_name) {
282 throw std::invalid_argument(
"If reference workspace is provided, it has "
283 "to have instrument with the same name as "
284 "specified by 'Instrument' property");
295 if (boost::ends_with(filename,
"l") || boost::ends_with(filename,
"L")) {
299 }
else if (boost::ends_with(filename,
"k") || boost::ends_with(filename,
"K")) {
304 g_log.
error() <<
"File " << filename <<
" is not in supported format. \n";
334 size_t numHist =
m_maskWS->getNumberHistograms();
335 for (
size_t wkspIndex = 0; wkspIndex < numHist; wkspIndex++) {
336 m_maskWS->setMaskedIndex(wkspIndex);
349 const std::vector<detid_t> &singledetids) {
352 g_log.
debug() <<
"Mask = " << tomask <<
" Final Single IDs Size = " << singledetids.size() <<
'\n';
354 for (
auto detid : singledetids) {
355 detid2index_map::const_iterator it;
356 it = indexmap.find(detid);
357 if (it != indexmap.end()) {
358 size_t index = it->second;
361 g_log.
warning() <<
"Pixel w/ ID = " << detid <<
" Cannot Be Located\n";
377 for (
auto &componentname : componentnames) {
378 g_log.
debug() <<
"Component name = " << componentname <<
'\n';
383 g_log.
debug() <<
"Component ID = " << component->getComponentID() <<
'\n';
386 g_log.
warning() <<
"Component " << componentname <<
" does not exist!\n";
391 std::shared_ptr<const Geometry::ICompAssembly> asmb =
392 std::dynamic_pointer_cast<const Geometry::ICompAssembly>(component);
393 std::vector<Geometry::IComponent_const_sptr> children;
394 asmb->getChildren(children,
true);
396 g_log.
debug() <<
"Number of Children = " << children.size() <<
'\n';
399 detid_t id_min(std::numeric_limits<Mantid::detid_t>::max());
402 for (
const auto &child : children) {
408 detectors.emplace_back(detid);
417 g_log.
debug() <<
"Number of Detectors in Children = " << numdets <<
" Range = " << id_min <<
", " << id_max
429 std::stringstream infoss;
430 infoss <<
"Bank IDs to be converted to detectors: \n";
431 for (
auto &singlebank : singlebanks) {
432 infoss <<
"Bank: " << singlebank <<
'\n';
438 for (
auto &singlebank : singlebanks) {
439 std::vector<Geometry::IDetector_const_sptr> idetectors;
441 minstrument->getDetectorsInBank(idetectors, singlebank);
442 g_log.
debug() <<
"Bank: " << singlebank <<
" has " << idetectors.size() <<
" detectors\n";
445 size_t numdets = idetectors.size();
446 detid_t detid_first = idetectors.front()->getID();
447 detid_t detid_last = idetectors.back()->getID();
451 for (
const auto &det : idetectors) {
453 detectors.emplace_back(detid);
455 g_log.
debug() <<
"Number of Detectors in Bank " << singlebank <<
" is: " << numdets
456 <<
"\nRange From: " << detid_first <<
" To: " << detid_last <<
'\n';
470 std::vector<int32_t> &singleDetIds) {
472 if (maskedSpecID.empty())
478 maskedSpecID.clear();
484 spec2index_map::const_iterator s2iter;
487 auto spec0 = maskedSpecID[0];
488 auto prev_masks = spec0;
489 for (
int spec2mask : maskedSpecID) {
491 s2iter = s2imap.find(spec2mask);
492 if (s2iter == s2imap.end()) {
494 g_log.
error() <<
"Spectrum " << spec2mask <<
" does not have an entry in GroupWorkspace's spec2index map\n";
495 throw std::runtime_error(
"Logic error");
497 size_t wsindex = s2iter->second;
498 if (wsindex >=
m_maskWS->getNumberHistograms()) {
500 g_log.
error() <<
"Group workspace's spec2index map is set wrong: "
501 <<
" Found workspace index = " << wsindex <<
" for spectrum No " << spec2mask
502 <<
" with workspace size = " <<
m_maskWS->getNumberHistograms() <<
'\n';
505 m_maskWS->mutableY(wsindex)[0] = (mask) ? 1.0 : 0.0;
509 if (spec2mask > prev_masks + 1) {
510 g_log.
debug() <<
"Masked Spectrum " << spec0 <<
" To " << prev_masks <<
'\n';
529 m_pDoc = pParser.parseString(xmlText);
530 }
catch (Poco::Exception &exc) {
538 g_log.
error(
"XML file: " + filename +
"contains no root element.");
568 throw std::runtime_error(
"Call LoadMask::initialize() before parseXML.");
571 Poco::AutoPtr<NodeList> pNL_type =
m_pRootElem->getElementsByTagName(
"type");
574 Poco::XML::NodeIterator it(
m_pDoc, Poco::XML::NodeFilter::SHOW_ELEMENT);
575 Poco::XML::Node *pNode = it.nextNode();
577 std::vector<specnum_t> singleSp, pairSp;
578 std::vector<detid_t> maskSingleDet, maskPairDet;
580 bool ingroup =
false;
582 const Poco::XML::XMLString
value = pNode->innerText();
584 if (pNode->nodeName() ==
"group") {
588 }
else if (pNode->nodeName() ==
"component") {
593 g_log.
error() <<
"XML File hierarchical (component) error!\n";
596 }
else if (pNode->nodeName() ==
"ids") {
599 parseRangeText(
value, singleSp, pairSp);
601 g_log.
error() <<
"XML File (ids) hierarchical error!"
602 <<
" Inner Text = " << pNode->innerText() <<
'\n';
605 }
else if (pNode->nodeName() ==
"detids") {
608 parseRangeText(
value, maskSingleDet, maskPairDet);
610 g_log.
error() <<
"XML File (detids) hierarchical error!\n";
613 }
else if (pNode->nodeName() ==
"detector-masking") {
618 pNode = it.nextNode();
622 convertToVector(maskSingleDet, maskPairDet,
m_maskDetID);
637 std::vector<int32_t> &singleDetIds) {
642 std::multimap<size_t, Mantid::detid_t> spectr2index_map;
643 for (
auto &it : sourceDetMap) {
644 spectr2index_map.insert(std::pair<size_t, Mantid::detid_t>(it.second, it.first));
646 for (
int i : maskedSpecID) {
648 const auto itSpec = s2imap.find(i);
649 if (itSpec == s2imap.end()) {
650 throw std::runtime_error(
"Can not find spectra with ID: " + boost::lexical_cast<std::string>(i) +
651 " in the workspace" + sourceWS.
getName());
653 size_t specN = itSpec->second;
656 const auto source_range = spectr2index_map.equal_range(specN);
657 if (source_range.first == spectr2index_map.end()) {
658 throw std::runtime_error(
"Can not find spectra N: " + boost::lexical_cast<std::string>(specN) +
659 " in the workspace" + sourceWS.
getName());
662 for (
auto it = source_range.first; it != source_range.second; ++it) {
663 singleDetIds.emplace_back(it->second);
677 const bool ignoreDirs(
true);
689 loadInst->executeAsChildAlg();
691 if (!loadInst->isExecuted()) {
693 throw std::invalid_argument(
"Incorrect instrument name or invalid IDF given.");
707 std::map<std::string, std::string> result;
712 boost::trim(InstrName);
713 boost::algorithm::to_lower(InstrName);
714 size_t len = InstrName.size();
717 bool IDF_provided{
false};
721 if (InstrName.compare(len - 4, len,
".xml") == 0) {
724 IDF_provided =
false;
727 IDF_provided =
false;
730 auto inst = inputWS->getInstrument();
731 std::string Name = inst->getName();
732 boost::algorithm::to_lower(Name);
733 if (Name != InstrName && !IDF_provided) {
734 result[
"RefWorkspace"] =
"If both reference workspace and instrument name are defined, "
735 "workspace has to have the instrument with the same name\n"
736 "'Instrument' value: " +
737 InstrName +
" Workspace Instrument name: " + Name;
740 result[
"RefWorkspace"] =
"If reference workspace is defined, it mast have an instrument";
#define DECLARE_ALGORITHM(classname)
double value
The value of the point.
std::map< DeltaEMode::Type, std::string > index
TypedValue getProperty(const std::string &name) const override
Get the value of a property.
virtual std::shared_ptr< Algorithm > createChildAlgorithm(const std::string &name, const double startProgress=-1., const double endProgress=-1., const bool enableLogging=true, const int &version=-1)
Create a Child Algorithm.
@ Load
allowed here which will be passed to the algorithm
Base MatrixWorkspace Abstract Class.
detid2index_map getDetectorIDToWorkspaceIndexMap(bool throwIfMultipleDets=false, bool ignoreIfNoValidDets=false) const
Return a map where: KEY is the DetectorID (pixel ID) VALUE is the Workspace Index.
spec2index_map getSpectrumToWorkspaceIndexMap() const
Return a map where: KEY is the Spectrum # VALUE is the Workspace Index.
A property class for workspaces.
const std::string & getName() const override
Get the workspace name.
LoadMask : Load masking file to generate a SpecialWorkspace2D object (masking workspace).
DataObjects::MaskWorkspace_sptr m_maskWS
Mask Workspace.
void processMaskOnWorkspaceIndex(bool mask, std::vector< specnum_t > &maskedSpecID, std::vector< detid_t > &singleDetIds)
Convert spectrum to detector.
void processMaskOnDetectors(const detid2index_map &indexmap, bool tomask, const std::vector< detid_t > &singledetids)
Mask detectors or Unmask detectors.
void convertSpMasksToDetIDs(const API::MatrixWorkspace &sourceWS, const std::vector< specnum_t > &maskedSpecID, std::vector< detid_t > &singleDetIds)
std::vector< std::string > m_uMaskCompIdSingle
Poco::XML::Element * m_pRootElem
Root element of the parsed XML.
void componentToDetectors(const std::vector< std::string > &componentnames, std::vector< detid_t > &detectors)
Convert component to detectors.
std::map< std::string, std::string > validateInputs() override
Validates if either input workspace or instrument name is defined.
std::string m_instrumentPropValue
Instrument name.
std::vector< std::string > m_maskCompIdSingle
std::vector< detid_t > m_maskDetID
bool m_defaultToUse
Default setup. If true, not masking, but use the pixel.
void exec() override
Run the algorithm.
Poco::AutoPtr< Poco::XML::Document > m_pDoc
XML document loaded.
std::vector< specnum_t > m_maskSpecID
void intializeMaskWorkspace()
Initialize a Mask Workspace.
void initializeXMLParser(const std::string &filename)
Initialize XML parser.
void parseXML()
Parse XML.
void bankToDetectors(const std::vector< std::string > &singlebanks, std::vector< detid_t > &detectors)
Convert bank to detector.
std::vector< detid_t > m_unMaskDetID
API::MatrixWorkspace_sptr m_sourceMapWS
optional source workspace, containing spectra-detector mapping
Concrete workspace implementation.
Records the filename and the description of failure.
Exception for errors associated with the instrument definition.
Exception for when an item is not found in a collection.
IPropertyManager * setProperty(const std::string &name, const T &value)
Templated method to set the value of a PropertyWithValue.
void debug(const std::string &msg)
Logs at debug level.
void error(const std::string &msg)
Logs at error level.
void warning(const std::string &msg)
Logs at warning level.
void information(const std::string &msg)
Logs at information level.
Validator to check that a property is not left empty.
OptionalBool : Tri-state bool.
static T & Instance()
Return a reference to the Singleton instance, creating it if it does not already exist Creation is do...
std::shared_ptr< MatrixWorkspace > MatrixWorkspace_sptr
shared pointer to the matrix workspace base class
std::shared_ptr< MaskWorkspace > MaskWorkspace_sptr
shared pointer to the MaskWorkspace class
std::shared_ptr< const IComponent > IComponent_const_sptr
Typdef of a shared pointer to a const IComponent.
std::shared_ptr< const Mantid::Geometry::IDetector > IDetector_const_sptr
Shared pointer to IDetector (const version)
std::shared_ptr< const Instrument > Instrument_const_sptr
Shared pointer to an const instrument object.
MANTID_KERNEL_DLL std::string loadFile(const std::string &filename)
Loads the entire contents of a text file into a string.
std::unordered_map< specnum_t, size_t > spec2index_map
Map with key = spectrum number, value = workspace index.
int32_t detid_t
Typedef for a detector ID.
std::unordered_map< detid_t, size_t > detid2index_map
Map with key = detector ID, value = workspace index.
@ Input
An input workspace.
@ Output
An output workspace.