BinMDTest.h 42.2 KB
Newer Older
1
2
3
#ifndef MANTID_MDEVENTS_BINTOMDHISTOWORKSPACETEST_H_
#define MANTID_MDEVENTS_BINTOMDHISTOWORKSPACETEST_H_

Janik Zikovsky's avatar
Janik Zikovsky committed
4
#include "MantidAPI/IMDEventWorkspace.h"
5
#include "MantidAPI/IMDHistoWorkspace.h"
6
7
#include "MantidAPI/FrameworkManager.h"
#include "MantidAPI/ImplicitFunctionBuilder.h"
Janik Zikovsky's avatar
Janik Zikovsky committed
8
#include "MantidAPI/ImplicitFunctionFactory.h"
9
#include "MantidAPI/ImplicitFunctionParser.h"
10
#include "MantidAPI/ImplicitFunctionParameterParserFactory.h"
11
12
#include "MantidGeometry/MDGeometry/MDImplicitFunction.h"
#include "MantidGeometry/MDGeometry/MDTypes.h"
13
#include "MantidGeometry/MDGeometry/QSample.h"
14
#include "MantidMDAlgorithms/BinMD.h"
15
#include "MantidMDAlgorithms/CreateMDWorkspace.h"
Alex Buts's avatar
Alex Buts committed
16
#include "MantidMDAlgorithms/FakeMDEventData.h"
17
#include "MantidTestHelpers/MDEventsTestHelper.h"
18

19
#include <boost/math/special_functions/fpclassify.hpp>
20

21
#include <cxxtest/TestSuite.h>
22

23
24
#include <gmock/gmock.h>
#include <gtest/gtest.h>
25
26

using namespace Mantid::API;
27
using namespace Mantid::DataObjects;
28
using namespace Mantid::Kernel;
29
using namespace Mantid::MDAlgorithms;
30
using Mantid::coord_t;
31

32
class BinMDTest : public CxxTest::TestSuite {
33
34

private:
35
36
  // Helper class. Mock Implicit function.
  class MockImplicitFunction : public Mantid::Geometry::MDImplicitFunction {
37
  public:
38
39
40
41
    using MDImplicitFunction::isPointContained; // Avoids Intel compiler
                                                // warning.
    virtual bool isPointContained(const Mantid::coord_t *) { return false; }
    virtual std::string getName() const { return "MockImplicitFunction"; }
42
    MOCK_CONST_METHOD0(toXMLString, std::string());
43
    ~MockImplicitFunction() { ; }
44
45
  };

46
47
48
  // Helper class. Builds mock implicit functions.
  class MockImplicitFunctionBuilder
      : public Mantid::API::ImplicitFunctionBuilder {
49
  public:
50
    Mantid::Geometry::MDImplicitFunction *create() const {
51
52
53
54
      return new MockImplicitFunction;
    }
  };

55
56
57
  // Helper class. Parses mock Implicit Functions.
  class MockImplicitFunctionParser
      : public Mantid::API::ImplicitFunctionParser {
58
  public:
59
60
61
    MockImplicitFunctionParser() : Mantid::API::ImplicitFunctionParser(NULL) {}
    Mantid::API::ImplicitFunctionBuilder *
    createFunctionBuilder(Poco::XML::Element * /*functionElement*/) {
62
63
      return new MockImplicitFunctionBuilder;
    }
64
65
66
67
    void
    setSuccessorParser(Mantid::API::ImplicitFunctionParser * /*successor*/) {}
    void setParameterParser(
        Mantid::API::ImplicitFunctionParameterParser * /*parser*/) {}
68
  };
69
  // helper ws creator
70
  Mantid::API::Workspace_sptr createSimple3DWorkspace() {
71
72
    using namespace Mantid::API;
    AnalysisDataService::Instance().remove("3D_Workspace");
73
74
75
76
    CreateMDWorkspace create;

    create.initialize();
    create.setProperty("Dimensions", 3);
77
78
79
80
    create.setPropertyValue("Extents", "0,10,0,10,0,10");
    create.setPropertyValue("Names", "x,y,z");
    create.setPropertyValue("Units", "m,m,m");
    create.setPropertyValue("SplitInto", "10");
81
82
    create.setPropertyValue("OutputWorkspace", "3D_Workspace");
    create.execute();
83
84
    return AnalysisDataService::Instance().retrieve("3D_Workspace");
  }
85

86
public:
87
  void testSetup() {
88
    using namespace Mantid::Kernel;
89
90
91
92
93
    Mantid::API::ImplicitFunctionFactory::Instance()
        .subscribe<testing::NiceMock<MockImplicitFunction>>(
            "MockImplicitFunction");
    Mantid::API::ImplicitFunctionParserFactory::Instance()
        .subscribe<MockImplicitFunctionParser>("MockImplicitFunctionParser");
94
  }
95

96
  void test_Init() {
97
    BinMD alg;
98
99
    TS_ASSERT_THROWS_NOTHING(alg.initialize())
    TS_ASSERT(alg.isInitialized())
100
  }
101
102
103
104
105
106

  /** Test the algo
  * @param nameX : name of the axis
  * @param expected_signal :: how many events in each resulting bin
  * @param expected_numBins :: how many points/bins in the output
  */
107
108
109
110
111
112
113
  void do_test_exec(std::string functionXML, std::string name1,
                    std::string name2, std::string name3, std::string name4,
                    double expected_signal, size_t expected_numBins,
                    bool IterateEvents = true, size_t numEventsPerBox = 1,
                    VMD expectBasisX = VMD(1, 0, 0),
                    VMD expectBasisY = VMD(0, 1, 0),
                    VMD expectBasisZ = VMD(0, 0, 1)) {
114
    BinMD alg;
115
116
    TS_ASSERT_THROWS_NOTHING(alg.initialize())
    TS_ASSERT(alg.isInitialized())
117

118
    Mantid::Geometry::QSample frame;
119
    IMDEventWorkspace_sptr in_ws =
120
121
        MDEventsTestHelper::makeAnyMDEWWithFrames<MDLeanEvent<3>, 3>(
            10, 0.0, 10.0, frame, numEventsPerBox);
122
123
    Mantid::Kernel::SpecialCoordinateSystem appliedCoord =
        Mantid::Kernel::QSample;
124

125
126
127
128
    auto eventNorm = Mantid::API::MDNormalization::VolumeNormalization;
    auto histoNorm = Mantid::API::MDNormalization::NumEventsNormalization;
    in_ws->setDisplayNormalization(eventNorm);
    in_ws->setDisplayNormalizationHisto(histoNorm);
129
    AnalysisDataService::Instance().addOrReplace("BinMDTest_ws", in_ws);
130

131
    // 1000 boxes with 1 event each
132
    TS_ASSERT_EQUALS(in_ws->getNPoints(), 1000 * numEventsPerBox);
133

134
135
    TS_ASSERT_THROWS_NOTHING(
        alg.setPropertyValue("InputWorkspace", "BinMDTest_ws"));
136
137
138
139
    TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("AlignedDim0", name1));
    TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("AlignedDim1", name2));
    TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("AlignedDim2", name3));
    TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("AlignedDim3", name4));
