PerformIndexOperations.cpp 12 KB
Newer Older
1
2
#include "MantidAlgorithms/PerformIndexOperations.h"
#include "MantidAPI/MatrixWorkspace.h"
3
#include "MantidAPI/AlgorithmManager.h"
4
#include "MantidKernel/Strings.h"
5
6
7
#include <boost/regex.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/algorithm/string.hpp>
8
9
10
11

using namespace Mantid::Kernel;
using namespace Mantid::API;

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
namespace {
/**
 * Command class for executing algorithms on workspaces and appending resulting
 * workspace together.
 */
class Command {
public:
  virtual bool isValid() const { return true; }

  virtual MatrixWorkspace_sptr execute(MatrixWorkspace_sptr input) const = 0;

  virtual MatrixWorkspace_sptr
  executeAndAppend(MatrixWorkspace_sptr inputWS,
                   MatrixWorkspace_sptr toAppend) const {
    if (!this->isValid()) {
      return toAppend;
    } else {
      MatrixWorkspace_sptr current = this->execute(inputWS);
      Mantid::API::AlgorithmManagerImpl &factory =
          Mantid::API::AlgorithmManager::Instance();
      auto conjoinWorkspaceAlg = factory.create("ConjoinWorkspaces");
      conjoinWorkspaceAlg->setChild(true);
      conjoinWorkspaceAlg->initialize();
      conjoinWorkspaceAlg->setProperty("InputWorkspace1", toAppend);
      conjoinWorkspaceAlg->setProperty("InputWorkspace2", current);
      conjoinWorkspaceAlg->execute();
      MatrixWorkspace_sptr outWS =
          conjoinWorkspaceAlg->getProperty("InputWorkspace1");
      return outWS;
41
    }
42
43
44
45
46
47
48
49
50
51
52
53
  }

  virtual ~Command() {}
};

/// Helper typedef
typedef std::vector<boost::shared_ptr<Command>> VecCommands;

/**
 * Command yielding no result.
 */
class NullCommand : public Command {
54
55
  bool isValid() const override { return false; }
  MatrixWorkspace_sptr execute(MatrixWorkspace_sptr) const override {
56
57
58
    throw std::runtime_error(
        "Should not be attempting ::execute on a NullCommand");
  }
59
  ~NullCommand() override {}
60
61
62
63
64
65
66
67
68
69
};

/**
 * Addition command for summing spectra together.
 */
class AdditionCommand : public Command {
private:
  std::vector<int> m_indexes;

public:
70
71
  explicit AdditionCommand(const std::vector<int> &indexes)
      : m_indexes(indexes) {}
72

73
  MatrixWorkspace_sptr execute(MatrixWorkspace_sptr inputWS) const override {
74
    MatrixWorkspace_sptr outWS;
75
    if (!m_indexes.empty()) {
76
77
78
79
80
81
82
83
84
85
86
87
88
89
      Mantid::API::AlgorithmManagerImpl &factory =
          Mantid::API::AlgorithmManager::Instance();
      auto sumSpectraAlg = factory.create("SumSpectra");
      sumSpectraAlg->setChild(true);
      sumSpectraAlg->initialize();
      sumSpectraAlg->setProperty("InputWorkspace", inputWS);
      sumSpectraAlg->setProperty("ListOfWorkspaceIndices", m_indexes);
      sumSpectraAlg->setPropertyValue("OutputWorkspace", "outWS");
      sumSpectraAlg->execute();
      outWS = sumSpectraAlg->getProperty("OutputWorkspace");
    }
    return outWS;
  }

90
  ~AdditionCommand() override {}
91
92
93
94
95
96
97
98
99
100
};

/**
 * Command for cropping spectra out of a workspace as a new workspace
 */
class CropCommand : public Command {
private:
  std::vector<int> m_indexes;

public:
101
  explicit CropCommand(const std::vector<int> &indexes) : m_indexes(indexes) {}
102

103
  MatrixWorkspace_sptr execute(MatrixWorkspace_sptr inputWS) const override {
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

    MatrixWorkspace_sptr outWS;
    for (size_t i = 0; i < m_indexes.size(); ++i) {
      Mantid::API::AlgorithmManagerImpl &factory =
          Mantid::API::AlgorithmManager::Instance();
      auto cropWorkspaceAlg = factory.create("CropWorkspace");
      cropWorkspaceAlg->setChild(true);
      cropWorkspaceAlg->initialize();
      cropWorkspaceAlg->setProperty("InputWorkspace", inputWS);
      cropWorkspaceAlg->setProperty("StartWorkspaceIndex", m_indexes[i]);
      cropWorkspaceAlg->setProperty("EndWorkspaceIndex", m_indexes[i]);
      cropWorkspaceAlg->setPropertyValue("OutputWorkspace", "outWS");
      cropWorkspaceAlg->execute();
      MatrixWorkspace_sptr subRange =
          cropWorkspaceAlg->getProperty("OutputWorkspace");
      if (i == 0) {
        outWS = subRange;
      } else {
122
123
124
        auto conjoinWorkspaceAlg = factory.create("ConjoinWorkspaces");
        conjoinWorkspaceAlg->setChild(true);
        conjoinWorkspaceAlg->initialize();
125
126
        conjoinWorkspaceAlg->setProperty("InputWorkspace1", outWS);
        conjoinWorkspaceAlg->setProperty("InputWorkspace2", subRange);
127
        conjoinWorkspaceAlg->execute();
128
        outWS = conjoinWorkspaceAlg->getProperty("InputWorkspace1");
129
130
      }
    }
131
132
    return outWS;
  }
133
  ~CropCommand() override {}
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
};

/**
 * Abstract type. Command parsing interface.
 */
class CommandParser {
public:
  virtual Command *interpret(const std::string &instruction) const = 0;

