AlignAndFocusPowderFromFilesTest.py 16.3 KB
Newer Older
1
2
3
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
4
5
#   NScD Oak Ridge National Laboratory, European Spallation Source,
#   Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6
7
8
9
# SPDX - License - Identifier: GPL - 3.0 +
#pylint: disable=no-init,invalid-name,attribute-defined-outside-init
import systemtesting
from mantid.simpleapi import *
10
11
from mantid.api import WorkspaceFactory
import numpy as np
12
import os
13
import time
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85


def do_cleanup(cacheDir):
    if os.path.exists(cacheDir) and os.path.isdir(cacheDir):
        print('Deleting cache: {}'.format(cacheDir))
        for filename in os.listdir(cacheDir):
            filename = os.path.join(cacheDir, filename)
            os.unlink(filename)
        os.rmdir(cacheDir)
    return True


def getCacheDir():
    """determine where to save - the current working directory"""
    direc = os.path.abspath(os.path.curdir)
    return os.path.join(direc, 'alignandfocuscache')


class SimplestCompare(systemtesting.MantidSystemTest):
    cal_file  = "PG3_FERNS_d4832_2011_08_24.cal"
    char_file = "PG3_characterization_2012_02_23-HR-ILL.txt"
    data_file = 'PG3_9829_event.nxs'

    def cleanup(self):
        return do_cleanup(self.cacheDir)

    def requiredMemoryMB(self):
        return 3*1024  # GiB

    def requiredFiles(self):
        return [self.cal_file, self.char_file, self.data_file]

    def runTest(self):
        self.cacheDir = getCacheDir()

        PDLoadCharacterizations(Filename=self.char_file, OutputWorkspace='characterizations',
                                SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0')

        self.wksp_mem = os.path.basename(self.data_file).split('.')[0]
        self.wksp_mem, self.wksp_file = self.wksp_mem + '_mem', self.wksp_mem + '_file'

        # load then process
        LoadEventAndCompress(Filename=self.data_file, OutputWorkspace=self.wksp_mem, MaxChunkSize=16, FilterBadPulses=0)
        LoadDiffCal(Filename=self.cal_file, InputWorkspace=self.wksp_mem, WorkspaceName='PG3')
        PDDetermineCharacterizations(InputWorkspace=self.wksp_mem, Characterizations='characterizations',
                                     ReductionProperties='__snspowderreduction_inner')
        AlignAndFocusPowder(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem,
                            GroupingWorkspace='PG3_group', CalibrationWorkspace='PG3_cal', MaskWorkspace='PG3_mask',
                            Params=-.0002, CompressTolerance=0.01,
                            PrimaryFlightPath=60, SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0',
                            ReductionProperties='__snspowderreduction_inner')
        NormaliseByCurrent(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem)
        ConvertUnits(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem, Target='dSpacing')

        # everything inside the algorithm
        AlignAndFocusPowderFromFiles(Filename=self.data_file, OutputWorkspace=self.wksp_file,
                                     GroupingWorkspace='PG3_group', CalibrationWorkspace='PG3_cal',
                                     MaskWorkspace='PG3_mask',
                                     Params=-.0002, CompressTolerance=0.01,
                                     PrimaryFlightPath=60, SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0',
                                     ReductionProperties='__snspowderreduction_inner')
        NormaliseByCurrent(InputWorkspace=self.wksp_file, OutputWorkspace=self.wksp_file)
        ConvertUnits(InputWorkspace=self.wksp_file, OutputWorkspace=self.wksp_file, Target='dSpacing')

    def validateMethod(self):
        self.tolerance = 1.0e-2
        return "ValidateWorkspaceToWorkspace"

    def validate(self):
        return (self.wksp_mem, self.wksp_file)


86
87
class ChunkingCompare(systemtesting.MantidSystemTest):
    # this test is very similar to SNAPRedux.Simple
88
89
90
91

    def requiredMemoryMB(self):
        return 24*1024  # GiB

92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
    def runTest(self):
        # 11MB file
        kwargs = {'Filename':'SNAP_45874',
                  'Params':(.5,-.004,7)}

        # create grouping for two output spectra
        CreateGroupingWorkspace(InstrumentFilename='SNAP_Definition.xml',
                                GroupDetectorsBy='Group',
                                OutputWorkspace='SNAP_grouping')

        # process in 4 chunks
        AlignAndFocusPowderFromFiles(OutputWorkspace='with_chunks', MaxChunkSize=.01, **kwargs)
        # process without chunks
        AlignAndFocusPowderFromFiles(OutputWorkspace='no_chunks', MaxChunkSize=0, **kwargs)

    def validateMethod(self):
        #self.tolerance = 1.0e-2
        return "ValidateWorkspaceToWorkspace"

    def validate(self):
        return ('with_chunks', 'no_chunks')


115
116
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
class UseCache(systemtesting.MantidSystemTest):
    cal_file  = "PG3_FERNS_d4832_2011_08_24.cal"
    char_file = "PG3_characterization_2012_02_23-HR-ILL.txt"
    data_file = 'PG3_9829_event.nxs'

    def cleanup(self):
        return do_cleanup(self.cacheDir)

    def requiredMemoryMB(self):
        return 3*1024  # GiB

    def requiredFiles(self):
        return [self.cal_file, self.char_file, self.data_file]

    def runTest(self):
        self.cacheDir = getCacheDir()

        PDLoadCharacterizations(Filename=self.char_file, OutputWorkspace='characterizations',
                                SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0')

        # first pass will create the cache file, second will use it
        self.wksp_make = 'makecache'
        self.wksp_use = 'usecache'

        # load then process
        LoadEventNexus(Filename=self.data_file, OutputWorkspace='meta', MetaDataOnly=True)
        LoadDiffCal(Filename=self.cal_file, InputWorkspace='meta', WorkspaceName='PG3')
        PDDetermineCharacterizations(InputWorkspace='meta', Characterizations='characterizations',
                                     ReductionProperties='__snspowderreduction_inner')
        DeleteWorkspace(Workspace='meta')

146
        duration = {}
147
        for name in (self.wksp_make, self.wksp_use):
148
            time_start = time.time()
149
150
151
152
153
154
155
            AlignAndFocusPowderFromFiles(Filename=self.data_file, OutputWorkspace=name,
                                         CacheDir=self.cacheDir,
                                         GroupingWorkspace='PG3_group', CalibrationWorkspace='PG3_cal',
                                         MaskWorkspace='PG3_mask',
                                         Params=-.0002, CompressTolerance=0.01,
                                         PrimaryFlightPath=60, SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0',
                                         ReductionProperties='__snspowderreduction_inner')
156
            duration[name] = time.time() - time_start
157
158
159
            NormaliseByCurrent(InputWorkspace=name, OutputWorkspace=name)
            ConvertUnits(InputWorkspace=name, OutputWorkspace=name, Target='dSpacing')

160
161
162
163
        # verify that the second time is faster
        self.assertLessThan(duration[self.wksp_use], duration[self.wksp_make],
                            'Should have been faster with cache {} > {}'.format(duration[self.wksp_use], duration[self.wksp_make]))

164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
    def validateMethod(self):
        self.tolerance = 1.0e-2
        return "ValidateWorkspaceToWorkspace"

    def validate(self):
        return (self.wksp_make, self.wksp_use)


class DifferentGrouping(systemtesting.MantidSystemTest):
    cal_file  = "PG3_FERNS_d4832_2011_08_24.cal"
    char_file = "PG3_characterization_2012_02_23-HR-ILL.txt"
    data_file = 'PG3_9829_event.nxs'

    def cleanup(self):
        return True  # nothing to cleanup

    def requiredMemoryMB(self):
        return 3*1024  # GiB

    def requiredFiles(self):
        return [self.cal_file, self.char_file, self.data_file]

    def runTest(self):
        self.cacheDir = getCacheDir()

        PDLoadCharacterizations(Filename=self.char_file, OutputWorkspace='characterizations',
                                SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0')

        # first pass will create the cache file, second will use it
        wksp_single = 'PG3_9829_single'
        wksp_banks = 'PG3_9829_banks'
        grp_banks = 'PG3_banks'

        # load then process
        LoadEventNexus(Filename=self.data_file, OutputWorkspace='meta', MetaDataOnly=True)
        LoadDiffCal(Filename=self.cal_file, InputWorkspace='meta', WorkspaceName='PG3')
        PDDetermineCharacterizations(InputWorkspace='meta', Characterizations='characterizations',
                                     ReductionProperties='__snspowderreduction_inner')
        CreateGroupingWorkspace(InputWorkspace='meta', OutputWorkspace=grp_banks, GroupDetectorsBy='bank')
        DeleteWorkspace(Workspace='meta')

        for name, grouping in zip((wksp_single, wksp_banks), ('PG3_group', grp_banks)):
            print('processing {} with {}'.format(name, grouping))
            AlignAndFocusPowderFromFiles(Filename=self.data_file, OutputWorkspace=name,
                                         GroupingWorkspace=grouping, CalibrationWorkspace='PG3_cal',
                                         MaskWorkspace='PG3_mask',
                                         Params=-.0002, CompressTolerance=0.01,
                                         PrimaryFlightPath=60, SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0',
                                         ReductionProperties='__snspowderreduction_inner')
            NormaliseByCurrent(InputWorkspace=name, OutputWorkspace=name)
            ConvertUnits(InputWorkspace=name, OutputWorkspace=name, Target='dSpacing')

        self.assertEqual(mtd[wksp_single].getNumberHistograms(), 1, 'focusing into single spectrum')
        self.assertEqual(mtd[wksp_banks].getNumberHistograms(), 23,
                         'focusing into detector banks {}!={}'.format(mtd[wksp_banks].getNumberHistograms(), 23))

    def validate(self):
        pass
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250


class AbsorptionCompare(systemtesting.MantidSystemTest):
    cal_file  = "PG3_FERNS_d4832_2011_08_24.cal"
    char_file = "PG3_characterization_2012_02_23-HR-ILL.txt"
    data_file = 'PG3_4866_event.nxs'

    def cleanup(self):
        return True

    def requiredMemoryMB(self):
        return 3*1024  # GiB

    def requiredFiles(self):
        return [self.cal_file, self.char_file, self.data_file]

    def runTest(self):
        PDLoadCharacterizations(Filename=self.char_file, OutputWorkspace='characterizations',
                                SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0')

        self.wksp_mem = os.path.basename(self.data_file).split('.')[0]
        self.wksp_mem, self.wksp_file = self.wksp_mem + '_mem', self.wksp_mem + '_file'

        # load then process
        LoadEventAndCompress(Filename=self.data_file, OutputWorkspace=self.wksp_mem, MaxChunkSize=16, FilterBadPulses=0)
        LoadDiffCal(Filename=self.cal_file, InputWorkspace=self.wksp_mem, WorkspaceName='PG3')
        PDDetermineCharacterizations(InputWorkspace=self.wksp_mem, Characterizations='characterizations',
                                     ReductionProperties='__snspowderreduction_inner')

251
        # set-up the absorption calculation
252
        num_wl_bins = 200
253
254
        prop_manager = PropertyManagerDataService.retrieve('__snspowderreduction_inner')
        wl_min, wl_max = prop_manager['wavelength_min'].value, prop_manager['wavelength_max'].value  # 0.05, 2.20
255
256
257
        absorptionWS = WorkspaceFactory.create(mtd[self.wksp_mem],
                                               NVectors=mtd[self.wksp_mem].getNumberHistograms(), XLength=num_wl_bins+1,
                                               YLength=num_wl_bins)
258
        xaxis = np.arange(0., float(num_wl_bins + 1)) * (wl_max - wl_min) / (num_wl_bins) + wl_min
259
260
261
262
263
264
265
        for i in range(absorptionWS.getNumberHistograms()):
            absorptionWS.setX(i, xaxis)
        absorptionWS.getAxis(0).setUnit('Wavelength')
        mantid.api.AnalysisDataService.addOrReplace('V_abs', absorptionWS)
        SetSample(InputWorkspace='V_abs',
                  Material={'ChemicalFormula': 'V', 'SampleNumberDensity': 0.0721},
                  Geometry={'Shape': 'Cylinder', 'Height': 6.97, 'Radius': (0.63 / 2), 'Center': [0., 0., 0.]})
266
        self.assertEqual(absorptionWS.blocksize(), num_wl_bins)
267
        # calculate the absorption
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
        CylinderAbsorption(InputWorkspace='V_abs', OutputWorkspace='V_abs',
                           NumberOfSlices=20, NumberOfAnnuli=3)

        # do the work in memory
        ConvertUnits(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem, Target='Wavelength')
        Divide(LHSWorkspace=self.wksp_mem, RHSWorkspace='V_abs', OutputWorkspace=self.wksp_mem)
        ConvertUnits(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem, Target='TOF')
        AlignAndFocusPowder(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem,
                            GroupingWorkspace='PG3_group', CalibrationWorkspace='PG3_cal', MaskWorkspace='PG3_mask',
                            Params=-.0002, CompressTolerance=0.01,
                            PrimaryFlightPath=60, SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0',
                            ReductionProperties='__snspowderreduction_inner')
        NormaliseByCurrent(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem)
        ConvertUnits(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem, Target='dSpacing')

        # everything inside the algorithm
        AlignAndFocusPowderFromFiles(Filename=self.data_file, OutputWorkspace=self.wksp_file,
                                     GroupingWorkspace='PG3_group', CalibrationWorkspace='PG3_cal',
                                     MaskWorkspace='PG3_mask',
                                     AbsorptionWorkspace='V_abs',
                                     Params=-.0002, CompressTolerance=0.01,
                                     PrimaryFlightPath=60, SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0',
                                     ReductionProperties='__snspowderreduction_inner')
        NormaliseByCurrent(InputWorkspace=self.wksp_file, OutputWorkspace=self.wksp_file)
        ConvertUnits(InputWorkspace=self.wksp_file, OutputWorkspace=self.wksp_file, Target='dSpacing')

    def validateMethod(self):
        self.tolerance = 1.0e-2
        return "ValidateWorkspaceToWorkspace"

    def validate(self):
299
300
301
        # verify the material name
        assert mtd[self.wksp_file].sample().getMaterial().name() == 'V'
        # use standard method
302
        return (self.wksp_mem, self.wksp_file)
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344

class VulcanRaggedCompare(systemtesting.MantidSystemTest):
    cal_file  = "VULCAN_calibrate_2019_06_27.h5"
    data_file = 'VULCAN_189186.nxs.h5'

    def cleanup(self):
        return do_cleanup(self.cacheDir)

    def requiredMemoryMB(self):
        return 3*1024  # GiB

    def requiredFiles(self):
        return [self.cal_file, self.data_file]

    def runTest(self):
        self.cacheDir = getCacheDir()

        self.wksp_mem = os.path.basename(self.data_file).split('.')[0]
        self.wksp_mem, self.wksp_file = self.wksp_mem + '_mem', self.wksp_mem + '_file'

        # load then process
        LoadEventAndCompress(Filename=self.data_file, OutputWorkspace=self.wksp_mem, MaxChunkSize=16, FilterBadPulses=0)
        LoadDiffCal(Filename=self.cal_file, InputWorkspace=self.wksp_mem, WorkspaceName='PG3')
        AlignAndFocusPowder(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem,
                            GroupingWorkspace='PG3_group', CalibrationWorkspace='PG3_cal', MaskWorkspace='PG3_mask',
                            Params=-.0002, CompressTolerance=0.01,
                            PrimaryFlightPath=60, SpectrumIDs='1,2,3', L2='3.18,3.18,3.18', Polar='90,270,145', Azimuthal='0,0,0')

        # everything inside the algorithm
        AlignAndFocusPowderFromFiles(Filename=self.data_file, OutputWorkspace=self.wksp_file,
                                     GroupingWorkspace='PG3_group', CalibrationWorkspace='PG3_cal',
                                     MaskWorkspace='PG3_mask',
                                     Params=-.0002, CompressTolerance=0.01,
                                     PrimaryFlightPath=60, SpectrumIDs='1,2,3', L2='3.18,3.18,3.18', Polar='90,270,145', Azimuthal='0,0,0',
                                     ReductionProperties='__snspowderreduction_inner')

    def validateMethod(self):
        self.tolerance = 1.0e-2
        return "ValidateWorkspaceToWorkspace"

    def validate(self):
        return (self.wksp_mem, self.wksp_file)