140
141
    TS_ASSERT_THROWS_NOTHING(
        alg.setPropertyValue("ImplicitFunctionXML", functionXML));
142
    TS_ASSERT_THROWS_NOTHING(alg.setProperty("IterateEvents", IterateEvents));
143
144
    TS_ASSERT_THROWS_NOTHING(
        alg.setPropertyValue("OutputWorkspace", "BinMDTest_ws"));
145

146
    TS_ASSERT_THROWS_NOTHING(alg.execute();)
147

148
    TS_ASSERT(alg.isExecuted());
149

150
151
152
153
    MDHistoWorkspace_sptr out;
    TS_ASSERT_THROWS_NOTHING(
        out = boost::dynamic_pointer_cast<MDHistoWorkspace>(
            AnalysisDataService::Instance().retrieve("BinMDTest_ws"));)
154
    TS_ASSERT(out);
155
156
    if (!out)
      return;
157

158
    TS_ASSERT_EQUALS(appliedCoord, out->getSpecialCoordinateSystem());
159
    // Took 6x6x6 bins in the middle of the box
160
    TS_ASSERT_EQUALS(out->getNPoints(), expected_numBins);
161
    // Every box has a single event summed into it, so 1.0 weight
162
163
    for (size_t i = 0; i < out->getNPoints(); i++) {
      if (functionXML == "") {
164
        // Nothing rejected
165
        TS_ASSERT_DELTA(out->getSignalAt(i), expected_signal, 1e-5);
166
        TS_ASSERT_DELTA(out->getNumEventsAt(i), expected_signal, 1e-5);
167
        TS_ASSERT_DELTA(out->getErrorAt(i), sqrt(expected_signal), 1e-5);
168
      } else {
169
        // All NAN cause of implicit function
170
171
172
173
174
        TS_ASSERT(boost::math::isnan(out->getSignalAt(i))); // The implicit
                                                            // function should
                                                            // have ensured that
                                                            // no bins were
                                                            // present.
175
      }
176
    }
177
    // check basis vectors
178
179
180
181
182
183
184
185
    TS_ASSERT_EQUALS(out->getBasisVector(0), expectBasisX);
    if (out->getNumDims() > 1) {
      TS_ASSERT_EQUALS(out->getBasisVector(1), expectBasisY);
    }
    if (out->getNumDims() > 2) {
      TS_ASSERT_EQUALS(out->getBasisVector(2), expectBasisZ);
    }
    CoordTransform const *ctFrom = out->getTransformFromOriginal();
186
    TS_ASSERT(ctFrom);
187
    // Experiment Infos were copied
188
189
190
191
    TS_ASSERT_EQUALS(out->getNumExperimentInfo(),
                     in_ws->getNumExperimentInfo());
    TSM_ASSERT_EQUALS("Should have num events normalization",
                      out->displayNormalization(), histoNorm);
192
    AnalysisDataService::Instance().remove("BinMDTest_ws");
193
194
  }

195
196
197
198
  void test_exec_3D() {
    do_test_exec("", "Axis0,2.0,8.0, 6", "Axis1,2.0,8.0, 6", "Axis2,2.0,8.0, 6",
                 "", 1.0 /*signal*/, 6 * 6 * 6 /*# of bins*/,
                 true /*IterateEvents*/);
199
200
  }

201
202
203
204
205
  void test_exec_3D_scrambled_order() {
    do_test_exec("", "Axis1,2.0,8.0, 6", "Axis0,2.0,8.0, 6", "Axis2,2.0,8.0, 6",
                 "", 1.0 /*signal*/, 6 * 6 * 6 /*# of bins*/,
                 true /*IterateEvents*/, 1, VMD(0, 1, 0), VMD(1, 0, 0),
                 VMD(0, 0, 1));
206
207
  }

208
209
210
211
  void test_exec_3D_unevenSizes() {
    do_test_exec("", "Axis0,2.0,8.0, 3", "Axis1,2.0,8.0, 6", "Axis2,2.0,8.0, 6",
                 "", 2.0 /*signal*/, 6 * 6 * 3 /*# of bins*/,
                 true /*IterateEvents*/);
212
213
  }

214
215
216
217
  void test_exec_2D() { // Integrate over the 3rd dimension
    do_test_exec("", "Axis0,2.0,8.0, 6", "Axis1,2.0,8.0, 6", "", "",
                 1.0 * 10.0 /*signal*/, 6 * 6 /*# of bins*/,
                 true /*IterateEvents*/);
218
219
  }

220
221
222
223
  void test_exec_2D_largeBins() {
    do_test_exec("", "Axis0,2.0,8.0, 3", "Axis1,2.0,8.0, 3", "", "",
                 4.0 * 10.0 /*signal*/, 3 * 3 /*# of bins*/,
                 true /*IterateEvents*/);
224
225
  }

226
227
228
229
  void test_exec_2D_scrambledAndUnevent() {
    do_test_exec("", "Axis0,2.0,8.0, 3", "Axis2,2.0,8.0, 6", "", "",
                 2.0 * 10.0 /*signal*/, 3 * 6 /*# of bins*/,
                 true /*IterateEvents*/, 1, VMD(1, 0, 0), VMD(0, 0, 1));
230
231
  }

232
233
234
  void test_exec_1D() {
    do_test_exec("", "Axis2,2.0,8.0, 6", "", "", "", 1.0 * 100.0 /*signal*/,
                 6 /*# of bins*/, true /*IterateEvents*/, 1, VMD(0, 0, 1));
235
236
  }

237
238
239
240
  void test_exec_1D_boxCompletelyContained() {
    do_test_exec("", "Axis2,2.0,8.0, 1", "", "", "",
                 20 * 6.0 * 100.0 /*signal*/, 1 /*# of bins*/,
                 true /*IterateEvents*/, 20 /*numEventsPerBox*/, VMD(0, 0, 1));
241
  }
Alex Buts's avatar
Alex Buts committed
242

243
244
245
246
247
  bool etta(int x, int base) {
    int ii = x - base / 2;
    if (ii < 0)
      return false;
    return !(ii % base);
Alex Buts's avatar
Alex Buts committed
248
249
  }

