forked from npshub/mantid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RunDescriptor.py
1837 lines (1611 loc) · 76.6 KB
/
RunDescriptor.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
#pylint: disable=attribute-defined-outside-init
""" File contains Descriptors used describe run for direct inelastic reduction """
from mantid.simpleapi import *
from mantid.dataobjects import *
from mantid.kernel import funcinspect
from Direct.PropertiesDescriptors import *
import re
import collections
class RunList(object):
"""Helper class to maintain list of runs used in RunDescriptor for summing
or subsequent processing range of files.
Supports basic operations with this list
"""
def __init__(self,theRumDescr,run_list,file_names=None,fext=None):
""" """
self._theRun = theRumDescr
self._last_ind2sum = -1
self._file_path = None
self._fext = None
self.set_list2add(run_list,file_names,fext)
self._partial_sum_ws_name = None
#
def set_list2add(self,runs_to_add,fnames=None,fext=None):
"""Set run numbers to add together with possible file guess-es """
if not isinstance(runs_to_add,list):
raise KeyError('Can only set list of run numbers to add')
runs = []
if fnames or len(fnames)>0:
fnames_given=True
local_fnames=fnames
else:
fnames_given=False
local_fnames=[]
if fext:
fext_given=True
local_fext=fext
else:
fext_given=False
local_fext=[]
for item in runs_to_add:
if isinstance(item, str):
file_path,run_num,fext = prop_helpers.parse_run_file_name(item)
runs.append(run_num)
if not fnames_given:
local_fnames.append(file_path)
if not fext_given:
if fext is not None:
if len(fext)==0:
fext=None
local_fext.append(fext)
else:
runs.append(int(item))
#pylint: disable=attribute-defined-outside-init
self._run_numbers = runs
self._set_fnames(local_fnames,local_fext)
#--------------------------------------------------------------------------------------------------
def set_cashed_sum_ws(self,ws,new_ws_name=None):
"""Store the name of a workspace in the class
as reference
"""
if new_ws_name:
old_name = ws.name()
if old_name != new_ws_name:
old_mon_name = old_name + '_monitors'
RenameWorkspace(ws,OutputWorkspace=new_ws_name)
if old_mon_name in mtd:
RenameWorkspace(old_mon_name,OutputWorkspace=new_ws_name + '_monitors')
else:
new_ws_name = ws.name()
self._partial_sum_ws_name = new_ws_name
#
def get_cashed_sum_ws(self):
"""Return python pointer to cached sum workspace
"""
if not self._partial_sum_ws_name:
return None
if self._partial_sum_ws_name in mtd:
return mtd[self._partial_sum_ws_name]
else:
return None
#
def get_cashed_sum_clone(self):
""" """
origin = self.get_cashed_sum_ws()
if not origin:
return None
origin_name = origin.name()
mon_name = origin_name + '_monitors'
if mon_name in mtd:
CloneWorkspace(InputWorkspace=mon_name,OutputWorkspace=origin_name + '_clone_monitors')
ws = CloneWorkspace(InputWorkspace=origin_name,OutputWorkspace=origin_name + '_clone')
return ws
#
def del_cashed_sum(self):
""" """
if not self._partial_sum_ws_name:
return
if self._partial_sum_ws_name in mtd:
DeleteWorkspace(self._partial_sum_ws_name)
mon_ws = self._partial_sum_ws_name + '_monitors'
if mon_ws in mtd:
DeleteWorkspace(mon_ws)
#--------------------------------------------------------------------------------------------------
#
def _set_fnames(self,fnames,fext):
"""Sets filenames lists and file extension lists
of length correspondent to run number length
if length of the list provided differs from the length
of the run list, expands fnames list and fext list
to the whole runnumber list using last for fext and
first for fnames members of the
"""
if fnames:
if isinstance(fnames,list):
self._file_path = fnames
else:
self._file_path = [fnames]
if not self._file_path:
self._file_path = [''] * len(self._run_numbers)
else:
if len(self._file_path) != len(self._run_numbers):
self._file_path = [self._file_path[0]] * len(self._run_numbers)
if fext:
if isinstance(fext,list):
self._fext = fext
else:
self._fext = [fext]
if not self._fext:
self._fext = [None] * len(self._run_numbers)
else:
if len(self._fext) != len(self._run_numbers):
base_fext = self._fext[-1]
self._fext = [base_fext] * len(self._run_numbers)
#
def get_fext(self,index=0):
"""Get file extension for file with run number
Should be used on defined Run_list only(which should be always true)
"""
fext_given =self._fext[index]
if fext_given is None:
#pylint: disable=protected-access
return self._theRun._holder.data_file_ext
else:
return fext_given
#
def get_file_guess(self,inst_name,run_num,index=None):
"""Return the name of run file for run number provided
Note: internal file extension overwrites
default_fext if internal is not empty
"""
if index is None:
index = self._run_numbers.index(run_num)
path_guess = self._file_path[index]
fext = self.get_fext(index)
guess = build_run_file_name(run_num,inst_name,path_guess,fext)
return (guess,index)
#
def get_run_file_list(self,inst_name):
"""Return list of files, used corresponding to runs"""
run_files = []
for ind,run in enumerate(self._run_numbers):
#pylint: disable=unused-variable
fname,index = self.get_file_guess(inst_name,run,ind)
run_files.append(fname)
return run_files
#
def get_all_run_list(self):
return self._run_numbers
#
def add_or_replace_run(self,run_number,fpath='',fext=None):
"""Add run number to list of existing runs
Let's prohibit adding the same run numbers using this method.
Equivalent run numbers can still be added using list assignment
file path and file extension are added/modified if present
regardless of run being added or replaced
"""
if run_number not in self._run_numbers:
self._run_numbers.append(run_number)
if not fpath:
fpath = self._file_path[-1]
self._file_path.append(fpath)
self._fext.append(fext)
self._last_ind2sum = len(self._run_numbers) - 1
return self._last_ind2sum
else:
ext_ind = self._run_numbers.index(run_number)
if len(fpath) > 0:
self._file_path[ext_ind] = fpath
if fext: #not to keep existing extension if new one is provided
self._fext[ext_ind] = fext
self._last_ind2sum = ext_ind
return ext_ind
#
def check_runs_equal(self,run_list,fpath=None,fext=None):
"""Returns true if all run numbers in existing list are
in the comparison list and vice versa.
if lists numbers coincide,
sets new file_path and fext list if such are provided
"""
if len(run_list) != len(self._run_numbers):
return False
for run in run_list:
if run not in self._run_numbers:
return False
self._set_fnames(fpath,fext)
return True
#
def get_current_run_info(self,sum_runs,ind=None):
"""Return last run info for file to sum"""
if ind:
if not(ind > -1 and ind < len(self._run_numbers)):
raise RuntimeError("Index {0} is outside of the run list of {1} runs".format(ind,len(self._run_numbers)))
else:
ind = self.get_last_ind2sum(sum_runs)
return self._run_numbers[ind],self._file_path[ind],self.get_fext(ind),ind
#
def set_last_ind2sum(self,run_number):
"""Check and set last number, contributing to summation
if this number is out of summation range, clear the summation
"""
run_number = int(run_number)
if run_number in self._run_numbers:
self._last_ind2sum = self._run_numbers.index(run_number)
else:
self._last_ind2sum = -1
#
def get_run_list2sum(self,num_to_sum=None):
"""Get run numbers of the files to be summed together
from the list of defined run numbers
"""
n_runs = len(self._run_numbers)
if num_to_sum:
if num_to_sum <= 0:
num_to_sum = 1
if num_to_sum > n_runs:
num_to_sum = n_runs
else:
num_to_sum = n_runs
if self._last_ind2sum >= 0 and self._last_ind2sum < num_to_sum:
num_to_sum = self._last_ind2sum + 1
return self._run_numbers[:num_to_sum]
#
def get_last_ind2sum(self,sum_runs):
"""Get last run number contributing to sum"""
if self._last_ind2sum >= 0 and self._last_ind2sum < len(self._run_numbers):
ind = self._last_ind2sum
else:
if sum_runs:
ind = len(self._run_numbers) - 1
else:
ind = 0
return ind
#
def sum_ext(self,sum_runs):
if sum_runs:
last = self.get_last_ind2sum(sum_runs)
sum_ext = "SumOf{0}".format(len(self._run_numbers[:last + 1]))
else:
sum_ext = ''
return sum_ext
#
def find_run_files(self,inst_name,run_list=None):
"""Find run files correspondent to the run list provided
and set path to these files as new internal parameters
for the files in list
Return the list of the runs, which files were
not found and found
Run list have to coincide or be part of self._run_numbers
No special check for correctness is performed, so may fail
miserably
"""
if not run_list:
run_list = self._run_numbers
not_found = []
found = []
for run in run_list:
file_hint,index = self.get_file_guess(inst_name,run)
try:
file_name = FileFinder.findRuns(file_hint)[0]
fpath,fname = os.path.split(file_name)
fname,fex = os.path.splitext(fname)
self._fext[index] = fex
self._file_path[index] = fpath
#self._last_ind2sum = index
found.append(run)
except RuntimeError:
not_found.append(run)
return not_found,found
#--------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------
#pylint: disable=too-many-instance-attributes
#pylint: disable=too-many-public-methods
#pylint: disable=attribute-defined-outside-init
class RunDescriptor(PropDescriptor):
"""Descriptor to work with a run or list of runs specified
either as run number (run file) or as
this run loaded in memory as a workspace
"""
# the host class referencing contained all instantiated descriptors.
# Descriptors methods rely on it to work (e.g. to extract file loader
# preferences)
# so it has to be set up manually by PropertyManager __init__ method
_holder = None
_logger = None
_sum_log_name = 'SumRuns'
#--------------------------------------------------------------------------------------------------------------------
def __init__(self,prop_name,DocString=None):
""" """
self._prop_name = prop_name
if DocString is not None:
self.__doc__ = DocString
self._ws_name = None
# pointer to workspace used to mask this workspace obtained at diag for
# this ws
self._mask_ws_name = None
self._clear_all()
def __len__(self):
"""overloaded len function, which
return length of the run-files list
to work with
"""
if not self._run_number:
return 0
if self._run_list:
#pylint: disable=protected-access
return len(self._run_list._run_numbers)
else:
return 1
#--------------------------------------------------------------------------------------------------------------------
def _clear_all(self):
"""clear all internal properties, workspaces and caches,
associated with this run
"""
# Run number
self._run_number = None
# Extension of the file to load data from
#
self._run_file_path = ''
self._fext = None
if self._ws_name:
mon_ws = self._ws_name + '_monitors'
# Workspace name which corresponds to the run
if self._ws_name in mtd:
DeleteWorkspace(self._ws_name)
if mon_ws in mtd:
DeleteWorkspace(mon_ws)
self._ws_name = None # none if not loaded
# String used to identify the workspace related to this property
# w.r.t. other workspaces
self._ws_cname = ''
self._ws_suffix = ''
# property contains run lists
self._run_list = None
#pylint: disable=attribute-defined-outside-init
self._in_cash = False
# clear masking workspace if any available
if self._mask_ws_name:
if self._mask_ws_name in mtd:
DeleteWorkspace(self._mask_ws_name)
self._mask_ws_name = None
#--------------------------------------------------------------------------------------------------------------------
def __get__(self,instance,owner):
"""Return current run number or workspace if it is loaded"""
if instance is None:
return self
if self._ws_name and self._ws_name in mtd:
return mtd[self._ws_name]
else:
return self._run_number
#--------------------------------------------------------------------------------------------------------------------
#pylint: disable=too-many-branches
def __set__(self,instance,value):
"""Set up Run number and define workspace name from any source """
#
if value is None: # clear current run number
self._clear_all()
return
if isinstance(value, api.Workspace):
if self._ws_name:
if self._ws_name != value.name():
self._clear_all()
self._set_ws_as_source(value)
else:
return # do nothing
# it is just reassigning the same workspace to itself
else: # first assignment of workspace to property
self._set_ws_as_source(value)
return
if isinstance(value, str): # it may be run number as string or it may be a workspace name
if value in mtd: # workspace name
ws = mtd[value]
self.__set__(instance,ws)
return
else: # split string into run indexes and auxiliary file parameters
file_path,run_num,fext = prop_helpers.parse_run_file_name(value)
if isinstance(run_num,list):
self._set_run_list(instance,run_num,file_path,fext)
else:
self._set_single_run(instance,run_num,file_path,fext)
elif isinstance(value, collections.Iterable): # xrange provided
value = list(value)
self._set_run_list(instance,value,"",None)
else:
self._set_single_run(instance,value,"",None)
#--------------------------------------------------------------------------------------------------------------------
def get_fext(self):
"""Return actual file extension for given run regardless of it
has been set or not
"""
if self._fext is None:
return self._holder.data_file_ext
else:
return self._fext
#--------------------------------------------------------------------------------------------------------------------
def _set_single_run(self,instance,run_number,file_path='',fext=None):
""" """
self._run_number = int(run_number)
# build workspace name for current run number
new_ws_name = self._build_ws_name()
if self._run_list and instance.sum_runs:
ind = self._run_list.add_or_replace_run(self._run_number,file_path,fext)
#pylint: disable=protected-access
self._run_file_path = self._run_list._file_path[ind]
#pylint: disable=protected-access
self._fext = self._run_list._fext[ind]
self._ws_name = new_ws_name
else:
if self._ws_name != new_ws_name:
self._clear_all()
# clear all would invalidate run number and workspace number
self._run_number = int(run_number)
self._ws_name = self._build_ws_name()
self._run_file_path = file_path
self._fext = fext
else: # nothing to do, there is workspace, which corresponds to this run number
# and it may be already loaded (may be not). Just nullify run list
# in case of previous workspace name came from a list.
self._run_list = None
if self._ws_name not in mtd:
# Change existing file path and file extension if alternatives are provided
if len(file_path)>0:
self._run_file_path = file_path
if fext is not None: # Change only if real new extension is provided
self._fext = fext
#--------------------------------------------------------------------------------------------------------------------
def _set_run_list(self,instance,run_list,file_path=None,fext=None):
if self._run_list and self._run_list.check_runs_equal(run_list,file_path,fext):
return
else:
self._clear_all()
self._run_list = RunList(self,run_list,file_path,fext)
run_num,file_path,main_fext,ind = self._run_list.get_current_run_info(instance.sum_runs)
self._run_list.set_last_ind2sum(ind)
self._run_number = run_num
self._run_file_path = file_path
if fext is None:
self._fext = None
else:
self._fext = main_fext
self._ws_name = self._build_ws_name()
def run_number(self):
"""Return run number regardless of workspace is loaded or not"""
if self._ws_name and self._ws_name in mtd:
ws = mtd[self._ws_name]
return ws.getRunNumber()
else:
return self._run_number
#--------------------------------------------------------------------------------------------------------------------
# Masking
#--------------------------------------------------------------------------------------------------------------------
def get_masking(self,noutputs=None):
"""Return masking workspace specific to this particular workspace
together with number of masked spectra if requested.
noutputs is provided as argument, as funcreturn does not propagate
through inheritance and overloaded functions
"""
if not noutputs:
try:
#pylint: disable=unused-variable
noutputs,r = funcinspect.lhs_info('both')
#pylint: disable=bare-except
except:
noutputs=0
if self._mask_ws_name:
if self._mask_ws_name in mtd:
mask_ws = mtd[self._mask_ws_name]
#TODO: need normal exposure of getNumberMasked() method of masks workspace
if noutputs>1:
__tmp_masks,spectra = ExtractMask(self._mask_ws_name)
num_masked = len(spectra)
DeleteWorkspace(__tmp_masks)
return (mask_ws,num_masked)
else:
return mask_ws
else:
self._mask_ws_name = None
if noutputs>1:
return (None,0)
else:
return None
#--------------------------------------------------------------------------------------------------------------------
def add_masked_ws(self,masked_ws):
"""Extract masking from the workspace provided and store masks
to use with this run workspace
"""
if self._mask_ws_name:
#pylint: disable=unused-variable
mask_ws = mtd[self._mask_ws_name]
add_mask_name = self._prop_name + '_tmp_masking'
else:
add_mask_name = self._prop_name + 'CurrentMasking'
#pylint: disable=unused-variable
masks,spectra = ExtractMask(InputWorkspace=masked_ws,OutputWorkspace=add_mask_name)
if self._mask_ws_name:
#pylint: disable=unused-variable
mask_ws +=masks
DeleteWorkspace(add_mask_name)
else:
self._mask_ws_name = add_mask_name
#
#--------------------------------------------------------------------------------------------------------------------
def is_monws_separate(self):
"""Is monitor workspace is separated from data workspace or not"""
try:
data_ws = self.get_workspace()
mon_ws = data_ws.getMonitorWorkspace()
return True
except:
pass
# lets go long but reliable way
mon_ws = self.get_monitors_ws()
if mon_ws:
name = mon_ws.name()
else:
return False
if name.endswith('_monitors'):
return True
else:
return False
#--------------------------------------------------------------------------------------------------------------------
def get_run_list(self):
"""Returns list of the files, assigned to current property """
current_run = self.run_number()
if self._run_list:
runs = self._run_list.get_all_run_list()
if current_run in runs:
return runs
else:
return [current_run]
else:
return [current_run]
#--------------------------------------------------------------------------------------------------------------------
def get_run_file_list(self):
"""Returns list of the files, assigned to current property """
inst = RunDescriptor._holder.short_inst_name
fext = self.get_fext()
run_num = self.run_number()
current_run = build_run_file_name(run_num,inst,self._run_file_path,fext)
if self._run_list:
runs = self._run_list.get_all_run_list()
if run_num in runs:
runf = self._run_list.get_run_file_list(inst)
return runf
else:
return [current_run]
else:
return [current_run]
#--------------------------------------------------------------------------------------------------------------------
@staticmethod
def get_sum_run_list(ws):
"""Retrieve list of contributed run numbers from the sum workspace log"""
summed_runs = []
if RunDescriptor._sum_log_name in ws.getRun():
summed_str = ws.getRun().getLogData(RunDescriptor._sum_log_name).value
run_nums = summed_str.split(',')
for run_str in run_nums:
summed_runs.append(int(run_str))
else:
raise RuntimeError("Presumably sum workspace {0} does not have sum log attached to it".format(ws.name()))
return summed_runs
#--------------------------------------------------------------------------------------------------------------------
def get_runs_to_sum(self,existing_sum_ws=None,num_files=None):
"""Return list of runs, expected to be summed together
excluding the runs, already summed and added to cached sum workspace
"""
if not RunDescriptor._holder.sum_runs:
return ([],None,0)
if not self._run_list:
return ([],None,0)
#
summed_runs = []
if not existing_sum_ws:
existing_sum_ws = self._run_list.get_cashed_sum_ws()
if existing_sum_ws:
summed_runs = RunDescriptor.get_sum_run_list(existing_sum_ws)
n_existing_sums = len(summed_runs)
runs2_sum = self._run_list.get_run_list2sum(num_files)
for run in summed_runs:
if run in runs2_sum:
del runs2_sum[runs2_sum.index(run)]
return (runs2_sum,existing_sum_ws,n_existing_sums)
#--------------------------------------------------------------------------------------------------------------------
def find_run_files(self,run_list=None):
"""Find run files correspondent to the run list provided
and set path to these files as new internal parameters
for the files in the list
Returns True and empty list or False and
the list of the runs, which files were not found
or not belong to the existing run list.
"""
if not self._run_list:
if not run_list:
return (True,[],[])
else:
return (False,run_list,[])
if run_list:
existing = self._run_list.get_all_run_list()
for run in run_list:
if run not in existing:
raise RuntimeError('run {0} is not in the existing run list'.format(run))
not_found=[]
found = []
inst = RunDescriptor._holder.short_instr_name
not_found,found = self._run_list.find_run_files(inst,run_list)
if len(not_found) == 0:
Ok = True
else:
Ok = False
return (Ok,not_found,found)
#--------------------------------------------------------------------------------------------------------------------
def set_action_suffix(self,suffix=None):
"""Method to set part of the workspace name, which indicate some action performed over this workspace
e.g.: default suffix of a loaded workspace is 'RAW' but we can set it to SPE to show that conversion to
energy will be performed for this workspace.
method returns the name of the workspace is will have with this suffix.
Algorithms would later work on the initial workspace and modify it in-place or to produce workspace
with new name (depending if one wants to keep initial workspace)
synchronize_ws(ws_pointer) then should synchronize workspace and its name.
TODO: This method should be automatically invoked by an algorithm decorator
Until implemented, one have to ensure that it is correctly used together with synchronize_ws
to ensue one can always get workspace from its name
"""
if suffix:
self._ws_suffix = suffix
else: # return to default
self._ws_suffix = ''
return self._build_ws_name()
#--------------------------------------------------------------------------------------------------------------------
def synchronize_ws(self,workspace=None,new_ws_name = None):
"""Synchronize workspace name (after workspace may have changed due to algorithm)
with internal run holder name. Accounts for the situation when
TODO: This method should be automatically invoked by an algorithm decorator
Until implemented, one have to ensure that it is correctly used together with
set_action_suffix to ensue one can always get expected workspace from its name
outside of a method visibility
"""
if not workspace:
workspace = mtd[self._ws_name]
if new_ws_name:
new_name = new_ws_name
else:
new_name = self._build_ws_name()
old_name = workspace.name()
if new_name != old_name:
# Compatibility with old test code comes here:
try:
mon_ws = workspace.getMonitorWorkspace()
except RuntimeError: # Its possible that monitor workspace for some reason was not attached
mon_ws_name = old_name + '_monitors' # to current workspace
if mon_ws_name in mtd:
mon_ws = mtd[mon_ws_name]
workspace.setMonitorWorkspace(mon_ws)
RenameWorkspace(InputWorkspace=old_name,OutputWorkspace=new_name,RenameMonitors=True)
self._ws_name = new_name
return mtd[new_name]
#--------------------------------------------------------------------------------------------------------------------
@staticmethod
def _check_calibration_source():
"""If user have not specified calibration as input to the script,
try to retrieve calibration stored in file with run properties"""
changed_prop = RunDescriptor._holder.getChangedProperties()
if 'det_cal_file' in changed_prop:
use_workspace_calibration = False
else:
use_workspace_calibration = True
return use_workspace_calibration
#--------------------------------------------------------------------------------------------------------------------
def get_workspace(self):
"""Method returns workspace correspondent to current run number(s)
and loads this workspace if it has not been loaded
Returns Mantid pointer to the workspace, corresponding to this run number
"""
if not self._ws_name:
self._ws_name = self._build_ws_name()
if self._ws_name in mtd:
ws = mtd[self._ws_name]
if not ws.run().hasProperty("calibrated"):
prefer_ws_calibration = self._check_calibration_source()
self.apply_calibration(ws,RunDescriptor._holder.det_cal_file,prefer_ws_calibration)
return ws
else:
if self._run_number is not None:
prefer_ws_calibration = self._check_calibration_source()
inst_name = RunDescriptor._holder.short_inst_name
calibration = RunDescriptor._holder.det_cal_file
if self._run_list and RunDescriptor._holder.sum_runs : # Sum runs
ws = self._load_and_sum_runs(inst_name,RunDescriptor._holder.load_monitors_with_workspace)
else: # load current workspace
ws = self.load_run(inst_name, calibration,False,
RunDescriptor._holder.load_monitors_with_workspace,prefer_ws_calibration)
self.synchronize_ws(ws)
self.apply_calibration(ws,calibration,prefer_ws_calibration)
return ws
else:
return None
#--------------------------------------------------------------------------------------------------------------------
def get_ws_clone(self,clone_name='ws_clone'):
"""Get unbounded clone of existing Run workspace"""
ws = self.get_workspace()
CloneWorkspace(InputWorkspace=ws,OutputWorkspace=clone_name)
mon_ws_name = ws.name() + '_monitors'
if mon_ws_name in mtd:
cl_mon_name = clone_name + '_monitors'
CloneWorkspace(InputWorkspace=mon_ws_name,OutputWorkspace=cl_mon_name)
return mtd[clone_name]
#--------------------------------------------------------------------------------------------------------------------
def _set_ws_as_source(self,value):
"""Assign all parts of the run if input value is workspace"""
self._run_number = value.getRunNumber()
ws_name = value.name()
self._ws_suffix = ''
self._split_ws_name(ws_name)
self.synchronize_ws(value)
#--------------------------------------------------------------------------------------------------------------------
#pylint: disable=too-many-arguments,redefined-outer-name
def chop_ws_part(self,origin,tof_range,rebin,chunk_num,n_chunks):
"""Chop part of the original workspace and sets it up to this run as new original.
Return the pointer to the original workspace (the chunk has been taken) if the
chunk is not the last one, or pointer to last chunk if the last chunk was taken
(original workspace was destroyed in this case)
"""
if not origin:
origin = self.get_workspace()
origin_name = origin.name()
# Check separate monitor's ws, attached to origin workspace (not to runWorkspace)
try:
mon_ws = origin.getMonitorWorkspace()
except RuntimeError:
mon_ws_name = origin_name+'_monitors'
if mon_ws_name in mtd:
mon_ws = mtd[mon_ws_name]
origin.setMonitorWorkspace(mon_ws)
else: # may be monitors are stored together with ws. We can not chop it
# so only way ahead is: TODO: Its possible to perform better here (take only monitors)
mon_ws = CloneWorkspace(InputWorkspace=origin_name,OutputWorkspace=origin_name + '_monitors')
origin.setMonitorWorkspace(mon_ws)
#
target_name = '#{0}/{1}#'.format(chunk_num,n_chunks) + origin_name
if chunk_num == n_chunks:
RenameWorkspace(InputWorkspace=origin_name,OutputWorkspace=target_name,RenameMonitors=True)
origin_name = target_name
else:
if mon_ws:
mon_ws = CloneWorkspace(InputWorkspace=mon_ws,OutputWorkspace=target_name + '_monitors')
if rebin: # debug and compatibility mode with old reduction
target=Rebin(origin_name,OutputWorkspace=target_name,Params=[tof_range[0],tof_range[1],tof_range[2]],PreserveEvents=False)
# Rebin in place does not conserves mon_ws?
origin_deleted = True
else:
target = CropWorkspace(origin_name,OutputWorkspace=target_name,XMin=tof_range[0],XMax=tof_range[2])
if origin_name == target_name:
origin_deleted = True
else:
origin_deleted = False
if mon_ws:
target.setMonitorWorkspace(mon_ws)
self._set_ws_as_source(mtd[target_name])
if origin_deleted:
return self.get_workspace()
else:
return mtd[origin_name]
#--------------------------------------------------------------------------------------------------------------------
#pylint: disable=too-many-branches
def get_monitors_ws(self,monitors_ID=None,otherWS=None):
"""Get pointer to a workspace containing monitors.
Explores different ways of finding monitor workspace in Mantid and returns the python pointer to the
workspace which contains monitors.
"""
if otherWS:
data_ws = otherWS
else:
data_ws = self.get_workspace()
if not data_ws:
return None
mon_ws = self.get_monitor_workspace(data_ws)
if mon_ws is None:
monitors_separate = False
mon_ws = data_ws
else:
monitors_separate = True
spec_to_mon = RunDescriptor._holder.spectra_to_monitors_list
combined_spec_list = prop_helpers.process_prop_list(mon_ws,"CombinedSpectraIDList")
if monitors_separate and spec_to_mon:
for specID in spec_to_mon:
if specID not in combined_spec_list:
mon_ws = self.copy_spectrum2monitors(data_ws,mon_ws,specID)
if mon_ws:
#mon_ws=mtd[mon_ws_name] # very weird operation needed
data_ws.setMonitorWorkspace(mon_ws)
if monitors_ID:
def flatten_list(targ_list,source):
if isinstance(source, collections.Iterable):
for item in source:
targ_list = flatten_list(targ_list,item)
else:
targ_list.append(source)
return targ_list
if isinstance(monitors_ID, collections.Iterable):
mon_list = []
mon_list = flatten_list(mon_list,monitors_ID)
else:
mon_list = [monitors_ID]
else:
mon_list = self._holder.get_used_monitors_list()
# Check if all requested spectra are indeed available
for monID in mon_list:
if monID in combined_spec_list:
continue
try:
mon_ws.getIndexFromSpectrumNumber(int(monID))
#pylint: disable=bare-except
except:
try:
monws_name = mon_ws.name()
#pylint: disable=bare-except
except:
monws_name = 'None'
RunDescriptor._logger('*** Monitor workspace {0} does not have spectra with ID {1}. Monitor workspace set to None'.
format(monws_name,monID),'warning')
mon_ws = None
break
return mon_ws
#--------------------------------------------------------------------------------------------------------------------
def get_monitor_workspace(self, data_ws):
mon_ws = None
try:
mon_ws = data_ws.getMonitorWorkspace()
except RuntimeError: # May be old code or some problem connecting workspace with monitor workspace
ws_name = data_ws.name()
mon_ws_name = ws_name+'_monitors'
if mon_ws_name in mtd:
mon_ws = mtd[mon_ws_name]
data_ws.setMonitorWorkspace(mon_ws) # connect workspace and monitors together
return mon_ws
#--------------------------------------------------------------------------------------------------------------------
def is_existing_ws(self):
"""Method verifies if property value relates to workspace, present in ADS"""
if self._ws_name:
if self._ws_name in mtd:
return True
else:
return False
else:
return False
#--------------------------------------------------------------------------------------------------------------------
def set_file_ext(self,val):
"""Set non-default file extension """
if isinstance(val, str):
if val[0] != '.':
value = '.' + val
else:
value = val
self._fext = value
else:
raise AttributeError('Source file extension can be only a string')