LoadMask.cpp 28.1 KB
Newer Older
1
#include "MantidDataHandling/LoadMask.h"
2
3
#include "MantidKernel/System.h"
#include "MantidAPI/FileProperty.h"
4
#include "MantidAPI/FileFinder.h"
5
#include "MantidKernel/MandatoryValidator.h"
6
7
#include "MantidKernel/ListValidator.h"
#include "MantidDataObjects/Workspace2D.h"
8
#include "MantidDataObjects/MaskWorkspace.h"
9
10
#include "MantidKernel/Strings.h"
#include "MantidGeometry/Instrument.h"
11
#include "MantidGeometry/ICompAssembly.h"
12
13
#include "MantidGeometry/IDTypes.h"

14
#include <fstream>
15
#include <sstream>
16

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <Poco/DOM/Document.h>
#include <Poco/DOM/DOMParser.h>
#include <Poco/DOM/Element.h>
#include <Poco/DOM/NodeFilter.h>
#include <Poco/DOM/NodeIterator.h>
#include <Poco/DOM/NodeList.h>
#include <Poco/Exception.h>

#include <boost/algorithm/string.hpp>

using Poco::XML::DOMParser;
using Poco::XML::Document;
using Poco::XML::Element;
using Poco::XML::Node;
using Poco::XML::NodeList;
using Poco::XML::NodeIterator;
using Poco::XML::NodeFilter;

using namespace Mantid::Kernel;
using namespace Mantid::API;
37
using namespace std;
38