250
  void testExecLagreRegularSignal() {
251

252
    CreateMDWorkspace creator;
253

Alex Buts's avatar
Alex Buts committed
254
    FakeMDEventData FakeDat;
255
256
257
258
259
260
261
262
    TS_ASSERT_THROWS_NOTHING(FakeDat.initialize())
    TS_ASSERT(FakeDat.isInitialized())

    // MDEventWorkspace3Lean::sptr in_ws = MDEventsTestHelper::makeMDEW<3>(3,
    // 0.0, 10.0, 0);
    auto a_ws = createSimple3DWorkspace();
    MDEventWorkspace3Lean::sptr in_ws =
        boost::dynamic_pointer_cast<MDEventWorkspace3Lean>(a_ws);
263
    TS_ASSERT(in_ws);
264
265
    if (!in_ws)
      return;
Alex Buts's avatar
Alex Buts committed
266

267
268
    AnalysisDataService::Instance().addOrReplace("FakeMDEventDataTest_ws",
                                                 in_ws);
Alex Buts's avatar
Alex Buts committed
269

270
271
    TS_ASSERT_THROWS_NOTHING(
        FakeDat.setPropertyValue("InputWorkspace", "FakeMDEventDataTest_ws"));
Alex Buts's avatar
Alex Buts committed
272
    TS_ASSERT_THROWS_NOTHING(FakeDat.setPropertyValue("PeakParams", ""));
273
274
    TS_ASSERT_THROWS_NOTHING(FakeDat.setPropertyValue(
        "UniformParams", "-1000,0.50001,1,0.50001,1,0.50001,1"));
Alex Buts's avatar
Alex Buts committed
275

276
277
    TS_ASSERT_THROWS_NOTHING(FakeDat.execute();)
    TS_ASSERT(FakeDat.isExecuted());
Alex Buts's avatar
Alex Buts committed
278
279

    // Now there are at 1000 points.
280
281
282
    TS_ASSERT_EQUALS(in_ws->getNPoints(), 1000);
    TS_ASSERT_DELTA(in_ws->getBox()->getSignal(), 1000.0, 1.e-6);
    TS_ASSERT_DELTA(in_ws->getBox()->getErrorSquared(), 1000.0, 1.e-6);
Alex Buts's avatar
Alex Buts committed
283
284

    BinMD BinAlg;
285
286
    TS_ASSERT_THROWS_NOTHING(BinAlg.initialize())
    TS_ASSERT(BinAlg.isInitialized())
Alex Buts's avatar
Alex Buts committed
287

288
289
290
291
292
293
294
295
    TS_ASSERT_THROWS_NOTHING(
        BinAlg.setPropertyValue("InputWorkspace", "FakeMDEventDataTest_ws"));
    TS_ASSERT_THROWS_NOTHING(
        BinAlg.setPropertyValue("AlignedDim0", "x,0,10,40"));
    TS_ASSERT_THROWS_NOTHING(
        BinAlg.setPropertyValue("AlignedDim1", "y,0,10,5"));
    TS_ASSERT_THROWS_NOTHING(
        BinAlg.setPropertyValue("AlignedDim2", "z,0,10,20"));
Alex Buts's avatar
Alex Buts committed
296

297
298
    TS_ASSERT_THROWS_NOTHING(
        BinAlg.setPropertyValue("OutputWorkspace", "BinMDTest_ws"));
Alex Buts's avatar
Alex Buts committed
299

300
    TS_ASSERT_THROWS_NOTHING(BinAlg.execute();)
Alex Buts's avatar
Alex Buts committed
301

302
    TS_ASSERT(BinAlg.isExecuted());
Alex Buts's avatar
Alex Buts committed
303

304
305
306
307
308
309
310
311
    MDHistoWorkspace_sptr out;
    TS_ASSERT_THROWS_NOTHING(
        out = boost::dynamic_pointer_cast<MDHistoWorkspace>(
            AnalysisDataService::Instance().retrieve("BinMDTest_ws"));)
    TSM_ASSERT("can not retrieve binned workspace from analysis data service",
               out);
    if (!out)
      return;
Alex Buts's avatar
Alex Buts committed
312

313
    TS_ASSERT_EQUALS(out->getNEvents(), 1000);
Alex Buts's avatar
Alex Buts committed
314
315

    double expected_signal(2.);
316
    std::vector<size_t> nBins(3);
317
318
319
320
321
    nBins[0] = 40;
    nBins[1] = 5;
    nBins[2] = 20;

    for (size_t i = 0; i < out->getNPoints(); i++) {
322
      auto indexes = Utils::getIndicesFromLinearIndex(i, nBins);
323
      if (etta(int(indexes[0]), 4) && etta(int(indexes[2]), 2)) {
Alex Buts's avatar
Alex Buts committed
324
325
326
        TS_ASSERT_DELTA(out->getSignalAt(i), expected_signal, 1e-5);
        TS_ASSERT_DELTA(out->getNumEventsAt(i), expected_signal, 1e-5);
        TS_ASSERT_DELTA(out->getErrorAt(i), sqrt(expected_signal), 1e-5);
327
      } else {
Alex Buts's avatar
Alex Buts committed
328
329
330
331
        TS_ASSERT_DELTA(out->getSignalAt(i), 0, 1e-5);
        TS_ASSERT_DELTA(out->getNumEventsAt(i), 0, 1e-5);
        TS_ASSERT_DELTA(out->getErrorAt(i), 0, 1e-5);
      }
Alex Buts's avatar
Alex Buts committed
332
    }
333

Alex Buts's avatar
Alex Buts committed
334
335
336
337
    AnalysisDataService::Instance().remove("FakeMDEventDataTest_ws");
    AnalysisDataService::Instance().remove("BinMDTest_ws");
  }

338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
  void test_exec_with_impfunction() {
    // This describes the local implicit function that will always reject bins.
    // so output workspace should have zero.
    std::string functionXML =
        std::string("<Function>") + "<Type>MockImplicitFunction</Type>" +
        "<ParameterList>" + "</ParameterList>" + "</Function>";
    do_test_exec(functionXML, "Axis0,2.0,8.0, 6", "Axis1,2.0,8.0, 6",
                 "Axis2,2.0,8.0, 6", "", 1.0 /*signal*/,
                 6 * 6 * 6 /*# of bins*/, false /*IterateEvents*/);
  }
  void test_exec_with_impfunction_IterateEvents() { // This describes the local
                                                    // implicit function that
                                                    // will always reject bins.
                                                    // so output workspace
                                                    // should have zero.
    std::string functionXML =
        std::string("<Function>") + "<Type>MockImplicitFunction</Type>" +
        "<ParameterList>" + "</ParameterList>" + "</Function>";
    do_test_exec(functionXML, "Axis0,2.0,8.0, 6", "Axis1,2.0,8.0, 6",
                 "Axis2,2.0,8.0, 6", "", 1.0 /*signal*/,
                 6 * 6 * 6 /*# of bins*/, true /*IterateEvents*/);
359
  }