  virtual ~CommandParser() {}
};

/// Helper typedef for vector of command parsers
typedef std::vector<boost::shared_ptr<CommandParser>> VecCommandParsers;

/**
 * Command parser base class for common concrete command parser types.
 */
template <typename ProductType> class CommandParserBase : public CommandParser {
public:
154
  Command *interpret(const std::string &instruction) const override {
155
    Command *command = nullptr;
156
157
158
159
160
161
162
163
164
165
    boost::regex ex = getRegex();
    if (boost::regex_match(instruction, ex)) {
      auto indexes =
          Mantid::Kernel::Strings::parseRange(instruction, ",", getSeparator());
      command = new ProductType(indexes);
    } else {
      command = new NullCommand;
    }
    return command;
  }
166
  ~CommandParserBase() override {}
167
168
169
170
171
172
173
174
175
176
177

private:
  virtual std::string getSeparator() const = 0;
  virtual boost::regex getRegex() const = 0;
};

/**
 * Parser to interpret Range Addition instructions.
 */
class AdditionParserRange : public CommandParserBase<AdditionCommand> {
public:
178
  ~AdditionParserRange() override {}
179
180

private:
181
  boost::regex getRegex() const override {
182
183
    return boost::regex("^\\s*[0-9]+\\s*\\-\\s*[0-9]+\\s*$");
  }
184
  std::string getSeparator() const override { return "-"; }
185
186
187
188
189
190
191
};

/**
 * Parser to interpret Addition instructions.
 */
class AdditionParser : public CommandParser {
public:
192
  ~AdditionParser() override {}
193

194
  Command *interpret(const std::string &instruction) const override {
195
    Command *command = nullptr;
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
    boost::regex ex("^\\s*[0-9]+\\s*\\+\\s*[0-9]+\\s*$");
    if (boost::regex_match(instruction, ex)) {
      std::vector<std::string> arguments;
      boost::split(arguments, instruction, boost::is_any_of("+"));
      int minIndex = -1;
      int maxIndex = -1;
      Mantid::Kernel::Strings::convert<int>(arguments.front(), minIndex);
      Mantid::Kernel::Strings::convert<int>(arguments.back(), maxIndex);
      std::vector<int> indexes;
      indexes.push_back(minIndex);
      indexes.push_back(maxIndex);
      command = new AdditionCommand(indexes);
    } else {
      command = new NullCommand;
    }
    return command;
  }
};

/**
 * Parser to interpret Crop Range instructions.
 */
class CropParserRange : public CommandParserBase<CropCommand> {
public:
220
  ~CropParserRange() override {}
221
222

private:
223
  boost::regex getRegex() const override {
224
225
    return boost::regex("^\\s*[0-9]+\\s*:\\s*[0-9]+\\s*$");
  }
226
  std::string getSeparator() const override { return ":"; }
227
228
229
230
231
232
233
};

/**
 * Parser to interpret single index cropping instructions
 */
class CropParserIndex : public CommandParser {
public:
234
  ~CropParserIndex() override {}
235

236
  Command *interpret(const std::string &instruction) const override {
237
    Command *command = nullptr;
238
239
240
241
242
243
244
245
246
247
248
249
250
    boost::regex ex("^\\s*[0-9]+\\s*$");
    if (boost::regex_match(instruction, ex)) {
      int index = -1;
      Mantid::Kernel::Strings::convert<int>(instruction, index);
      std::vector<int> indexes(1, index);
      command = new CropCommand(indexes);
    } else {
      command = new NullCommand;
    }
    return command;
  }
};
}
251