39
40
41
42
43
44
45
46
namespace Mantid {
namespace DataHandling {

DECLARE_ALGORITHM(LoadMask)

//----------------------------------------------------------------------------------------------
/** Constructor
 */
47
48
49
LoadMask::LoadMask()
    : m_maskWS(), m_instrumentPropValue(""), m_pDoc(NULL), m_pRootElem(NULL),
      m_defaultToUse(true) {}
50
51
52
53
54

//----------------------------------------------------------------------------------------------
/** Destructor
 */
LoadMask::~LoadMask() {
55
56
  // note Poco::XML::Document and Poco::XML::Element declare their constructors
  // as protected
57
58
  if (m_pDoc)
    m_pDoc->release();
59
60
61
62
  // note that m_pRootElem does not need a release(), and that can
  // actually cause a double free corruption, as
  // Poco::DOM::Document::documentElement() does not require a
  // release(). So just to be explicit that they're gone:
63
  m_pDoc = NULL;
64
  m_pRootElem = NULL;
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
}

/// Initialise the properties
void LoadMask::init() {

  // 1. Declare property
  declareProperty("Instrument", "",
                  boost::make_shared<MandatoryValidator<std::string>>(),
                  "The name of the instrument to apply the mask.");
  std::vector<std::string> exts;
  exts.push_back(".xml");
  exts.push_back(".msk");
  declareProperty(new FileProperty("InputFile", "", FileProperty::Load, exts),
                  "Masking file for masking. Supported file format is XML and "
                  "ISIS ASCII. ");
  declareProperty(new WorkspaceProperty<DataObjects::MaskWorkspace>(
                      "OutputWorkspace", "Masking", Direction::Output),
                  "Output Masking Workspace");

  return;
}

//----------------------------------------------------------------------------------------------
/** Main execution body of this algorithm
  */
void LoadMask::exec() {
  // 1. Load Instrument and create output Mask workspace
  const std::string instrumentname = getProperty("Instrument");
  m_instrumentPropValue = instrumentname;

  this->intializeMaskWorkspace();
96
  setProperty("OutputWorkspace", m_maskWS);
97

98
  m_defaultToUse = true;
99
100
101
102
103
104
105
106
107
108
109
110

  // 2. Parse Mask File
  std::string filename = getProperty("InputFile");

  if (boost::ends_with(filename, "l") || boost::ends_with(filename, "L")) {
    // 2.1 XML File
    this->initializeXMLParser(filename);
    this->parseXML();
  } else if (boost::ends_with(filename, "k") ||
             boost::ends_with(filename, "K")) {
    // 2.2 ISIS Masking file
    loadISISMaskFile(filename);
111
    m_defaultToUse = true;
112
113
114
  } else {
    g_log.error() << "File " << filename << " is not in supported format. "
                  << std::endl;
115
116
    return;
  }
Zhou, Wenduo's avatar
Zhou, Wenduo committed
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
  // 3. Translate and set geometry
  g_log.information() << "To Mask: " << std::endl;
  std::vector<int32_t> maskdetids;
  std::vector<int32_t> maskdetidpairsL;
  std::vector<int32_t> maskdetidpairsU;

  componentToDetectors(mask_bankid_single, maskdetids);
  detectorToDetectors(mask_detid_single, mask_detid_pair_low,
                      mask_detid_pair_up, maskdetids, maskdetidpairsL,
                      maskdetidpairsU);

  g_log.information() << "To UnMask: " << std::endl;
  std::vector<int32_t> unmaskdetids;
  std::vector<int32_t> unmaskdetidpairsL;
  std::vector<int32_t> unmaskdetidpairsU;

  this->bankToDetectors(unmask_bankid_single, unmaskdetids, unmaskdetidpairsL,
                        unmaskdetidpairsU);
  this->detectorToDetectors(unmask_detid_single, unmask_detid_pair_low,
                            unmask_detid_pair_up, unmaskdetids,
                            unmaskdetidpairsL, unmaskdetidpairsU);

  // 4. Apply
  this->initDetectors();
  this->processMaskOnDetectors(true, maskdetids, maskdetidpairsL,
                               maskdetidpairsU);
  this->processMaskOnWorkspaceIndex(true, mask_specid_pair_low,
                                    mask_specid_pair_up);

  this->processMaskOnDetectors(false, unmaskdetids, unmaskdetidpairsL,
                               unmaskdetidpairsU);

  return;
}

void LoadMask::initDetectors() {

155
156
  if (!m_defaultToUse) { // Default is to use all detectors
    size_t numHist = m_maskWS->getNumberHistograms();
157
    for (size_t wkspIndex = 0; wkspIndex < numHist; wkspIndex++) {
158
      m_maskWS->setMaskedIndex(wkspIndex);
159
    }
160
161
  }

162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
  return;
}

//----------------------------------------------------------------------------------------------
/**  Mask detectors or Unmask detectors
 *   @param tomask:  true to mask, false to unmask
 *   @param singledetids: list of individual det ids to mask
 *   @param pairdetids_low: list of lower bound of det ids to mask
 *   @param pairdetids_up: list of upper bound of det ids to mask
 */
void LoadMask::processMaskOnDetectors(bool tomask,
                                      std::vector<int32_t> singledetids,
                                      std::vector<int32_t> pairdetids_low,
                                      std::vector<int32_t> pairdetids_up) {
  // 1. Get index map
  const detid2index_map indexmap =
178
      m_maskWS->getDetectorIDToWorkspaceIndexMap(true);
179
180
181
182
183
184
185
186
187
188
189
190
191

  // 2. Mask
  g_log.debug() << "Mask = " << tomask
                << "  Final Single IDs Size = " << singledetids.size()
                << std::endl;

  for (size_t i = 0; i < singledetids.size(); i++) {
    detid_t detid = singledetids[i];
    detid2index_map::const_iterator it;
    it = indexmap.find(detid);
    if (it != indexmap.end()) {
      size_t index = it->second;
      if (tomask)
192
        m_maskWS->dataY(index)[0] = 1;
193
      else
194
        m_maskWS->dataY(index)[0] = 0;
195
196
197
    } else {
      g_log.error() << "Pixel w/ ID = " << detid << " Cannot Be Located"
                    << std::endl;
198
    }
199
  }
200

201
202
203
204
205
  // 3. Mask pairs
  for (size_t i = 0; i < pairdetids_low.size(); i++) {
    g_log.error() << "To Be Implemented Soon For Pair (" << pairdetids_low[i]
                  << ", " << pairdetids_up[i] << "!" << std::endl;
  }
206

207
208
209
210
211
212
213
214
215
  return;
}

//----------------------------------------------------------------------------------------------
/** Convert a component to detectors.  It is a generalized version of
 * bankToDetectors()
 */
void LoadMask::componentToDetectors(std::vector<std::string> componentnames,
                                    std::vector<int32_t> &detectors) {
216
  Geometry::Instrument_const_sptr minstrument = m_maskWS->getInstrument();
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232

  for (size_t i = 0; i < componentnames.size(); i++) {
    g_log.debug() << "Component name = " << componentnames[i] << std::endl;

    // a) get component
    Geometry::IComponent_const_sptr component =
        minstrument->getComponentByName(componentnames[i]);
    if (component)
      g_log.debug() << "Component ID = " << component->getComponentID()
                    << std::endl;
    else {
      // A non-exiting component.  Ignore
      g_log.warning() << "Component " << componentnames[i] << " does not exist!"
                      << std::endl;
      continue;
    }
233

234
235
236
237
238
    // b) component -> component assembly --> children (more than detectors)
    boost::shared_ptr<const Geometry::ICompAssembly> asmb =
        boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(component);
    std::vector<Geometry::IComponent_const_sptr> children;
    asmb->getChildren(children, true);
239

240
    g_log.debug() << "Number of Children = " << children.size() << std::endl;
241

242
243
244
    int32_t numdets = 0;
    int32_t id_min = 1000000;
    int32_t id_max = 0;
245

246
247
248
249
250
    for (size_t ic = 0; ic < children.size(); ic++) {
      // c) convert component to detector
      Geometry::IComponent_const_sptr child = children[ic];
      Geometry::IDetector_const_sptr det =
          boost::dynamic_pointer_cast<const Geometry::IDetector>(child);
251

252
253
254
255
256
257
258
259
      if (det) {
        int32_t detid = det->getID();
        detectors.push_back(detid);
        numdets++;
        if (detid < id_min)
          id_min = detid;
        if (detid > id_max)
          id_max = detid;
260
261
262
      }
    }

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
    g_log.debug() << "Number of Detectors in Children = " << numdets
                  << "  Range = " << id_min << ", " << id_max << std::endl;
  } // for component

  return;
}

//----------------------------------------------------------------------------------------------
/** Convert bank to detectors
 */
void LoadMask::bankToDetectors(std::vector<std::string> singlebanks,
                               std::vector<int32_t> &detectors,
                               std::vector<int32_t> &detectorpairslow,
                               std::vector<int32_t> &detectorpairsup) {
  std::stringstream infoss;
  infoss << "Bank IDs to be converted to detectors: " << endl;
  for (size_t i = 0; i < singlebanks.size(); i++) {
    infoss << "Bank: " << singlebanks[i] << std::endl;
281
  }
282
  g_log.debug(infoss.str());
283

284
  Geometry::Instrument_const_sptr minstrument = m_maskWS->getInstrument();
285

286
287
  for (size_t ib = 0; ib < singlebanks.size(); ib++) {
    std::vector<Geometry::IDetector_const_sptr> idetectors;
288

289
290
291
    minstrument->getDetectorsInBank(idetectors, singlebanks[ib]);
    g_log.debug() << "Bank: " << singlebanks[ib] << " has " << idetectors.size()
                  << " detectors" << std::endl;
292

293
294
295
296
    // a) get information
    size_t numdets = idetectors.size();
    detid_t detid_first = idetectors[0]->getID();
    detid_t detid_last = idetectors[idetectors.size() - 1]->getID();
297

298
299
300
301
    // b) set detectors
    if (detid_first + int32_t(numdets) == detid_last + 1 && false) {
      // TODO This save-time method is not used at this stage
      g_log.information() << "Using Range of Detectors" << std::endl;
302

303
304
      detectorpairslow.push_back(detid_first);
      detectorpairsup.push_back(detid_last);
305

306
307
308
309
    } else {
      g_log.debug() << "Apply 1 by 1  "
                    << "DetID: " << detid_first << ", " << detid_last
                    << std::endl;
310

311
312
313
314
      for (size_t i = 0; i < idetectors.size(); i++) {
        Geometry::IDetector_const_sptr det = idetectors[i];
        int32_t detid = det->getID();
        detectors.push_back(detid);
315
316
      }

317
318
319
320
321
    } // if-else
  }   // ENDFOR

  return;
}
322

323
324
325
326
327
328
329
330
//----------------------------------------------------------------------------------------------
/** Set the mask on the spectrum IDs
 */
void LoadMask::processMaskOnWorkspaceIndex(bool mask,
                                           std::vector<int32_t> pairslow,
                                           std::vector<int32_t> pairsup) {
  // 1. Check
  if (pairslow.size() == 0)
331
    return;
332
333
334
335
336
  if (pairslow.size() != pairsup.size()) {
    g_log.error() << "Input spectrum IDs are not paired.  Size(low) = "
                  << pairslow.size() << ", Size(up) = " << pairsup.size()
                  << std::endl;
    throw std::invalid_argument("Input spectrum IDs are not paired. ");
337
338
  }

339
  // 2. Get Map
340
  const spec2index_map s2imap = m_maskWS->getSpectrumToWorkspaceIndexMap();
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
  spec2index_map::const_iterator s2iter;

  // 3. Set mask
  for (size_t i = 0; i < pairslow.size(); i++) {
    // TODO Make this function work!
    g_log.debug() << "Mask Spectrum " << pairslow[i] << "  To " << pairsup[i]
                  << std::endl;

    for (int32_t specid = pairslow[i]; specid <= pairsup[i]; specid++) {
      s2iter = s2imap.find(specid);
      if (s2iter == s2imap.end()) {
        // spectrum not found.  bad brach
        g_log.error()
            << "Spectrum " << specid
            << " does not have an entry in GroupWorkspace's spec2index map"
            << std::endl;
        throw std::runtime_error("Logic error");
      } else {
        size_t wsindex = s2iter->second;
360
        if (wsindex >= m_maskWS->getNumberHistograms()) {
361
362
363
364
365
          // workspace index is out of range.  bad branch
          g_log.error() << "Group workspace's spec2index map is set wrong: "
                        << " Found workspace index = " << wsindex
                        << " for spectrum ID " << specid
                        << " with workspace size = "
366
                        << m_maskWS->getNumberHistograms() << std::endl;
367
368
369
        } else {
          // Finally set the group workspace.  only good branch
          if (mask)
370
            m_maskWS->dataY(wsindex)[0] = 1.0;
371
          else
372
            m_maskWS->dataY(wsindex)[0] = 0.0;
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
        } // IF-ELSE: ws index out of range
      }   // IF-ELSE: spectrum ID has an entry
    }     // FOR EACH SpecID
  }       // FOR EACH Pair

  return;
}

//----------------------------------------------------------------------------------------------
/** Convert spectrum to detectors
 */
void LoadMask::detectorToDetectors(std::vector<int32_t> singles,
                                   std::vector<int32_t> pairslow,
                                   std::vector<int32_t> pairsup,
                                   std::vector<int32_t> &detectors,
                                   std::vector<int32_t> &detectorpairslow,
                                   std::vector<int32_t> &detectorpairsup) {
  UNUSED_ARG(detectorpairslow)
  UNUSED_ARG(detectorpairsup)
392

393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
  /*
  for (size_t i = 0; i < singles.size(); i ++){
    g_log.information() << "Detector " << singles[i] << std::endl;
  }
  for (size_t i = 0; i < pairslow.size(); i ++){
    g_log.information() << "Detector " << pairslow[i] << "  To " << pairsup[i]
  << std::endl;
  }
  */
  for (size_t i = 0; i < singles.size(); i++) {
    detectors.push_back(singles[i]);
  }
  for (size_t i = 0; i < pairslow.size(); i++) {
    for (int32_t j = 0; j < pairsup[i] - pairslow[i] + 1; j++) {
      int32_t detid = pairslow[i] + j;
      detectors.push_back(detid);
    }
    /*
    detectorpairslow.push_back(pairslow[i]);
    detectorpairsup.push_back(pairsup[i]);
    */
  }
415

416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
  return;
}

//----------------------------------------------------------------------------------------------
/** Initalize Poco XML Parser
 */
void LoadMask::initializeXMLParser(const std::string &filename) {
  // const std::string instName
  std::cout << "Load File " << filename << std::endl;
  const std::string xmlText = Kernel::Strings::loadFile(filename);
  std::cout << "Successfully Load XML File " << std::endl;

  // Set up the DOM parser and parse xml file
  DOMParser pParser;
  try {
431
    m_pDoc = pParser.parseString(xmlText);
432
433
434
435
436
437
438
  } catch (Poco::Exception &exc) {
    throw Kernel::Exception::FileError(
        exc.displayText() + ". Unable to parse File:", filename);
  } catch (...) {
    throw Kernel::Exception::FileError("Unable to parse File:", filename);
  }
  // Get pointer to root element
439
440
  m_pRootElem = m_pDoc->documentElement();
  if (!m_pRootElem->hasChildNodes()) {
441
442
443
444
445
446
447
448
449
450
451
    g_log.error("XML file: " + filename + "contains no root element.");
    throw Kernel::Exception::InstrumentDefinitionError(
        "No root element in XML instrument file", filename);
  }
}

//----------------------------------------------------------------------------------------------
/** Parse XML file
 */
void LoadMask::parseXML() {
  // 0. Check
452
  if (!m_pDoc)
453
454
455
    throw std::runtime_error("Call LoadMask::initialize() before parseXML.");

  // 1. Parse and create a structure
456
  Poco::AutoPtr<NodeList> pNL_type = m_pRootElem->getElementsByTagName("type");
457
458
  g_log.information() << "Node Size = " << pNL_type->length() << std::endl;

459
  Poco::XML::NodeIterator it(m_pDoc, Poco::XML::NodeFilter::SHOW_ELEMENT);
460
461
462
463
464
465
466
467
468
469
470
471
472
  Poco::XML::Node *pNode = it.nextNode();

  bool tomask = true;
  bool ingroup = false;
  while (pNode) {
    const Poco::XML::XMLString value = pNode->innerText();

    if (pNode->nodeName().compare("group") == 0) {
      // Node "group"
      ingroup = true;
      tomask = true;
      /*
      // get type
473
      Poco::AutoPtr<Poco::XML::NamedNodeMap> att = pNode->attributes();
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
      Poco::XML::Node* cNode = att->item(0);
      if (cNode->getNodeValue().compare("mask") == 0 ||
      cNode->getNodeValue().compare("notuse") == 0){
        tomask = true;
      } else if (cNode->getNodeValue().compare("unmask") == 0 ||
      cNode->getNodeValue().compare("use") == 0){
        tomask = false;
      } else {
        g_log.error() << "Type (" << cNode->localName() << ") = " <<
      cNode->getNodeValue() << " is not supported!" << std::endl;
      }
      g_log.information() << "Node Group:  child Node Name = " <<
      cNode->localName() << ": " << cNode->getNodeValue()
              << "(always)"<< std::endl;
      */
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
    } else if (pNode->nodeName().compare("component") == 0) {
      // Node "component"
      if (ingroup) {
        this->parseComponent(value, tomask);
      } else {
        g_log.error() << "XML File heirachial (component) error!" << std::endl;
      }
      // g_log.information() << "Component: " << value << std::endl;

    } else if (pNode->nodeName().compare("ids") == 0) {
      // Node "ids"
      if (ingroup) {
        this->parseSpectrumIDs(value, tomask);
      } else {
        g_log.error() << "XML File (ids) heirachial error!"
                      << "  Inner Text = " << pNode->innerText() << std::endl;
      }
      // g_log.information() << "detids: " << value << std::endl;

    } else if (pNode->nodeName().compare("detids") == 0) {
      // Node "detids"
      if (ingroup) {
        this->parseDetectorIDs(value, tomask);
      } else {
        g_log.error() << "XML File (detids) heirachial error!" << std::endl;
      }
516

517
518
    } else if (pNode->nodeName().compare("detector-masking") == 0) {
      // Node "detector-masking".  Check default value
519
      m_defaultToUse = true;
520
      /*
521
      Poco::AutoPtr<Poco::XML::NamedNodeMap> att = pNode->attributes();
522
523
      if (att->length() > 0){
        Poco::XML::Node* cNode = att->item(0);
524
        m_defaultToUse = true;
525
526
        if (cNode->localName().compare("default") == 0){
          if (cNode->getNodeValue().compare("use") == 0){
527
            m_defaultToUse = true;
528
          } else {
529
            m_defaultToUse = false;
530
531
532
533
          }
      } // if - att-length
      */
    } // END-IF-ELSE: pNode->nodeName()
534

535
536
    pNode = it.nextNode();
  } // ENDWHILE
537

538
539
  return;
}
540

541
542
543
544
545
546
547
//----------------------------------------------------------------------------------------------
/** Parse bank IDs (string name)
 * Sample:  bank2
 * @param valuetext:  must be bank name
 * @param tomask: if true, mask, if not unmask
 */
void LoadMask::parseComponent(std::string valuetext, bool tomask) {
548

549
550
551
552
553
554
  // 1. Parse bank out
  /*
  std::vector<std::string> values;
  this->splitString(valuetext, values, "bank");
  if (values.size() <= 1){
    g_log.error() << "Bank information format error!" << std::endl;
555
556
    return;
  }
557
  */
558

559
560
561
562
563
  if (tomask) {
    mask_bankid_single.push_back(valuetext);
  } else {
    unmask_bankid_single.push_back(valuetext);
  }
564

565
566
567
  /*
  for (size_t i = 0; i < singles.size(); i ++){
    g_log.information() << "Bank " << singles[i] << std::endl;
568
  }
569
570
571
572
573
  for (size_t i = 0; i < pairs.size()/2; i ++){
    g_log.information() << "Bank " << pairs[2*i] << "  To " << pairs[2*i+1] <<
  std::endl;
  }
  */
574

575
576
  return;
}
577

578
579
580
581
//----------------------------------------------------------------------------------------------
/** Parse input string for spectrum ID
 */
void LoadMask::parseSpectrumIDs(std::string inputstr, bool tomask) {
582

583
584
585
586
  // 1. Parse range out
  std::vector<int32_t> singles;
  std::vector<int32_t> pairs;
  this->parseRangeText(inputstr, singles, pairs);
587

588
589
590
591
  // 2. Set to data storage
  if (tomask) {
    for (size_t i = 0; i < singles.size(); i++) {
      mask_specid_single.push_back(singles[i]);
592
    }
593
594
595
    for (size_t i = 0; i < pairs.size() / 2; i++) {
      mask_specid_pair_low.push_back(pairs[2 * i]);
      mask_specid_pair_up.push_back(pairs[2 * i + 1]);
596
    }
597
598
599
  } else {
    for (size_t i = 0; i < singles.size(); i++) {
      unmask_specid_single.push_back(singles[i]);
600
    }
601
602
603
    for (size_t i = 0; i < pairs.size() / 2; i++) {
      unmask_specid_pair_low.push_back(pairs[2 * i]);
      unmask_specid_pair_up.push_back(pairs[2 * i + 1]);
604
605
606
    }
  }

607
608
  return;
}
609

610
611
612
613
614
//----------------------------------------------------------------------------------------------
/** Parse input string for spectrum ID
 */
void LoadMask::parseDetectorIDs(std::string inputstr, bool tomask) {
  // g_log.information() << "Detector IDs: " << inputstr << std::endl;
615

616
617
618
619
  // 1. Parse range out
  std::vector<int32_t> singles;
  std::vector<int32_t> pairs;
  this->parseRangeText(inputstr, singles, pairs);
620

621
622
623
624
  // 2. Set to data storage
  if (tomask) {
    for (size_t i = 0; i < singles.size(); i++) {
      mask_detid_single.push_back(singles[i]);
625
    }
626
627
628
    for (size_t i = 0; i < pairs.size() / 2; i++) {
      mask_detid_pair_low.push_back(pairs[2 * i]);
      mask_detid_pair_up.push_back(pairs[2 * i + 1]);
629
    }
630
631
632
  } else {
    for (size_t i = 0; i < singles.size(); i++) {
      unmask_detid_single.push_back(singles[i]);
633
    }
634
635
636
    for (size_t i = 0; i < pairs.size() / 2; i++) {
      unmask_detid_pair_low.push_back(pairs[2 * i]);
      unmask_detid_pair_up.push_back(pairs[2 * i + 1]);
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
  return;
}

/*
 * Parse index range text to singles and pairs
 * Example: 3,4,9-10,33
 */
void LoadMask::parseRangeText(std::string inputstr,
                              std::vector<int32_t> &singles,
                              std::vector<int32_t> &pairs) {
  // 1. Split ','
  std::vector<std::string> rawstrings;
  this->splitString(inputstr, rawstrings, ",");

  // 2. Filter
  std::vector<std::string> strsingles;
  std::vector<std::string> strpairs;
  for (size_t i = 0; i < rawstrings.size(); i++) {
    // a) Find '-':
    bool containto = false;
    const char *tempchs = rawstrings[i].c_str();
    for (size_t j = 0; j < rawstrings[i].size(); j++)
      if (tempchs[j] == '-') {
        containto = true;
        break;
665
      }
666
667
668
669
670
671
    // b) Rebin
    if (containto)
      strpairs.push_back(rawstrings[i]);
    else
      strsingles.push_back(rawstrings[i]);
  } // ENDFOR i
672

673
674
675
676
  // 3. Treat singles
  for (size_t i = 0; i < strsingles.size(); i++) {
    int32_t itemp = atoi(strsingles[i].c_str());
    singles.push_back(itemp);
677
678
  }

679
680
681
682
683
684
685
686
687
  // 4. Treat pairs
  for (size_t i = 0; i < strpairs.size(); i++) {
    // a) split and check
    std::vector<std::string> ptemp;
    this->splitString(strpairs[i], ptemp, "-");
    if (ptemp.size() != 2) {
      g_log.error() << "Range string " << strpairs[i] << " has a wrong format!"
                    << std::endl;
      throw std::invalid_argument("Wrong format");
688
689
    }

690
691
692
693
694
695
696
    // b) parse
    int32_t intstart = atoi(ptemp[0].c_str());
    int32_t intend = atoi(ptemp[1].c_str());
    if (intstart >= intend) {
      g_log.error() << "Range string " << strpairs[i] << " has a reversed order"
                    << std::endl;
      throw std::invalid_argument("Wrong format");
697
    }
698
699
700
    pairs.push_back(intstart);
    pairs.push_back(intend);
  }
701

702
703
  return;
}
704

705
706
void LoadMask::splitString(std::string inputstr,
                           std::vector<std::string> &strings, std::string sep) {
707

708
709
710
  // std::vector<std::string> SplitVec;
  boost::split(strings, inputstr, boost::is_any_of(sep),
               boost::token_compress_on);
711

712
713
  // g_log.information() << "Inside... split size = " << strings.size() <<
  // std::endl;
714

715
716
  return;
}
717

718
719
720
721
/*
 * Load and parse an ISIS masking file
 */
void LoadMask::loadISISMaskFile(std::string isisfilename) {
722

723
724
725
726
727
  std::ifstream ifs;
  ifs.open(isisfilename.c_str(), std::ios::in);
  if (!ifs.is_open()) {
    g_log.error() << "Cannot open ISIS mask file " << isisfilename << endl;
    throw std::invalid_argument("Cannot open ISIS mask file");
728
729
  }

730
731
732
  std::string isisline;
  while (getline(ifs, isisline)) {
    boost::trim(isisline);
733

734
735
736
    // a. skip empty line
    if (isisline.size() == 0)
      continue;
737

738
739
740
    // b. skip comment line
    if (isisline.c_str()[0] < '0' || isisline.c_str()[0] > '9')
      continue;
741

742
743
744
745
746
    // c. parse
    g_log.debug() << "Input: " << isisline << std::endl;
    parseISISStringToVector(isisline, mask_specid_pair_low,
                            mask_specid_pair_up);
  }
747

748
749
750
751
  for (size_t i = 0; i < mask_specid_pair_low.size(); i++) {
    g_log.debug() << i << ": " << mask_specid_pair_low[i] << ", "
                  << mask_specid_pair_up[i] << std::endl;
  }
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
  ifs.close();

  return;
}

/*
 * Parse a line in an ISIS mask file string to vector
 * Combination of 5 types of format for unit
 * (1) a (2) a-b (3) a - b (4) a- b (5) a- b
 * separated by space(s)
 */
void LoadMask::parseISISStringToVector(string ins,
                                       std::vector<int> &rangestartvec,
                                       std::vector<int> &rangeendvec) {
  // 1. Split by space
  std::vector<string> splitstrings;
  boost::split(splitstrings, ins, boost::is_any_of(" "),
               boost::token_compress_on);

  // 2. Replace a-b to a - b, remove a-b and insert a, -, b
  bool tocontinue = true;
  size_t index = 0;
  while (tocontinue) {
    // a) Determine end of loop.  Note that loop size changes
    if (index == splitstrings.size() - 1) {
      tocontinue = false;
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
    // b) Need to split?
    vector<string> temps;
    boost::split(temps, splitstrings[index], boost::is_any_of("-"),
                 boost::token_compress_on);
    if (splitstrings[index].compare("-") == 0 || temps.size() == 1) {
      // Nothing to split
      index++;
    } else if (temps.size() == 2) {
      // Has a '-' inside.  Delete and Replace
      temps.insert(temps.begin() + 1, "-");
      splitstrings.erase(splitstrings.begin() + index);
      for (size_t ic = 0; ic < 3; ic++) {
        if (temps[ic].size() > 0) {
          splitstrings.insert(splitstrings.begin() + index, temps[ic]);
          index++;
        }
      }
    } else {
      // Exception
      g_log.error() << "String " << splitstrings[index]
                    << " has a wrong format.  Too many '-'" << std::endl;
      throw std::invalid_argument("Invalid string in input");
    }
804

805
806
    if (index >= splitstrings.size())
      tocontinue = false;
807

808
  } // END WHILE
809

810
811
812
813
814
815
  // 3. Put to output integer vector
  tocontinue = true;
  index = 0;
  while (tocontinue) {
    // i)   push to the starting vector
    rangestartvec.push_back(atoi(splitstrings[index].c_str()));
816

817
818
819
820
821
822
823
824
825
826
827
    // ii)  push the ending vector
    if (index == splitstrings.size() - 1 ||
        splitstrings[index + 1].compare("-") != 0) {
      // the next one is not '-'
      rangeendvec.push_back(atoi(splitstrings[index].c_str()));
      index++;
    } else {
      // the next one is '-', thus read '-', next
      rangeendvec.push_back(atoi(splitstrings[index + 2].c_str()));
      index += 3;
    }
828

829
830
831
    if (index >= splitstrings.size())
      tocontinue = false;
  } // END-WHILE
832

833
  splitstrings.clear();
834

835
836
  return;
}
837

838
839
840
841
//----------------------------------------------------------------------------------------------
/** Initialize the Mask Workspace with instrument
 */
void LoadMask::intializeMaskWorkspace() {
842
  const bool ignoreDirs(true);
843
844
  const std::string idfPath = API::FileFinder::Instance().getFullPath(
      m_instrumentPropValue, ignoreDirs);
845

846
  MatrixWorkspace_sptr tempWs(new DataObjects::Workspace2D());
847

848
849
  auto loadInst = createChildAlgorithm("LoadInstrument");
  loadInst->setProperty<MatrixWorkspace_sptr>("Workspace", tempWs);
850

851
852
853
854
  if (idfPath.empty())
    loadInst->setPropertyValue("InstrumentName", m_instrumentPropValue);
  else
    loadInst->setPropertyValue("Filename", m_instrumentPropValue);
855

856
857
  loadInst->setProperty("OverwriteSpectraMap",
                        Mantid::Kernel::OptionalBool(false));
858
  loadInst->executeAsChildAlg();
859

860
861
862
863
864
  if (!loadInst->isExecuted()) {
    g_log.error() << "Unable to load Instrument " << m_instrumentPropValue
                  << std::endl;
    throw std::invalid_argument(
        "Incorrect instrument name or invalid IDF given.");
865
866
  }

867
  m_maskWS = DataObjects::MaskWorkspace_sptr(
868
      new DataObjects::MaskWorkspace(tempWs->getInstrument()));
869
  m_maskWS->setTitle("Mask");
870
}
871
872
873

} // namespace Mantid
} // namespace DataHandling