360
361
362
363
364
365

  /** Test the algorithm, with a coordinate transformation.
   *
  * @param binsX : # of bins in the output
  * @param expected_signal :: how many events in each resulting bin
  * @param expected_numBins :: how many points/bins in the output
366
  * @param FlipYBasis :: flip the Y basis vector
367
368
  */
  void do_test_transform(int binsX, int binsY, int binsZ,
369
370
371
                         double expected_signal, size_t expected_numBins,
                         bool IterateEvents, bool ForceOrthogonal,
                         bool FlipYBasis = false) {
372
    BinMD alg;
373
374
    TS_ASSERT_THROWS_NOTHING(alg.initialize())
    TS_ASSERT(alg.isInitialized())
375

376
377
378
379
    // Make a workspace with events along a regular grid that is rotated and
    // offset along x,y
    MDEventWorkspace3Lean::sptr in_ws =
        MDEventsTestHelper::makeMDEW<3>(10, -10.0, 20.0, 0);
380
381
    in_ws->splitBox();
    double theta = 0.1;
382
    VMD origin(-2.0, -3.0, -4.0);
383
384
385
386
387
    for (coord_t ox = 0.5; ox < 10; ox++)
      for (coord_t oy = 0.5; oy < 10; oy++)
        for (coord_t oz = 0.5; oz < 10; oz++) {
          double x = ox * cos(theta) - oy * sin(theta) + origin[0];
          double y = oy * cos(theta) + ox * sin(theta) + origin[1];
388
          double z = oz + origin[2];
389
          double center[3] = {x, y, z};
390
          MDLeanEvent<3> ev(1.0, 1.0, center);
391
          //          std::cout << x << "," << y << "," << z << std::endl;
392
393
394
395
396
          in_ws->addEvent(ev);
        }
    in_ws->refreshCache();

    // Build the transformation (from eventWS to binned workspace)
397
    CoordTransformAffine ct(3, 3);
398
399
400

    // Build the basis vectors, a 0.1 rad rotation along +Z
    double angle = 0.1;
401
402
    VMD baseX(cos(angle), sin(angle), 0.0);
    VMD baseY(-sin(angle), cos(angle), 0.0);
403
    if (FlipYBasis) {
404
405
406
407
      baseY = baseY * -1.;
      // Adjust origin to be at the upper left corner of the square
      origin = origin + VMD(-sin(angle), cos(angle), 0) * 10.0;
    }
408
    VMD baseZ(0.0, 0.0, 1.0);
409
    // Make a bad (i.e. non-orthogonal) input, to get it fixed.
410
    if (ForceOrthogonal) {
411
412
413
      baseY = VMD(0.0, 1.0, 0);
      baseZ = VMD(0.5, 0.5, 0.5);
    }
414

415
    AnalysisDataService::Instance().addOrReplace("BinMDTest_ws", in_ws);
416
    if (false) {
417
      // Save to NXS file for testing
418
419
420
      FrameworkManager::Instance().exec("SaveMD", 4, "InputWorkspace",
                                        "BinMDTest_ws", "Filename",
                                        "BinMDTest_ws_rotated.nxs");
421
    }
422
423

    // 1000 boxes with 1 event each
424
    TS_ASSERT_EQUALS(in_ws->getNPoints(), 1000);
425

426
427
    TS_ASSERT_THROWS_NOTHING(
        alg.setPropertyValue("InputWorkspace", "BinMDTest_ws"));
428
    TS_ASSERT_THROWS_NOTHING(alg.setProperty("AxisAligned", false));
429
430
431
432
433
434
    TS_ASSERT_THROWS_NOTHING(
        alg.setPropertyValue("BasisVector0", "OutX,m," + baseX.toString(",")));
    TS_ASSERT_THROWS_NOTHING(
        alg.setPropertyValue("BasisVector1", "OutY,m," + baseY.toString(",")));
    TS_ASSERT_THROWS_NOTHING(
        alg.setPropertyValue("BasisVector2", "OutZ,m," + baseZ.toString(",")));
435
    TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("BasisVector3", ""));
436
437
438
439
440
    TS_ASSERT_THROWS_NOTHING(
        alg.setPropertyValue("Translation", origin.toString(",")));
    TS_ASSERT_THROWS_NOTHING(
        alg.setProperty("ForceOrthogonal", ForceOrthogonal));
    TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("ImplicitFunctionXML", ""));
441
    TS_ASSERT_THROWS_NOTHING(alg.setProperty("IterateEvents", IterateEvents));
442

443
    std::vector<int> OutputBins{binsX, binsY, binsZ};
444
    TS_ASSERT_THROWS_NOTHING(alg.setProperty("OutputBins", OutputBins));
445
446
    TS_ASSERT_THROWS_NOTHING(
        alg.setProperty("OutputExtents", "0,10, 0,10, 0,10"));
447

448
449
    TS_ASSERT_THROWS_NOTHING(
        alg.setPropertyValue("OutputWorkspace", "BinMDTest_ws"));
450

451
    TS_ASSERT_THROWS_NOTHING(alg.execute();)
452

453
    TS_ASSERT(alg.isExecuted());
454

455
456
457
458
    MDHistoWorkspace_sptr out;
    TS_ASSERT_THROWS_NOTHING(
        out = boost::dynamic_pointer_cast<MDHistoWorkspace>(
            AnalysisDataService::Instance().retrieve("BinMDTest_ws"));)
459
    TS_ASSERT(out);
460
461
    if (!out)
      return;
462
463
464
465

    // Took 6x6x6 bins in the middle of the box
    TS_ASSERT_EQUALS(out->getNPoints(), expected_numBins);
    // Every box has a single event summed into it, so 1.0 weight
466
    for (size_t i = 0; i < out->getNPoints(); i++) {
467
468
      // Nothing rejected
      TS_ASSERT_DELTA(out->getSignalAt(i), expected_signal, 1e-5);
469
      TS_ASSERT_DELTA(out->getErrorAt(i), std::sqrt(expected_signal), 1e-5);
470
    }
471
472

    // check basis vectors
473
474
475
476
477
    TS_ASSERT_EQUALS(out->getBasisVector(0), baseX);
    if (!ForceOrthogonal) {
      TS_ASSERT_EQUALS(out->getBasisVector(1), baseY);
      TS_ASSERT_EQUALS(out->getBasisVector(2), baseZ);
    }
478

479
    CoordTransform const *ctFrom = out->getTransformFromOriginal();
480
    TS_ASSERT(ctFrom);
481
    CoordTransform const *ctTo = out->getTransformToOriginal();
482
    TS_ASSERT(ctTo);
483
484
    if (!ctTo)
      return;
485
486
487

    // Round-trip transform
    coord_t originalPoint[3] = {1.0, 2.0, 3.0};
488
489
    coord_t *transformedPoint = new coord_t[3];
    coord_t *originalBack = new coord_t[3];
490
491
    ctFrom->apply(originalPoint, transformedPoint);
    ctTo->apply(transformedPoint, originalBack);
492
493
494
    for (size_t d = 0; d < 3; d++) {
      TS_ASSERT_DELTA(originalPoint[d], originalBack[d], 1e-5);
    }
495

496
    AnalysisDataService::Instance().remove("BinMDTest_ws");
497
498
  }

499
500
501
502
  void test_exec_with_transform() {
    do_test_transform(10, 10, 10, 1.0 /*signal*/, 1000 /*# of bins*/,
                      true /*IterateEvents*/,
                      false /* Dont force orthogonal */);
503
504
  }

505
506
507
508
  void test_exec_with_transform_unevenSizes() {
    do_test_transform(5, 10, 2, 10 * 1.0 /*signal*/, 100 /*# of bins*/,
                      true /*IterateEvents*/,
                      false /* Dont force orthogonal */);
509
510
  }

