forked from npshub/mantid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SANSUtility.py
2428 lines (1996 loc) · 88.2 KB
/
SANSUtility.py
1
2
3
4
5
6
7
8
9
10
11
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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
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
299
300
301
302
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
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
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
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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
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
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
#pylint: disable=too-many-lines
#pylint: disable=invalid-name
#########################################################
# This module contains utility functions common to the
# SANS data reduction scripts
########################################################
from mantid.simpleapi import *
from mantid.api import IEventWorkspace, MatrixWorkspace, WorkspaceGroup, FileLoaderRegistry, FileFinder
from mantid.kernel import DateAndTime
import inspect
import math
import os
import re
import types
import numpy as np
import h5py as h5
sanslog = Logger("SANS")
ADDED_TAG = '-add'
ADDED_EVENT_DATA_TAG = '_added_event_data'
ADD_TAG = '-add'
ADD_MONITORS_TAG = '-add_monitors'
REG_DATA_NAME = ADD_TAG + ADDED_EVENT_DATA_TAG + '[_1-9]*$'
REG_DATA_MONITORS_NAME = ADD_MONITORS_TAG + ADDED_EVENT_DATA_TAG + '[_1-9]*$'
ZERO_ERROR_DEFAULT = 1e6
INCIDENT_MONITOR_TAG = '_incident_monitor'
MANTID_PROCESSED_WORKSPACE_TAG = 'Mantid Processed Workspace'
def deprecated(obj):
"""
Decorator to apply to functions or classes that we think are not being (or
should not be) used anymore. Prints a warning to the log.
"""
if inspect.isfunction(obj) or inspect.ismethod(obj):
if inspect.isfunction(obj):
obj_desc = "\"%s\" function" % obj.__name__
else:
obj_desc = "\"%s\" class" % obj.__self__.__class__.__name__
def print_warning_wrapper(*args, **kwargs):
sanslog.warning("The %s has been marked as deprecated and may be "
"removed in a future version of Mantid. If you "
"believe this to have been marked in error, please "
"contact the member of the Mantid team responsible "
"for ISIS SANS." % obj_desc)
return obj(*args, **kwargs)
return print_warning_wrapper
# Add a @deprecated decorator to each of the member functions in the class
# (by recursion).
if inspect.isclass(obj):
for name, fn in inspect.getmembers(obj):
if isinstance(fn, types.MethodType):
setattr(obj, name, deprecated(fn))
return obj
assert False, "Programming error. You have incorrectly applied the "\
"@deprecated decorator. This is only for use with functions "\
"or classes."
def GetInstrumentDetails(instrum):
"""
Return the details specific to the instrument's current detector bank
@return number of pixels ac, first spectrum in the current detector, its last spectrum
"""
det = instrum.cur_detector()
#LOQ HAB is not a square detector and so has no width
#for backwards compatibility we have to return a width
if instrum.name() == 'LOQ' and instrum.cur_detector().name() == 'HAB':
if det.n_columns is None :
return 128, det.get_first_spec_num(), det.last_spec_num
first_spectrum = det.get_first_spec_num()
last_spectrum = det.last_spec_num
if instrum.name() == 'SANS2D':
first_spectrum += 4
last_spectrum += 4
return det.n_columns, first_spectrum, last_spectrum
def InfinitePlaneXML(id_name, plane_pt, normal_pt):
return '<infinite-plane id="' + str(id_name) + '">' + \
'<point-in-plane x="' + str(plane_pt[0]) + '" y="' + str(plane_pt[1]) + '" z="' + str(plane_pt[2]) + '" />' + \
'<normal-to-plane x="' + str(normal_pt[0]) + '" y="' + str(normal_pt[1]) + '" z="' + str(normal_pt[2]) + '" />'+ \
'</infinite-plane>'
def InfiniteCylinderXML(id_name, centre, radius, axis):
return '<infinite-cylinder id="' + str(id_name) + '">' + \
'<centre x="' + str(centre[0]) + '" y="' + str(centre[1]) + '" z="' + str(centre[2]) + '" />' + \
'<axis x="' + str(axis[0]) + '" y="' + str(axis[1]) + '" z="' + str(axis[2]) + '" />' + \
'<radius val="' + str(radius) + '" />' + \
'</infinite-cylinder>\n'
# Mask a cylinder, specifying the algebra to use
def MaskWithCylinder(workspace, radius, xcentre, ycentre, algebra):
'''Mask a cylinder on the input workspace.'''
xmldef = InfiniteCylinderXML('shape', [xcentre, ycentre, 0.0], radius, [0,0,1])
xmldef += '<algebra val="' + algebra + 'shape" />'
# Apply masking
MaskDetectorsInShape(Workspace=workspace,ShapeXML=xmldef)
# Mask such that the remainder is that specified by the phi range
def LimitPhi(workspace, centre, phimin, phimax, use_mirror=True):
# convert all angles to be between 0 and 360
while phimax > 360 :
phimax -= 360
while phimax < 0 :
phimax += 360
while phimin > 360 :
phimin -= 360
while phimin < 0 :
phimin += 360
while phimax<phimin :
phimax += 360
#Convert to radians
phimin = math.pi*phimin/180.0
phimax = math.pi*phimax/180.0
xmldef = InfinitePlaneXML('pla',centre, [math.cos(-phimin + math.pi/2.0),math.sin(-phimin + math.pi/2.0),0]) + \
InfinitePlaneXML('pla2',centre, [-math.cos(-phimax + math.pi/2.0),-math.sin(-phimax + math.pi/2.0),0]) + \
InfinitePlaneXML('pla3',centre, [math.cos(-phimax + math.pi/2.0),math.sin(-phimax + math.pi/2.0),0]) + \
InfinitePlaneXML('pla4',centre, [-math.cos(-phimin + math.pi/2.0),-math.sin(-phimin + math.pi/2.0),0])
if use_mirror :
xmldef += '<algebra val="#((pla pla2):(pla3 pla4))" />'
else:
#the formula is different for acute verses obstruse angles
if phimax-phimin > math.pi :
# to get an obtruse angle, a wedge that's more than half the area, we need to add the semi-inifinite volumes
xmldef += '<algebra val="#(pla:pla2)" />'
else :
# an acute angle, wedge is more less half the area, we need to use the intesection of those semi-inifinite volumes
xmldef += '<algebra val="#(pla pla2)" />'
MaskDetectorsInShape(Workspace=workspace,ShapeXML= xmldef)
# Work out the spectra IDs for block of detectors
def spectrumBlock(base, ylow, xlow, ydim, xdim, det_dimension, orientation):
'''Compile a list of spectrum Nos for rectangular block of size xdim by ydim'''
output = ''
if orientation == Orientation.Horizontal:
start_spec = base + ylow*det_dimension + xlow
for y in range(0, ydim):
for x in range(0, xdim):
output += str(start_spec + x + (y*det_dimension)) + ','
elif orientation == Orientation.Vertical:
start_spec = base + xlow*det_dimension + ylow
for x in range(det_dimension - 1, det_dimension - xdim-1,-1):
for y in range(0, ydim):
std_i = start_spec + y + ((det_dimension-x-1)*det_dimension)
output += str(std_i ) + ','
elif orientation == Orientation.Rotated:
# This is the horizontal one rotated so need to map the xlow and vlow to their rotated versions
start_spec = base + ylow*det_dimension + xlow
max_spec = det_dimension*det_dimension + base - 1
for y in range(0, ydim):
for x in range(0, xdim):
std_i = start_spec + x + (y*det_dimension)
output += str(max_spec - (std_i - base)) + ','
return output.rstrip(",")
# Mask by bin range
def MaskByBinRange(workspace, timemask):
# timemask should be a ';' separated list of start/end values
ranges = timemask.split(';')
for r in ranges:
limits = r.split()
if len(limits) == 2:
MaskBins(InputWorkspace=workspace,OutputWorkspace= workspace, XMin= limits[0] ,XMax=limits[1])
def QuadrantXML(centre,rmin,rmax,quadrant):
cin_id = 'cyl-in'
xmlstring = InfiniteCylinderXML(cin_id, centre, rmin, [0,0,1])
cout_id = 'cyl-out'
xmlstring+= InfiniteCylinderXML(cout_id, centre, rmax, [0,0,1])
plane1Axis=None
plane2Axis=None
if quadrant == 'Left':
plane1Axis = [-1,1,0]
plane2Axis = [-1,-1,0]
elif quadrant == 'Right':
plane1Axis = [1,-1,0]
plane2Axis = [1,1,0]
elif quadrant == 'Up':
plane1Axis = [1,1,0]
plane2Axis = [-1,1,0]
elif quadrant == 'Down':
plane1Axis = [-1,-1,0]
plane2Axis = [1,-1,0]
else:
return ''
p1id = 'pl-a'
xmlstring += InfinitePlaneXML(p1id, centre, plane1Axis)
p2id = 'pl-b'
xmlstring += InfinitePlaneXML(p2id, centre, plane2Axis)
# The composition of the shape is "(cyl-out (#cyl-in) (pl-a:pl-b))". The breakdown is:
# 1. Create an infinite hollow cylinder by performing "cyl-out (#cyl-in)". This is the intersection of the
# outer radius cylinder with the inverse inner radius cylinder. We have a shell-like selection
# 2. Create a three-quarter wedge selection by performing (pl-a:pl-b). This selects everything except
# for the slice region we don't want to be masked.
# 3. Create the intersection between 1 and 2. This will provide a three-quarter wedge of the hollow
# cylinder.
xmlstring += '<algebra val="(#(' + cout_id + ' (#' + cin_id + ')) : (' + p1id + ':' + p2id + '))"/>\n'
return xmlstring
def getWorkspaceReference(ws_pointer):
if isinstance(ws_pointer, str):
ws_pointer = mtd[ws_pointer]
if str(ws_pointer) not in mtd:
raise RuntimeError("Invalid workspace name input: " + str(ws_pointer))
return ws_pointer
def isEventWorkspace(ws_reference):
return isinstance(getWorkspaceReference(ws_reference),IEventWorkspace)
def getBinsBoundariesFromWorkspace(ws_reference):
ws_reference = getWorkspaceReference(ws_reference)
Xvalues = ws_reference.dataX(0)
binning = str(Xvalues[0])
binGap = Xvalues[1] - Xvalues[0]
binning = binning + ',' + str(binGap)
for j in range(2, len(Xvalues)):
nextBinGap = Xvalues[j] - Xvalues[j-1]
if nextBinGap != binGap:
binGap = nextBinGap
binning = binning + ',' + str(Xvalues[j-1]) + ',' + str(binGap)
binning = binning + "," + str(Xvalues[-1])
return binning
def getFilePathFromWorkspace(ws):
ws_pointer = getWorkspaceReference(ws)
if isinstance(ws_pointer, WorkspaceGroup):
ws_pointer = ws_pointer[0]
file_path = None
try:
for hist in ws_pointer.getHistory():
try:
if 'Load' in hist.name():
file_path = hist.getPropertyValue('Filename')
# pylint: disable=bare-except
except:
pass
except:
try:
hist = ws_pointer.getHistory().lastAlgorithm()
file_path = hist.getPropertyValue('Filename')
except:
raise RuntimeError("Failed while looking for file in workspace: " + str(ws))
if not file_path:
raise RuntimeError("Can not find the file name for workspace " + str(ws))
return file_path
def fromEvent2Histogram(ws_event, ws_monitor, binning = ""):
"""Transform an event mode workspace into a histogram workspace.
It does conjoin the monitor and the workspace as it is expected from the current
SANS data inside ISIS.
A non-empty binning string will specify a rebin param list to use instead of using
the binning of the monitor ws.
Finally, it copies the parameter map from the workspace to the resulting histogram
in order to preserve the positions of the detectors components inside the workspace.
It will finally, replace the input workspace with the histogram equivalent workspace.
"""
assert ws_monitor is not None
name = '__monitor_tmp'
if binning != "":
aux_hist = Rebin(ws_event, binning, False)
Rebin(InputWorkspace=ws_monitor, Params=binning, PreserveEvents=False, OutputWorkspace=name)
else:
aux_hist = RebinToWorkspace(WorkspaceToRebin=ws_event, WorkspaceToMatch=ws_monitor,
PreserveEvents=False)
ws_monitor.clone(OutputWorkspace=name)
ConjoinWorkspaces(name, aux_hist, CheckOverlapping=True)
CopyInstrumentParameters(ws_event, OutputWorkspace=name)
ws_hist = RenameWorkspace(name, OutputWorkspace=str(ws_event))
return ws_hist
def getChargeAndTime(ws_event):
r = ws_event.getRun()
charges = r.getLogData('proton_charge')
total_charge = sum(charges.value)
time_passed = (charges.times[-1] - charges.times[0]) / np.timedelta64(1, 's')
return total_charge, time_passed
def sliceByTimeWs(ws_event, time_start=None, time_stop=None):
def formatTime(time_val):
return "_T%.1f" % time_val
params = dict()
outname=str(ws_event)
if time_start:
outname +=formatTime(time_start)
params['StartTime'] = time_start
if time_stop:
outname += formatTime(time_stop)
params['StopTime'] = time_stop
params['OutputWorkspace'] = outname
sliced_ws = FilterByTime(ws_event, **params)
return sliced_ws
def slice2histogram(ws_event, time_start, time_stop, monitor, binning=""):
"""Return the histogram of the sliced event and a tuple with the following:
- total time of the experiment
- total charge
- time of sliced data
- charge of sliced data
@param ws_event pointer to the event workspace
@param time_start: the minimum value to filter. Pass -1 to get the minimum available
@param time_stop: the maximum value to filter. Pass -1 to get the maximum available
@param monitor: pointer to the monitor workspace
@param binning: optional binning string to use instead of the binning from the monitor
"""
if not isEventWorkspace(ws_event):
raise RuntimeError("The workspace "+str(ws_event)+ " is not a valid Event workspace")
tot_c, tot_t = getChargeAndTime(ws_event)
if (time_start == -1) and (time_stop == -1):
hist = fromEvent2Histogram(ws_event, monitor, binning)
return hist, (tot_t, tot_c, tot_t, tot_c)
if time_start == -1:
time_start = 0.0
if time_stop == -1:
time_stop = tot_t+0.001
sliced_ws = sliceByTimeWs(ws_event, time_start, time_stop)
sliced_ws = RenameWorkspace(sliced_ws, OutputWorkspace=ws_event.name())
part_c, part_t = getChargeAndTime(sliced_ws)
scaled_monitor = monitor * (part_c/tot_c)
hist = fromEvent2Histogram(sliced_ws, scaled_monitor, binning)
return hist, (tot_t, tot_c, part_t, part_c)
def sliceParser(str_to_parser): # noqa: C901
"""
Create a list of boundaries from a string defing the slices.
Valid syntax is:
* From 8 to 9 > '8-9' --> return [[8,9]]
* From 8 to 9 and from 10 to 12 > '8-9, 10-12' --> return [[8,9],[10,12]]
* From 5 to 10 in steps of 1 > '5:1:10' --> return [[5,6],[6,7],[7,8],[8,9],[9,10]]
* From 5 > '>5' --> return [[5,-1]]
* Till 5 > '<5' --> return [[-1,5]]
Any combination of these syntax separated by comma is valid.
A special mark is used to signalize no limit: -1,
As, so, for an empty string, it will return: [[-1, -1]].
It does not accept negative values.
"""
num_pat = r'(\d+(?:\.\d+)?(?:[eE][+-]\d+)?)' # float without sign
slice_pat = num_pat + r'-' + num_pat
lowbound = '>'+num_pat
upbound = '<'+num_pat
sss_pat = num_pat+r':'+num_pat+r':'+num_pat
exception_pattern = 'Invalid input for Slicer: %s'
MARK = -1
def _check_match(inpstr, patternstr, qtde_nums):
match = re.match(patternstr, inpstr)
if match:
answer = match.groups()
if len(answer) != qtde_nums:
raise SyntaxError(exception_pattern %(inpstr))
return [float(answer[i]) for i in range(qtde_nums)]
else:
return False
def _parse_slice(inpstr):
return _check_match(inpstr, slice_pat, 2)
def _parse_lower(inpstr):
val = _check_match(inpstr, lowbound, 1)
if not val:
return val
return [val[0], MARK]
def _parse_upper(inpstr):
val = _check_match(inpstr, upbound, 1)
if not val:
return val
return [MARK, val[0]]
def _parse_start_step_stop(inpstr):
val = _check_match(inpstr, sss_pat, 3)
if not val:
return val
start = val[0]
step = val[1]
stop = val[2]
curr_value = start
vallist = []
while True:
next_value = curr_value + step
if next_value >= stop:
vallist.append([curr_value, stop])
return vallist
else:
vallist.append([curr_value, next_value])
curr_value = next_value
def _extract_simple_input(inpstr):
for fun in _parse_slice, _parse_lower, _parse_upper:
val = fun(inpstr)
if val:
return val
return False
def _extract_composed_input(inpstr):
return _parse_start_step_stop(inpstr)
if not str_to_parser:
return [[MARK, MARK]]
parts = str_to_parser.split(',')
result = []
for inps in parts:
inps = inps.replace(' ','')
aux_res = _extract_simple_input(inps)
if aux_res:
result.append(aux_res)
continue
aux_res = _extract_composed_input(inps)
if aux_res:
result += aux_res
continue
raise SyntaxError('Invalid input '+ str_to_parser +'. Failed caused by this term:'+inps)
return result
def getFileAndName(incomplete_path):
this_path = FileFinder.getFullPath(incomplete_path)
if not this_path:
# do not catch exception, let it goes.
this_path = FileFinder.findRuns(incomplete_path)
# if list, get first value
if hasattr(this_path, '__iter__'):
this_path = this_path[0]
# this_path contains the full_path
basename = os.path.basename(this_path)
# remove extension
basename = os.path.splitext(basename)[0]
return this_path, basename
def _merge_to_ranges(ints):
"""
Given an integer list, will "merge" adjacent integers into "ranges".
Assumes that the given list will already be sorted and that it contains no
duplicates. Best explained with examples:
Input: [1, 2, 3, 4]
Output: [[1, 4]]
Input: [1, 2, 3, 5, 6, 7]
Output: [[1, 3], [5, 7]]
Input: [1, 2, 3, 5, 7, 8, 9]
Output: [[1, 3], [5, 5], [7, 9]]
Input: [1, 2, 7, 5, 6, 3, 2, 2]
Output: Unknown -- the input contains duplicates and is unsorted.
@params ints :: the integer list to merge, sorted and without duplicates
@returns a list of ranges
"""
ranges = []
current_range = []
for i in ints:
if current_range == []:
current_range = [i, i]
elif current_range[1] + 1 == i:
current_range[1] = i
else:
ranges.append(current_range)
current_range = [i, i]
if current_range not in ranges:
ranges.append(current_range)
return ranges
def _yield_masked_det_ids(masking_ws):
"""
For some reason Detector.isMasked() does not work for MaskingWorkspaces.
We use masking_ws.readY(ws_index)[0] == 1 instead.
"""
for ws_index in range(masking_ws.getNumberHistograms()):
if masking_ws.readY(ws_index)[0] == 1:
yield masking_ws.getDetector(ws_index).getID()
def get_masked_det_ids_from_mask_file(mask_file_path, idf_path):
"""
Given a mask file and the (necessary) path to the corresponding IDF, will
load in the file and return a list of detector IDs that are masked.
@param mask_file_path :: the path of the mask file to read in
@param idf_path :: the path to the corresponding IDF. Necessary so that we
know exactly which instrument to use, and therefore know
the correct detector IDs.
@returns the list of detector IDs that were masked in the file
"""
mask_ws_name = "__temp_mask"
LoadMask(
Instrument=idf_path,
InputFile=mask_file_path,
OutputWorkspace=mask_ws_name)
det_ids = list(_yield_masked_det_ids(mtd[mask_ws_name]))
DeleteWorkspace(Workspace=mask_ws_name)
return det_ids
def mask_detectors_with_masking_ws(ws_name, masking_ws_name):
"""
Rolling our own MaskDetectors wrapper since masking is broken in a couple
of places that affect us here.
Calling MaskDetectors(Workspace=ws_name, MaskedWorkspace=mask_ws_name) is
not something we can do because the algorithm masks by ws index rather than
detector id, and unfortunately for SANS the detector table is not the same
for MaskingWorkspaces as it is for the workspaces containing the data to be
masked. Basically, we get a mirror image of what we expect. Instead, we
have to extract the det IDs and use those via the DetectorList property.
@param ws :: the workspace to be masked.
@param masking_ws :: the masking workspace that contains masking info.
"""
ws, masking_ws = mtd[ws_name], mtd[masking_ws_name]
masked_det_ids = list(_yield_masked_det_ids(masking_ws))
MaskDetectors(Workspace=ws, DetectorList=masked_det_ids, ForceInstrumentMasking=True)
def check_child_ws_for_name_and_type_for_added_eventdata(wsGroup, number_of_entries=None):
'''
Ensure that the while loading added event data, we are dealing with
1. The correct naming convention. For event data this is the run number,
an add tag and possibly underscores and numbers when the same workspace
is reloaded. For monitor data it is the run number, an add tag, a monitor
tag and the possibly underscores and numbers when the same workspace is
reloaded
2. The correct workspace types.
@param wsGroup :: workspace group.
@param number_of_entries:: how many entries the group workspace may have.
'''
# Check if there are only two children in the group workspace
if number_of_entries is not None:
if len(wsGroup) != number_of_entries:
return False
# There has to be an even number of workspaces, for each data workspace
# there has to be a monitor workspace
if len(wsGroup)%2 != 0:
return False
assert isinstance(wsGroup, WorkspaceGroup)
# Check all entries
has_data = []
has_monitors = []
for index in range(len(wsGroup)):
childWorkspace = wsGroup.getItem(index)
if re.search(REG_DATA_NAME, childWorkspace.name()):
is_in = True if isinstance(childWorkspace, IEventWorkspace) else False
has_data.append(is_in)
elif re.search(REG_DATA_MONITORS_NAME, childWorkspace.name()):
is_in = True if isinstance(childWorkspace, MatrixWorkspace) else False
has_monitors.append(is_in)
total_has_data = False if len(has_data) == 0 else all(has_data)
total_has_monitors = False if len(has_data) == 0 else all(has_monitors)
one_monitor_per_data = len(has_data) == len(has_monitors)
return total_has_data and total_has_monitors and one_monitor_per_data
def extract_child_ws_for_added_eventdata(ws_group, appendix):
'''
Extract the the child workspaces from a workspace group which was
created by adding event data. The workspace group must contains a data
workspace which is an EventWorkspace and a monitor workspace which is a
matrix workspace.
@param ws_group :: workspace group.
@param appendix :: what to append to the names of the child workspaces
'''
# Store the name of the group workspace in a string
ws_group_name = ws_group.name()
# Get a handle on each child workspace
ws_handles = []
for index in range(len(ws_group)):
ws_handles.append(ws_group.getItem(index))
if len(ws_handles) % 2:
raise RuntimeError("Expected two child workspaces when loading added event data."
"Please make sure that you have loaded added event data which was generated by the Add tab of the SANS Gui."
)
# Now ungroup the group
UnGroupWorkspace(ws_group)
# Rename the child workspaces to be of the expected format. (see _get_workspace_name in sans_reduction_steps)
data_workspaces = []
monitor_workspaces = []
for ws_handle in ws_handles:
old_workspace_name = ws_handle.name()
# Get the index of the multiperiod workspace if it is present
new_workspace_name = get_new_workspace_name(appendix, old_workspace_name, ws_group_name)
RenameWorkspace(InputWorkspace = ws_handle, OutputWorkspace=new_workspace_name)
if appendix in old_workspace_name:
monitor_workspaces.append(new_workspace_name)
else:
data_workspaces.append(new_workspace_name)
# If there is more than one entry for the data and monitor workspaces, then we need to group them
if len(data_workspaces) != len(monitor_workspaces):
raise RuntimeError("The number of data workspaces does not match the number of monitor workspaces.")
if len(data_workspaces) > 1 and len(monitor_workspaces) > 1:
GroupWorkspaces(InputWorkspaces = monitor_workspaces, OutputWorkspace = ws_group_name + appendix)
GroupWorkspaces(InputWorkspaces = data_workspaces, OutputWorkspace = ws_group_name)
def get_new_workspace_name(appendix, old_workspace_name, ws_group_name):
new_workspace_name = ws_group_name
final_number = re.search(r'_(\d+)$', old_workspace_name)
if final_number is not None:
new_workspace_name += final_number.group(0)
if appendix in old_workspace_name:
new_workspace_name += appendix
return new_workspace_name
class WorkspaceType(object):
class Event(object):
pass
class Histogram(object):
pass
class MultiperiodEvent(object):
pass
class MultiperiodHistogram(object):
pass
class Other(object):
pass
def get_number_of_periods_from_file(file_name):
full_file_path = FileFinder.findRuns(file_name)
if hasattr(full_file_path, '__iter__'):
full_file_path = full_file_path[0]
try:
with h5.File(full_file_path, 'r') as h5_file:
first_entry = h5_file["raw_data_1"]
period_group = first_entry["periods"]
proton_charge_data_set = period_group["proton_charge"]
number_of_periods = len(proton_charge_data_set)
except IOError:
number_of_periods = -1
return number_of_periods
def check_if_is_event_data(file_name):
"""
Event mode files have a class with a "NXevent_data" type
Structure:
|--mantid_workspace_1/raw_data_1|
|--some_group|
|--Attribute: NX_class = NXevent_data
"""
full_file_path = FileFinder.findRuns(file_name)
if hasattr(full_file_path, '__iter__'):
file_name = full_file_path[0]
with h5.File(file_name, 'r') as h5_file:
# Open first entry
keys = list(h5_file.keys())
first_entry = h5_file[keys[0]]
# Open instrument group
is_event_mode = False
for value in list(first_entry.values()):
if "NX_class" in value.attrs:
if "NXevent_data" == value.attrs["NX_class"].decode() :
is_event_mode = True
break
return is_event_mode
def is_nexus_file(file_name):
full_file_path = FileFinder.findRuns(file_name)
if hasattr(full_file_path, '__iter__'):
file_name = full_file_path[0]
is_nexus = True
try:
with h5.File(file_name, 'r') as h5_file:
keys = list(h5_file.keys())
nexus_test = "raw_data_1" in keys or "mantid_workspace_1" in keys
is_nexus = True if nexus_test else False
except: # noqa
is_nexus = False
return is_nexus
def get_workspace_type(file_name):
if is_nexus_file(file_name):
number_of_periods = get_number_of_periods_from_file(file_name)
is_event_data = check_if_is_event_data(file_name)
if number_of_periods > 1:
workspace_type = WorkspaceType.MultiperiodEvent if is_event_data else WorkspaceType.MultiperiodHistogram
else:
workspace_type = WorkspaceType.Event if is_event_data else WorkspaceType.Histogram
else:
workspace_type = WorkspaceType.Other
return workspace_type
def bundle_added_event_data_as_group(out_file_name, out_file_monitors_name, is_multi_period):
"""
We load an added event data file and its associated monitor file. Combine
the data in a group workspace and delete the original files.
@param out_file_name :: the file name of the event data file
@param out_file_monitors_name :: the file name of the monitors file
@param is_multi_period: if the data set is multiperid
@return the name fo the new group workspace file
"""
# Extract the file name and the extension
file_name, file_extension = os.path.splitext(out_file_name)
event_data_temp = file_name + ADDED_EVENT_DATA_TAG
Load(Filename = out_file_name, OutputWorkspace = event_data_temp)
event_data_ws = mtd[event_data_temp]
monitor_temp = file_name + '_monitors' + ADDED_EVENT_DATA_TAG
Load(Filename = out_file_monitors_name, OutputWorkspace = monitor_temp)
monitor_ws = mtd[monitor_temp]
out_group_file_name = file_name + file_extension
out_group_ws_name = file_name
# Delete the intermediate files
full_data_path_name = get_full_path_for_added_event_data(out_file_name)
full_monitor_path_name = get_full_path_for_added_event_data(out_file_monitors_name)
if os.path.exists(full_data_path_name):
os.remove(full_data_path_name)
if os.path.exists(full_monitor_path_name):
os.remove(full_monitor_path_name)
# Create a grouped workspace with the data and the monitor child workspaces
workspace_names_to_group = []
if isinstance(event_data_ws, WorkspaceGroup):
for workspace in event_data_ws:
workspace_names_to_group.append(workspace.name())
else:
workspace_names_to_group.append(event_data_ws.name())
if isinstance(monitor_ws, WorkspaceGroup):
for workspace in monitor_ws:
workspace_names_to_group.append(workspace.name())
else:
workspace_names_to_group.append(monitor_ws.name())
GroupWorkspaces(InputWorkspaces = workspace_names_to_group, OutputWorkspace = out_group_ws_name)
group_ws = mtd[out_group_ws_name]
# Save the group
SaveNexusProcessed(InputWorkspace = group_ws, Filename = out_group_file_name, Append=False)
# Delete the files and the temporary workspaces
if out_group_ws_name in mtd:
DeleteWorkspace(out_group_ws_name)
return out_group_file_name
def get_full_path_for_added_event_data(file_name):
path,base = os.path.split(file_name)
if path == '' or base not in os.listdir(path):
path = config['defaultsave.directory'] + path
# If the path is still an empty string check in the current working directory
if path == '':
path = os.getcwd()
assert base in os.listdir(path)
full_path_name = os.path.join(path, base)
return full_path_name
def extract_spectra(ws, det_ids, output_ws_name):
"""
A more generic version of ExtactSingleSpectrum. Accepts an arbitrary list
of ws indices to keep. Everything else is ignored.
@param ws :: the workspace from which to extract spectra
@param det_ids :: the detector IDs corresponding to the spectra to extract
@param output_ws_name :: the name of the resulting workspace
@returns :: a workspace containing the extracted spectra
"""
ExtractSpectra(InputWorkspace=ws,OutputWorkspace=output_ws_name, DetectorList=det_ids)
return mtd[output_ws_name]
def get_masked_det_ids(ws):
"""
Given a workspace, will return a list of all the IDs that correspond to
detectors that have been masked.
@param ws :: the workspace to extract the det IDs from
@returns a list of IDs for masked detectors
"""
spectrumInfo = ws.spectrumInfo()
for ws_index in range(ws.getNumberHistograms()):
if not spectrumInfo.hasDetectors(ws_index):
# Skip the rest after finding the first spectra with no detectors,
# which is a big speed increase for SANS2D.
break
if spectrumInfo.isMasked(ws_index):
yield ws.getDetector(ws_index).getID()
def create_zero_error_free_workspace(input_workspace_name, output_workspace_name):
'''
Creates a cloned workspace where all zero-error values have been replaced with a large value
@param input_workspace_name :: The input workspace name
@param output_workspace_name :: The output workspace name
@returns a message and a completion flag
'''
# Load the input workspace
message = ""
complete = False
if input_workspace_name not in mtd:
message = 'Failed to create a zero error free cloned workspace: The input workspace does not seem to exist.'
return message, complete
# Create a cloned workspace
ws_in = mtd[input_workspace_name]
# Remove all zero errors from the cloned workspace
CloneWorkspace(InputWorkspace=ws_in, OutputWorkspace=output_workspace_name)
if output_workspace_name not in mtd:
message = 'Failed to create a zero error free cloned workspace: A clone could not be created.'
return message, complete
ws_out = mtd[output_workspace_name]
try:
remove_zero_errors_from_workspace(ws_out)
complete = True
except ValueError:
DeleteWorkspace(Workspace=output_workspace_name)
message = 'Failed to create a zero error free cloned workspace: Could not remove the zero errors.'
return message, complete
def remove_zero_errors_from_workspace(ws):
'''
Removes the zero errors from a Matrix workspace
@param ws :: The input workspace
'''
# Make sure we are dealing with a MatrixWorkspace
if not isinstance(ws, MatrixWorkspace) or isinstance(ws,IEventWorkspace):
raise ValueError('Cannot remove zero errors from a workspace which is not of type MatrixWorkspace.')
# Iterate over the workspace and replace the zero values with a large default value
numSpectra = ws.getNumberHistograms()
errors = ws.dataE
for index in range(0,numSpectra):
spectrum = errors(index)
spectrum[spectrum <= 0.0] = ZERO_ERROR_DEFAULT
def delete_zero_error_free_workspace(input_workspace_name):
'''
Deletes the zero-error free workspace
@param ws :: The input workspace
'''
complete = False
message = ""
if input_workspace_name in mtd:
DeleteWorkspace(Workspace=input_workspace_name)
complete = True
else:
message = 'Failed to delete a zero-error free workspace'
return message, complete
def is_valid_ws_for_removing_zero_errors(input_workspace_name):
'''
Check if a workspace has been created via Q1D or Qxy.
@param ws :: The input workspace
'''
isValid = False
message = ""
ws = mtd[input_workspace_name]
workspaceHistory= ws.getHistory()
histories = workspaceHistory.getAlgorithmHistories()
for history in histories:
name = history.name()
if name == 'Q1D' or name == 'Qxy':
isValid = True
break
if not isValid:
message = ("Workspace does not seem valid for zero error removal."
"It must have been reduced with Q1D or Qxy.")
return message, isValid
class AddOperation(object):
"""
The AddOperation allows to add two workspaces at a time.
"""
def __init__(self, is_overlay, time_shifts):
"""
The AddOperation requires to know if the workspaces are to
be plainly added or to be overlaid. Additional time shifts can be
specified
:param is_overlay :: true if the operation is an overlay operation
:param time_shifts :: a string with comma-separated time shift values
"""
super(AddOperation, self).__init__()
factory = CombineWorkspacesFactory()
self.adder = factory.create_add_algorithm(is_overlay)
self.time_shifter = TimeShifter(time_shifts)
def add(self, LHS_workspace, RHS_workspace, output_workspace, run_to_add, estimate_logs=False):
"""
Add two workspaces together and place the result into the outputWorkspace.
The user needs to specify which run is being added in order to determine
the correct time shift
:param LHS_workspace :: first workspace, this workspace is a reference workspace
and hence never shifted
:param RHS_workspace :: second workspace which can be shifted in time
:param output_workspace :: the output workspace name
:param run_to_add :: the number of the nth added workspace
:param estimate_logs :: bool. whether or not to estimate good values for bad proton charge logs.
Only applicable for Overlay. Default is False.
"""
current_time_shift = self.time_shifter.get_Nth_time_shift(run_to_add)
self.adder.add(LHS_workspace=LHS_workspace,
RHS_workspace=RHS_workspace,
output_workspace=output_workspace,
time_shift=current_time_shift,