252
253
namespace Mantid {
namespace Algorithms {
254

255
256
// Register the algorithm into the AlgorithmFactory
DECLARE_ALGORITHM(PerformIndexOperations)
257

258
//------------------------------------------------------------------------------
259
260
/** Constructor
 */
261
PerformIndexOperations::PerformIndexOperations() {}
262

263
//------------------------------------------------------------------------------
264
265
266
/** Destructor
 */
PerformIndexOperations::~PerformIndexOperations() {}
267

268
//------------------------------------------------------------------------------
269
270
271
/// Algorithm's name for identification. @see Algorithm::name
const std::string PerformIndexOperations::name() const {
  return "PerformIndexOperations";
272
}
273

274
/// Algorithm's version for identification. @see Algorithm::version
275
int PerformIndexOperations::version() const { return 1; }
276

277
278
279
280
/// Algorithm's category for identification. @see Algorithm::category
const std::string PerformIndexOperations::category() const {
  return "Transforms\\Grouping";
}
281

282
//------------------------------------------------------------------------------
283

284
//------------------------------------------------------------------------------
285
286
287
/** Initialize the algorithm's properties.
 */
void PerformIndexOperations::init() {
288
289
  declareProperty(make_unique<WorkspaceProperty<MatrixWorkspace>>(
                      "InputWorkspace", "", Direction::Input),
290
                  "Input to processes workspace.");
291
292
  declareProperty(make_unique<PropertyWithValue<std::string>>(
                      "ProcessingInstructions", "", Direction::Input),
293
                  "Processing instructions. See full instruction list.");
294
295
  declareProperty(make_unique<WorkspaceProperty<MatrixWorkspace>>(
                      "OutputWorkspace", "", Direction::Output),
296
297
                  "Output processed workspace");
}
298

299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/**
 * Interpret the instructions as an ordered list of commands that can be
 *executed later.
 *
 * @param processingInstructions : Instructions to process
 * @return Vector of Commands. Commands wrap mantid-algorithmic steps to achieve
 *the desired result.
 */
VecCommands interpret(const std::string &processingInstructions) {
  std::vector<std::string> processingInstructionsSplit;
  boost::split(processingInstructionsSplit, processingInstructions,
               boost::is_any_of(","));

  VecCommandParsers commandParsers;
  commandParsers.push_back(boost::make_shared<AdditionParserRange>());
  commandParsers.push_back(boost::make_shared<CropParserRange>());
  commandParsers.push_back(boost::make_shared<CropParserIndex>());
  commandParsers.push_back(boost::make_shared<AdditionParser>());

  VecCommands commands;
319
  for (auto candidate : processingInstructionsSplit) {
320
    bool parserFound = false;
321
    for (auto commandParser : commandParsers) {
322
323
324
      Command *command = commandParser->interpret(candidate);
      boost::shared_ptr<Command> commandSptr(command);
      if (commandSptr->isValid()) // Do not record invalid commands.
325
      {
326
327
        parserFound = true;
        commands.push_back(commandSptr);
328
      }
329
    }
330
331
    if (!parserFound) {
      throw std::invalid_argument("Cannot interpret " + candidate);
332
    }
333
334
  }
  return commands;
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
/** Execute the algorithm.
 */
void PerformIndexOperations::exec() {
  MatrixWorkspace_sptr inputWorkspace = this->getProperty("InputWorkspace");
  const std::string processingInstructions =
      this->getProperty("ProcessingInstructions");

  boost::regex re(
      "^\\s*[0-9]+\\s*$|^(\\s*,*[0-9]+(\\s*(,|:|\\+|\\-)\\s*)*[0-9]*)*$");
  if (!boost::regex_match(processingInstructions, re)) {
    throw std::invalid_argument("ProcessingInstructions are not well formed: " +
                                processingInstructions);
  }

  if (processingInstructions.empty()) {
    auto cloneWS = this->createChildAlgorithm("CloneWorkspace");
    cloneWS->initialize();
    cloneWS->setProperty("InputWorkspace", inputWorkspace);
    cloneWS->execute();
    Workspace_sptr tmp = cloneWS->getProperty("OutputWorkspace");
    MatrixWorkspace_sptr outWS =
        boost::dynamic_pointer_cast<MatrixWorkspace>(tmp);
    this->setProperty("OutputWorkspace", outWS);
  } else {
    // Interpret the instructions.
    VecCommands commands = interpret(processingInstructions);

    // Execute the commands.
    auto command = commands[0];
    MatrixWorkspace_sptr outWS = command->execute(inputWorkspace);
    for (size_t j = 1; j < commands.size(); ++j) {
      outWS = commands[j]->executeAndAppend(inputWorkspace, outWS);
    }

    this->setProperty("OutputWorkspace", outWS);
  }
}
375

376
} // namespace Algorithms
377
} // namespace Mantid