511
512
513
  void test_exec_with_transform_ForceOrthogonal() {
    do_test_transform(5, 10, 2, 10 * 1.0 /*signal*/, 100 /*# of bins*/,
                      true /*IterateEvents*/, true /* Do force orthogonal */);
514
515
  }

516
  /** Change the handedness of the basis vectors by flipping the Y vector */
517
518
519
520
  void test_exec_with_transform_flipping_Y_basis() {
    do_test_transform(10, 10, 10, 1.0 /*signal*/, 1000 /*# of bins*/,
                      true /*IterateEvents*/, false /* Dont force orthogonal */,
                      true /* Flip sign of Y basis vector*/);
521
522
  }

523
524
525
526
527
528
  //---------------------------------------------------------------------------------------------
  /** Check that two MDHistos have the same values .
   *
   * @param binned1Name :: original, binned direct from MDEW
   * @param binned2Name :: binned from a MDHisto
   * @param origWS :: both should have this as its originalWorkspace
529
   * @return binned2 shared pointer
530
   */
531
532
533
534
535
536
537
538
539
540
541
  MDHistoWorkspace_sptr do_compare_histo(std::string binned1Name,
                                         std::string binned2Name,
                                         std::string origWS) {
    MDHistoWorkspace_sptr binned1 =
        AnalysisDataService::Instance().retrieveWS<MDHistoWorkspace>(
            binned1Name);
    MDHistoWorkspace_sptr binned2 =
        AnalysisDataService::Instance().retrieveWS<MDHistoWorkspace>(
            binned2Name);
    TS_ASSERT_EQUALS(binned1->getOriginalWorkspace()->getName(), origWS);
    TS_ASSERT_EQUALS(binned2->getOriginalWorkspace()->getName(), origWS);
542
543
    TS_ASSERT(binned2);
    size_t numErrors = 0;
544
    for (size_t i = 0; i < binned1->getNPoints(); i++) {
545
      double diff = std::abs(binned1->getSignalAt(i) - binned2->getSignalAt(i));
546
547
548
      if (diff > 1e-6)
        numErrors++;
      TS_ASSERT_DELTA(binned1->getSignalAt(i), binned2->getSignalAt(i), 1e-5);
549
    }
550
    TS_ASSERT_EQUALS(numErrors, 0);
551
    return binned2;
552
553
554
  }

  /** Common setup for double-binning tests */
555
  void do_prepare_comparison() {
556
557
558
559
560
    AnalysisDataService::Instance().remove("mdew");
    AnalysisDataService::Instance().remove("binned0");
    AnalysisDataService::Instance().remove("binned1");
    AnalysisDataService::Instance().remove("binned2");

561
    // ---- Start with empty MDEW ----
562
563
564
565
    FrameworkManager::Instance().exec(
        "CreateMDWorkspace", 16, "Dimensions", "2", "Extents", "-10,10,-10,10",
        "Names", "x,y", "Units", "m,m", "SplitInto", "4", "SplitThreshold",
        "100", "MaxRecursionDepth", "20", "OutputWorkspace", "mdew");
566

567
    // Give fake uniform data
568
569
570
    FrameworkManager::Instance().exec("FakeMDEventData", 6, "InputWorkspace",
                                      "mdew", "UniformParams", "1000",
                                      "RandomSeed", "1234");
571
  }
572

573
574
  //---------------------------------------------------------------------------------------------
  /** Bin a MDHistoWorkspace that was itself binned from a MDEW, axis-aligned */
575
  void test_exec_Aligned_then_nonAligned() {
576
577
    do_prepare_comparison();
    // Bin aligned to original. Coordinates remain the same
578
579
580
581
    FrameworkManager::Instance().exec(
        "BinMD", 10, "InputWorkspace", "mdew", "OutputWorkspace", "binned0",
        "AxisAligned", "1", "AlignedDim0", "x, -10, 10, 10", "AlignedDim1",
        "y, -10, 10, 10");
582
583

    // Bin, non-axis-aligned, with translation
584
585
586
587
588
    FrameworkManager::Instance().exec(
        "BinMD", 18, "InputWorkspace", "binned0", "OutputWorkspace", "binned1",
        "AxisAligned", "0", "BasisVector0", "rx,m, 1.0,0.0", "BasisVector1",
        "ry,m, 0.0,1.0", "ForceOrthogonal", "1", "Translation", "-10, -10",
        "OutputExtents", "0,20, 0,20", "OutputBins", "10,10");
589

590
591
    MDHistoWorkspace_sptr binned1 =
        do_compare_histo("binned0", "binned1", "mdew");
592
593

    // Intermediate workspace (the MDHisto)
594
595
    TS_ASSERT_EQUALS(binned1->numOriginalWorkspaces(), 2);
    TS_ASSERT_EQUALS(binned1->getOriginalWorkspace(1)->name(), "binned0");
596
    // Transforms to/from the INTERMEDIATE workspace exist
597
598
599
600
601
    CoordTransform const *toIntermediate = binned1->getTransformToOriginal(1);
    CoordTransform const *fromIntermediate =
        binned1->getTransformFromOriginal(1);
    TS_ASSERT(toIntermediate);
    TS_ASSERT(fromIntermediate);
602
603
604
605

    // Transform from the BINNED to the INTERMEDIATE and check.
    VMD binnedPos(0.1, 0.2);
    VMD intermediatePos = toIntermediate->applyVMD(binnedPos);
606
607
    TS_ASSERT_DELTA(intermediatePos[0], -9.9, 1e-5);
    TS_ASSERT_DELTA(intermediatePos[1], -9.8, 1e-5);
608
609
610
  }

  //---------------------------------------------------------------------------------------------
611
612
613
  /** Bin a MDHistoWorkspace that was itself binned from a MDEW, axis-aligned,
   * but swapping axes around */
  void test_exec_AlignedSwappingAxes_then_nonAligned() {
614
615
    do_prepare_comparison();
    // Bin aligned to original.
616
617
618
619
    FrameworkManager::Instance().exec(
        "BinMD", 10, "InputWorkspace", "mdew", "OutputWorkspace", "binned0",
        "AxisAligned", "1", "AlignedDim0", "y, -10, 10, 10", "AlignedDim1",
        "x, -10, 10, 10");
620
621
622
623

    // binned0.x is mdew.y
    // binned0.y is mdew.x
    // Bin, non-axis-aligned, with translation
624
625
626
627
628
    FrameworkManager::Instance().exec(
        "BinMD", 18, "InputWorkspace", "binned0", "OutputWorkspace", "binned1",
        "AxisAligned", "0", "BasisVector0", "rx,m, 1.0,0.0", "BasisVector1",
        "ry,m, 0.0,1.0", "ForceOrthogonal", "1", "Translation", "-10, -5",
        "OutputExtents", "0,20, 0,20", "OutputBins", "10,10");
629
630

    // Get the final binned workspace
631
632
    MDHistoWorkspace_sptr binned1 =
        AnalysisDataService::Instance().retrieveWS<MDHistoWorkspace>("binned1");
633
634

    // Intermediate workspace (the MDHisto) is binned0
635
636
    TS_ASSERT_EQUALS(binned1->numOriginalWorkspaces(), 2);
    TS_ASSERT_EQUALS(binned1->getOriginalWorkspace(1)->name(), "binned0");
637
    // Transforms to/from the INTERMEDIATE workspace exist
638
639
640
641
642
    CoordTransform const *toIntermediate = binned1->getTransformToOriginal(1);
    CoordTransform const *fromIntermediate =
        binned1->getTransformFromOriginal(1);
    TS_ASSERT(toIntermediate);
    TS_ASSERT(fromIntermediate);
643
644

    // Transforms to/from the REALLY ORIGINAL workspace exist
645
646
647
648
    CoordTransform const *toOriginal = binned1->getTransformToOriginal(0);
    CoordTransform const *fromOriginal = binned1->getTransformFromOriginal(0);
    TS_ASSERT(toOriginal);
    TS_ASSERT(fromOriginal);
649
650
651
652
653
654
655
656

    // Transform from the BINNED coordinates.
    // in binned1 : (0.1,   0.2)
    // in binned0 : (-9.9, -4.8)
    // in mdew :    (-4.8, -9.9)
    VMD binned1Pos(0.1, 0.2);
    VMD intermediatePos = toIntermediate->applyVMD(binned1Pos);
    VMD originalPos = toOriginal->applyVMD(binned1Pos);
657
658
659
660
    TS_ASSERT_DELTA(intermediatePos[0], -9.9, 1e-5);
    TS_ASSERT_DELTA(intermediatePos[1], -4.8, 1e-5);
    TS_ASSERT_DELTA(originalPos[0], -4.8, 1e-5);
    TS_ASSERT_DELTA(originalPos[1], -9.9, 1e-5);
661
662

    // Now check the reverse transforms
663
664
665
    VMD originalToBinned = fromOriginal->applyVMD(VMD(-4.8, -9.9));
    TS_ASSERT_DELTA(originalToBinned[0], 0.1, 1e-5);
    TS_ASSERT_DELTA(originalToBinned[1], 0.2, 1e-5);
666

667
668
669
    VMD intermediateToBinned = fromIntermediate->applyVMD(VMD(-9.9, -4.8));
    TS_ASSERT_DELTA(intermediateToBinned[0], 0.1, 1e-5);
    TS_ASSERT_DELTA(intermediateToBinned[1], 0.2, 1e-5);
670
671
  }

672
  //---------------------------------------------------------------------------------------------
673
674
675
  /** Bin a MDHistoWorkspace that was itself binned from a MDEW, axis-aligned,
   * but swapping axes around */
  void test_exec_AlignedSwappingAxes_then_nonAligned_3D() {
676
677
    AnalysisDataService::Instance().remove("mdew3d");

678
679
680
681
    FrameworkManager::Instance().exec(
        "CreateMDWorkspace", 16, "Dimensions", "3", "Extents",
        "-10,10,-10,10,-10,10", "Names", "A,B,C", "Units", "m,m,m", "SplitInto",
        "4", "SplitThreshold", "100", "MaxRecursionDepth", "20",
682
683
        "OutputWorkspace", "mdew3d");

684
685
686
687
688
689
690
691
692
693
694
    FrameworkManager::Instance().exec(
        "BinMD", 12, "InputWorkspace", "mdew3d", "OutputWorkspace", "binned0",
        "AxisAligned", "1", "AlignedDim0", "B, -10, 10, 10", "AlignedDim1",
        "C, -10, 10, 10", "AlignedDim2", "A, -10, 10, 10");

    FrameworkManager::Instance().exec(
        "BinMD", 20, "InputWorkspace", "binned0", "OutputWorkspace", "binned1",
        "AxisAligned", "0", "BasisVector0", "rx,m, 1.0,0.0,0.0", "BasisVector1",
        "ry,m, 0.0,1.0,0.0", "BasisVector2", "rz,m, 0.0,0.0,1.0",
        "ForceOrthogonal", "1", "Translation", "-10, -5, -3", "OutputExtents",
        "0,20, 0,20, 0,20", "OutputBins", "10,10,10");
695
696

    // Get the final binned workspace
697
698
    MDHistoWorkspace_sptr binned1 =
        AnalysisDataService::Instance().retrieveWS<MDHistoWorkspace>("binned1");
699
700

    // Intermediate workspace (the MDHisto) is binned0
701
702
    TS_ASSERT_EQUALS(binned1->numOriginalWorkspaces(), 2);
    TS_ASSERT_EQUALS(binned1->getOriginalWorkspace(1)->name(), "binned0");
703
    // Transforms to/from the INTERMEDIATE workspace exist
704
705
706
707
708
    CoordTransform const *toIntermediate = binned1->getTransformToOriginal(1);
    CoordTransform const *fromIntermediate =
        binned1->getTransformFromOriginal(1);
    TS_ASSERT(toIntermediate);
    TS_ASSERT(fromIntermediate);
709
710

    // Transforms to/from the REALLY ORIGINAL workspace exist
711
712
713
714
    CoordTransform const *toOriginal = binned1->getTransformToOriginal(0);
    CoordTransform const *fromOriginal = binned1->getTransformFromOriginal(0);
    TS_ASSERT(toOriginal);
    TS_ASSERT(fromOriginal);
715
716
717
718
719
720
721
722

    // Transform from the BINNED coordinates.
    // in binned1 : (0.1,   0.2, 0.3)
    // in binned0 : (-9.9, -4.8, -2.7)
    // in mdew3d :  (-2.7, -9.9, -4.8)
    VMD binned1Pos(0.1, 0.2, 0.3);
    VMD intermediatePos = toIntermediate->applyVMD(binned1Pos);
    VMD originalPos = toOriginal->applyVMD(binned1Pos);
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
    TS_ASSERT_DELTA(intermediatePos[0], -9.9, 1e-5);
    TS_ASSERT_DELTA(intermediatePos[1], -4.8, 1e-5);
    TS_ASSERT_DELTA(intermediatePos[2], -2.7, 1e-5);
    TS_ASSERT_DELTA(originalPos[0], -2.7, 1e-5);
    TS_ASSERT_DELTA(originalPos[1], -9.9, 1e-5);
    TS_ASSERT_DELTA(originalPos[2], -4.8, 1e-5);

    //
    //    // Now check the reverse transforms
    //    VMD originalToBinned = fromOriginal->applyVMD( VMD(-4.8, -9.9) );
    //    TS_ASSERT_DELTA( originalToBinned[0], 0.1, 1e-5);
    //    TS_ASSERT_DELTA( originalToBinned[1], 0.2, 1e-5);
    //
    //    VMD intermediateToBinned = fromIntermediate->applyVMD( VMD(-9.9, -4.8)
    //    );
    //    TS_ASSERT_DELTA( intermediateToBinned[0], 0.1, 1e-5);
    //    TS_ASSERT_DELTA( intermediateToBinned[1], 0.2, 1e-5);
740
741
  }

742
  //---------------------------------------------------------------------------------------------
743
744
745
  /** Bin a MDHistoWorkspace that was itself binned from a MDEW, not
   * axis-aligned */
  void test_exec_nonAligned_then_nonAligned_rotation() {
746
747
748
    do_prepare_comparison();

    // Bin NOT aligned to original, with translation
749
750
751
752
753
    FrameworkManager::Instance().exec(
        "BinMD", 18, "InputWorkspace", "mdew", "OutputWorkspace", "binned0",
        "AxisAligned", "0", "BasisVector0", "rx,m, 1.0, 0.0", "BasisVector1",
        "ry,m, 0.0, 1.0", "ForceOrthogonal", "1", "Translation", "-10, -10",
        "OutputExtents", "0,20, 0,20", "OutputBins", "10,10");
754
755

    // Bin with some rotation (10 degrees)
756
757
758
759
760
    FrameworkManager::Instance().exec(
        "BinMD", 18, "InputWorkspace", "mdew", "OutputWorkspace", "binned1",
        "AxisAligned", "0", "BasisVector0", "rx,m, 0.98, 0.17", "BasisVector1",
        "ry,m, -.17, 0.98", "ForceOrthogonal", "1", "Translation", "-10, -10",
        "OutputExtents", "0,20, 0,20", "OutputBins", "10,10");
761
    // Bin the binned output with the opposite rotation
762
763
764
765
766
    FrameworkManager::Instance().exec(
        "BinMD", 18, "InputWorkspace", "binned1", "OutputWorkspace", "binned2",
        "AxisAligned", "0", "BasisVector0", "rrx,m, 0.98, -.17", "BasisVector1",
        "rry,m, 0.17, 0.98", "ForceOrthogonal", "1", "Translation", "0, 0",
        "OutputExtents", "0,20, 0,20", "OutputBins", "10,10");
767
    // Check they are the same
768
769
    MDHistoWorkspace_sptr binned2 =
        do_compare_histo("binned0", "binned2", "mdew");
770
771

    // Intermediate workspace (the MDHisto)
772
773
    TS_ASSERT_EQUALS(binned2->numOriginalWorkspaces(), 2);
    TS_ASSERT_EQUALS(binned2->getOriginalWorkspace(1)->name(), "binned1");
774
    // Transforms to/from the INTERMEDIATE workspace exist
775
776
    TS_ASSERT(binned2->getTransformToOriginal(1));
    TS_ASSERT(binned2->getTransformFromOriginal(1));
777
778
  }

779
  //---------------------------------------------------------------------------------------------
780
781
782
  /** Bin a MDHistoWorkspace that was itself binned from a MDEW, not
   * axis-aligned, with translation */
  void test_exec_nonAligned_then_nonAligned_translation() {
783
    do_prepare_comparison();
784
785

    // Bin aligned to original
786
787
788
789
790
    FrameworkManager::Instance().exec(
        "BinMD", 18, "InputWorkspace", "mdew", "OutputWorkspace", "binned0",
        "AxisAligned", "0", "BasisVector0", "rx,m, 1.0, 0.0", "BasisVector1",
        "ry,m, 0.0, 1.0", "ForceOrthogonal", "1", "Translation", "-10, -10",
        "OutputExtents", "0,20, 0,20", "OutputBins", "10,10");
791
792

    // Bin with a translation. -10,-10 in MDEW becomes 0,0 in binned1
793
794
795
796
797
    FrameworkManager::Instance().exec(
        "BinMD", 18, "InputWorkspace", "mdew", "OutputWorkspace", "binned1",
        "AxisAligned", "0", "BasisVector0", "rx,m, 1.0, 0.0", "BasisVector1",
        "ry,m, 0.0, 1.0", "ForceOrthogonal", "1", "Translation", "-10, -10",
        "OutputExtents", "0,20, 0,20", "OutputBins", "10,10");
798
799

    // Bin the binned output with the opposite translation
800
801
802
803
804
    FrameworkManager::Instance().exec(
        "BinMD", 18, "InputWorkspace", "binned1", "OutputWorkspace", "binned2",
        "AxisAligned", "0", "BasisVector0", "rrx,m, 1.0, 0.0", "BasisVector1",
        "rry,m, 0.0, 1.0", "ForceOrthogonal", "1", "Translation", "0, 0",
        "OutputExtents", "0,20, 0,20", "OutputBins", "10,10");
805

806
807
808
809
810
    // Check they are the same
    do_compare_histo("binned0", "binned2", "mdew");
  }

  //---------------------------------------------------------------------------------------------
811
812
813
  /** Can't do Axis-Aligned on a MDHisto because the transformation gets too
   * annoying. */
  void test_exec_Aligned_onMDHisto_fails() {
814
815
816
    do_prepare_comparison();

    // Bin NOT aligned to original, translated. Coordinates change.
817
818
819
820
821
    FrameworkManager::Instance().exec(
        "BinMD", 18, "InputWorkspace", "mdew", "OutputWorkspace", "binned0",
        "AxisAligned", "0", "BasisVector0", "rx,m, 1.0, 0.0", "BasisVector1",
        "ry,m, 0.0, 1.0", "ForceOrthogonal", "1", "Translation", "-10, -10",
        "OutputExtents", "0,20, 0,20", "OutputBins", "10,10");
822
823

    // Bin aligned to binned0. This is not allowed!
824
825
826
827
828
    IAlgorithm_sptr alg = FrameworkManager::Instance().exec(
        "BinMD", 10, "InputWorkspace", "binned0", "OutputWorkspace", "binned1",
        "AxisAligned", "1", "AlignedDim0", "rx, 0, 20, 10", "AlignedDim1",
        "ry, 0, 20, 10");
    TS_ASSERT(!alg->isExecuted());
829
830
  }

831
832
833
834
835
  //---------------------------------------------------------------------------------------------
  /** A = a MDEventWorkspace
   *  B = binned from A with translation and scaling
   *  C = binned from B with translation and scaling
   *  */
836
  void test_exec_nonAligned_then_nonAligned_translation_scaling() {
837
838
839
    do_prepare_comparison();

    // Make the reference bin, which is all space (-10 to 10) with 10 bins
840
841
842
843
844
845
    FrameworkManager::Instance().exec(
        "BinMD", 20, "InputWorkspace", "mdew", "OutputWorkspace", "reference",
        "AxisAligned", "0", "BasisVector0", "tx,m, 1.0, 0.0", "BasisVector1",
        "ty,m, 0.0, 1.0", "NormalizeBasisVectors", "0", "ForceOrthogonal", "0",
        "Translation", "-10, -10", "OutputExtents", "0,20, 0,20", "OutputBins",
        "10,10");
846
847

    // Bin to workspace B. Have translation and scaling
848
849
850
851
852
853
    FrameworkManager::Instance().exec(
        "BinMD", 20, "InputWorkspace", "mdew", "OutputWorkspace", "B",
        "AxisAligned", "0", "BasisVector0", "tx, m, 2.0, 0.0", "BasisVector1",
        "ty, m, 0.0, 2.0", "NormalizeBasisVectors", "0", "ForceOrthogonal", "0",
        "Translation", "-2, -2", "OutputExtents",
        "-4,6, -4,6", /* The extents are in the scaled OUTPUT dimensions */
854
855
856
857
858
859
860
        "OutputBins", "10,10");

    // Check that B turns out to be the same as "Reference"
    do_compare_histo("reference", "B", "mdew");

    // Bin the binned output with more translation and scaling,
    // but it still ends up binning A from (-10 to 10) with 10 bins.
861
862
863
864
865
866
867
868
869
870
    FrameworkManager::Instance().exec(
        "BinMD", 20, "InputWorkspace", "B", "OutputWorkspace", "C",
        "AxisAligned", "0", "BasisVector0",
        "ttx,m, 2.0, 0.0", /* size 2 in B = size 4 in A */
        "BasisVector1", "tty,m, 0.0, 2.0", "NormalizeBasisVectors", "0",
        "ForceOrthogonal", "0", "Translation",
        "-1, -1", /* coords in B = (-4,-4) in A */
        "OutputExtents",
        "-1.5, 3.5, -1.5, 3.5", /* size of 5 in C = size of 10 in B = size
                                   of 20 in A */
871
872
873
874
875
        "OutputBins", "10,10");

    // Finally, C maps back onto A (mdew) binned as reference
    do_compare_histo("reference", "C", "mdew");

876
877
    IMDWorkspace_sptr C =
        AnalysisDataService::Instance().retrieveWS<IMDWorkspace>("C");
878
879
880
881
    TS_ASSERT(C);

    VMD out;
    // Check the mapping of coordinates from C to B
882
    CoordTransform const *transf_C_to_B = C->getTransformToOriginal(1);
883
    out = transf_C_to_B->applyVMD(VMD(-1.5, -1.5));
884
    TS_ASSERT_EQUALS(out, VMD(-4, -4));
885
886

    // And this is the mapping to the A workspace
887
    CoordTransform const *transf_C_to_A = C->getTransformToOriginal(0);
888
    out = transf_C_to_A->applyVMD(VMD(-1.5, -1.5));
889
    TS_ASSERT_EQUALS(out, VMD(-10, -10));
890
891
  }

892
893
894
  //---------------------------------------------------------------------------------------------
  /** Modify a MDHistoWorkspace with a binary operation.
   *  */
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
  void test_FailsIfYouModify_a_MDHistoWorkspace() {
    FrameworkManager::Instance().exec(
        "BinMD", 18, "InputWorkspace", "mdew", "OutputWorkspace", "binned0",
        "AxisAligned", "0", "BasisVector0", "rx,m, 1.0, 0.0", "BasisVector1",
        "ry,m, 0.0, 1.0", "ForceOrthogonal", "1", "Translation", "-10, -10",
        "OutputExtents", "0,20, 0,20", "OutputBins", "10,10");

    FrameworkManager::Instance().exec("PlusMD", 6, "LHSWorkspace", "binned0",
                                      "RHSWorkspace", "binned0",
                                      "OutputWorkspace", "binned0");

    IAlgorithm_sptr alg = FrameworkManager::Instance().exec(
        "BinMD", 18, "InputWorkspace", "binned0", "OutputWorkspace", "binned1",
        "AxisAligned", "0", "BasisVector0", "rx,m, 1.0, 0.0", "BasisVector1",
        "ry,m, 0.0, 1.0", "ForceOrthogonal", "1", "Translation", "-10, -10",
        "OutputExtents", "0,20, 0,20", "OutputBins", "10,10");
    TSM_ASSERT("Algorithm threw an error, as expected", !alg->isExecuted())
  }

  void test_throws_if_InputWorkspace_pure_IMDHistWorkspace() {
    BinMD alg;
    alg.setChild(true);
    alg.setRethrows(true);
    alg.initialize();
    // Histoworkspace with no original workspace or transforms
    IMDHistoWorkspace_sptr inWS = MDEventsTestHelper::makeFakeMDHistoWorkspace(
        1 /*signal*/, 2 /*numDims*/, 10 /*numBins*/);

    alg.setProperty("InputWorkspace", inWS); // Input workspace - Pure histogram
    alg.setProperty("AlignedDim0",
                    "x,0,10,10"); // Values not relevant to this test
    alg.setProperty("AlignedDim1",
                    "y,0,10,10"); // Values not relevant to this test
    alg.setPropertyValue("OutputWorkspace", "dummy");
    TSM_ASSERT_THROWS(
        "Cannot allow BinMD on a pure MDHistoWorkspace. Should throw.",
        alg.execute(), std::runtime_error &);
  }

  void test_normalization() {

    FrameworkManager::Instance().exec(
        "CreateMDWorkspace", 16, "Dimensions", "2", "Extents", "-10,10,-10,10",
        "Names", "x,y", "Units", "m,m", "SplitInto", "4", "SplitThreshold",
        "100", "MaxRecursionDepth", "20", "OutputWorkspace", "mdew");

    FrameworkManager::Instance().exec(
        "BinMD", 20, "InputWorkspace", "mdew", "OutputWorkspace", "binned",
        "AxisAligned", "0", "BasisVector0", "tx, m, 2.0, 0.0", "BasisVector1",
        "ty, m, 0.0, 2.0", "NormalizeBasisVectors", "1", "ForceOrthogonal", "0",
        "Translation", "-2, -2", "OutputExtents",
        "-4,6, -4,6", /* The extents are in the scaled OUTPUT dimensions */
947
        "OutputBins", "10,10");
948

949
950
951
952
    auto binned =
        AnalysisDataService::Instance().retrieveWS<IMDHistoWorkspace>("binned");
    TSM_ASSERT("All basis vectors should have been normalized",
               binned->allBasisNormalized());
953
  }
954
955
};

956
class BinMDTestPerformance : public CxxTest::TestSuite {
957
public:
958
  MDEventWorkspace3Lean::sptr in_ws;
959

960
961
  // This pair of boilerplate methods prevent the suite being created statically
  // This means the constructor isn't called when running other tests
962
963
964
965
  static BinMDTestPerformance *createSuite() {
    return new BinMDTestPerformance();
  }
  static void destroySuite(BinMDTestPerformance *suite) { delete suite; }
966

967
  BinMDTestPerformance() {
968
969
    in_ws = MDEventsTestHelper::makeMDEW<3>(10, 0.0, 10.0, 0);
    in_ws->getBoxController()->setSplitThreshold(2000);
970
    in_ws->splitAllIfNeeded(NULL);
971
    AnalysisDataService::Instance().addOrReplace("BinMDTest_ws", in_ws);
972
973
974
    FrameworkManager::Instance().exec("FakeMDEventData", 4, "InputWorkspace",
                                      "BinMDTest_ws", "UniformParams",
                                      "1000000");
975
    // 1 million random points
976
977
    TS_ASSERT_EQUALS(in_ws->getNPoints(), 1000 * 1000);
    TS_ASSERT_EQUALS(in_ws->getBoxController()->getMaxId(), 1001);
978
979