forked from npshub/mantid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PropertiesDescriptors.py
1819 lines (1514 loc) · 66.9 KB
/
PropertiesDescriptors.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
""" File contains collection of Descriptors used to define complex
properties in NonIDF_Properties and PropertyManager classes
"""
import os
import numpy as np
import math
import re
from collections import Iterable
import mantid.simpleapi as mantid
from mantid import api
import Direct.ReductionHelpers as prop_helpers
from Direct.AbsorptionShapes import *
import collections
# -----------------------------------------------------------------------------------------
# Descriptors, providing overloads for complex properties in NonIDF_Properties
# class
# -----------------------------------------------------------------------------------------
class PropDescriptor(object):
"""Class provides common custom interface for property descriptors """
def dependencies(self):
"""Returns the list of other properties names, this property depends on"""
return []
# pylint: disable=unused-argument
def validate(self, instance, owner):
"""Interface to validate property descriptor,
provided to check properties interaction before long run
Return validation result, errors severity (0 -- fine, 1 -- warning, 2-- error)
and error message if any
"""
return (True, 0, '')
# end PropDescriptor
# -----------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------
class SumRuns(PropDescriptor):
"""Boolean property specifies if list of files provided as input for sample_run property
should be summed.
"""
def __init__(self, sample_run_prop):
# internal reference to sample run property
self._sample_run = sample_run_prop
# class containing this property
#
self._sum_runs = False
#
def __get__(self, instance, holder_class):
if instance is None:
return self
return self._sum_runs
#
def __set__(self, instance, value):
old_value = self._sum_runs
if isinstance(value, bool):
self._sum_runs = value
elif isinstance(value, int):
if value > 0:
self._sum_runs = True
else:
self._sum_runs = False
else:
self._sum_runs = bool(value)
#
if old_value != self._sum_runs:
self._sample_run.notify_sum_runs_changed(old_value, self._sum_runs)
# --------------------------------------------------------------------------------------------------------------------
class AvrgAccuracy(PropDescriptor):
"""Property-helper to round-of data nicely to provide consistent binning
in auto-ei mode.
"""
def __init__(self):
self._accuracy = 2
def __get__(self, instance, owner=None):
""" return current number of significant digits"""
if instance is None:
return self
else:
return self._accuracy
def __set__(self, instance, value):
""" Set up incident energy or range of energies in various formats
or define autoEi"""
val = int(value)
if val < 1:
raise ValueError("Averaging accuracy can be only a positive number >= 1")
self._accuracy = val
def roundoff(self, value):
"""Round specified sequence for specified number of significant digits"""
if isinstance(value, Iterable):
vallist = value
else:
vallist = [value]
rez = []
lim = 10 ** (self._accuracy - 1)
def out(a, b, mult):
if mult > 1:
return a < b
else:
return False
for val in vallist:
if abs(val) > lim:
rez.append(round(val, 0))
continue
elif abs(val) < lim:
mult = 10
else:
mult = 1
tv = abs(val)
fin_mult = 1
while out(tv, lim, mult):
fin_mult *= mult
tv *= mult
fin_rez = math.copysign(round(tv, 0) / fin_mult, val)
rez.append(fin_rez)
if len(rez) == 1:
return rez[0]
else:
return rez
# --------------------------------------------------------------------------------------------------------------------
class IncidentEnergy(PropDescriptor):
"""Provide incident energy or range of incident energies to be processed.
Set it up to list of values (even with single value i.e. prop_man.incident_energy=[10]),
if the energy_bins property value to be treated as relative energy ranges.
Set it up to single value (e.g. prop_man.incident_energy=10) to treat energy_bins
as absolute energy values.
"""
def __init__(self):
self._incident_energy = 0
self._num_energies = 1
self._cur_iter_en = 0
# Properties related to autoEi
self._use_autoEi = False
self._autoEiRunNumber = None
self._autoEiCalculated = False
def __get__(self, instance, owner=None):
""" return incident energy or list of incident energies """
if instance is None:
return self
if self._use_autoEi:
return 'AUTO'
else:
return self._incident_energy
# pylint: disable=too-many-branches
def __set__(self, instance, value):
""" Set up incident energy or range of energies in various formats
or define autoEi"""
if value is not None:
if isinstance(value, str):
# Check autoEi
if value.lower() == 'auto':
self._use_autoEi = True
currentRun = instance.sample_run
if isinstance(currentRun, api.Workspace):
currentRun = currentRun.getRunNumber()
if currentRun != self._autoEiRunNumber or currentRun is None:
self._autoEiRunNumber = currentRun
self._autoEiCalculated = False
self._incident_energy = 0
self._cur_iter_en = 0
return
# Ei in string form is provided
else:
if value.find('[') > -1:
energy_list = True
value = value.replace('[', '').replace(']', '').strip()
else:
energy_list = False
en_list = value.split(',')
if len(en_list) > 1:
rez = []
for en_str in en_list:
val = float(en_str)
rez.append(val)
self._incident_energy = rez
else:
if energy_list:
self._incident_energy = [float(value)]
else:
self._incident_energy = float(value)
else:
if isinstance(value, list):
rez = []
for val in value:
en_val = float(val)
if en_val <= 0:
raise KeyError("Incident energy has to be positive, but is: {0} ".format(en_val))
else:
rez.append(en_val)
self._incident_energy = rez
else:
self._incident_energy = float(value)
else:
raise KeyError("Incident energy have to be positive number of list of positive numbers. Got None")
# here we have set specific energy or range of incident energies
self._use_autoEi = False
if isinstance(self._incident_energy, list):
self._num_energies = len(self._incident_energy)
else:
self._num_energies = 1
self._cur_iter_en = 0
# pylint: disable=unused-variable
ok, sev, message = self.validate(instance)
if not ok:
raise KeyError(message)
#
def autoEi_mode(self):
"""Return true if energies should be calculated in autoEi mode"""
return self._use_autoEi
#
def multirep_mode(self):
""" return true if energy is defined as list of energies or multirep m and false otherwise """
if isinstance(self._incident_energy, list) or self._use_autoEi:
return True
else:
return False
#
def getAllEiList(self):
"""Return incident energy(ies) range, defined by the property"""
if isinstance(self._incident_energy, list):
return self._incident_energy
else:
if self._incident_energy == 0:
return []
else:
return [self._incident_energy]
#
def get_current(self):
""" Return current energy out of range of energies"""
if isinstance(self._incident_energy, list):
ind = self._cur_iter_en
return self._incident_energy[ind]
else:
return self._incident_energy
#
# Python 3 compatibility
def __next__(self):
return self.next()
def next(self):
if isinstance(self._incident_energy, list):
self._cur_iter_en += 1
if self._cur_iter_en >= len(self._incident_energy):
raise StopIteration
else:
raise StopIteration
#
def set_current_ind(self, ind=None):
""" set current energy value (used in multirep mode) as
energy estimate for the reduction
ind -- if provided, the number of the value in the list of
values (can be used together with enumerate)
"""
if isinstance(self._incident_energy, list):
if ind is None:
self._cur_iter_en = 0
else:
if ind > len(self._incident_energy):
raise IndexError("Index exceed number of energies")
self._cur_iter_en = ind
else:
self._cur_iter_en = 0
#
def set_auto_Ei(self, monitor_ws, instance, ei_mon_spec=None):
"""Calculate autoEi and set it as input for iterations over energy"""
if not self._use_autoEi:
return
newRunNum = monitor_ws.getRunNumber()
if self._autoEiCalculated and newRunNum == self._autoEiRunNumber:
return
# Calculate autoEi
self._autoEiCalculated = False
if ei_mon_spec is None:
ei_mon_spec = instance.ei_mon_spectra
guess_ei_ws = GetAllEi(
Workspace=monitor_ws, Monitor1SpecID=ei_mon_spec[0],
Monitor2SpecID=ei_mon_spec[1])
guessEi = guess_ei_ws.readX(0)
fin_ei = []
for ei in guessEi:
try:
ei_ref, _, _, _ = GetEi(InputWorkspace=monitor_ws,
Monitor1Spec=ei_mon_spec[0], Monitor2Spec=ei_mon_spec[1],
EnergyEstimate=ei)
fin_ei.append(ei_ref)
# pylint: disable=bare-except
except:
instance.log("Can not refine guess energy {0:f}. Ignoring it.".format(ei), 'warning')
if len(fin_ei) == 0:
raise RuntimeError("Was not able to identify auto-energies for workspace: {0}".format(monitor_ws.name()))
# Success! Set up estimated energies
self._autoEiCalculated = True
self._autoEiRunNumber = newRunNum
self._incident_energy = fin_ei
self._num_energies = len(fin_ei)
self._cur_iter_en = 0
# Clear dataservice from unnecessary workspace
DeleteWorkspace(guess_ei_ws)
def validate(self, instance, owner=None):
#
if self._use_autoEi: # nothing much to validate. The ei will be auto if possible
return (True, 0, '')
inc_en = self._incident_energy
if isinstance(inc_en, list):
for ind, en in enumerate(inc_en):
if en <= 0:
return (False, 2, "Incident energy have to be positive number or list of positive numbers.\n"
"For input argument {0} got negative energy {1}".format(ind, en))
else:
if inc_en <= 0:
return (False, 2, "Incident energy have to be positive number or list of positive numbers.\n"
"Got single negative incident energy {0} ".format(inc_en))
return (True, 0, '')
# end IncidentEnergy
# -----------------------------------------------------------------------------------------
class EnergyBins(PropDescriptor):
"""Energy binning, expected in final converted to energy transfer workspace.
Provide it in the form:
propman.energy_bins = [min_energy,step,max_energy]
if energy to process (incident_energy property) has a single value,
or
propman.energy_bins = [min_rel_enrgy,rel_step,max_rel_energy]
where all values are relative to the incident energy,
if energy(ies) to process (incident_energy(ies)) are list of energies.
The list of energies can contain only single value.
(e.g. prop_man.incident_energy=[100])/
"""
def __init__(self, IncidentEnergyProp, AccuracyProp):
self._incident_energy = IncidentEnergyProp
self._averager = AccuracyProp
self._energy_bins = None
# how close you are ready to rebin w.r.t. the incident energy
self._range = 0.99999
def __get__(self, instance, owner=None):
"""Binning range for the result of convertToenergy procedure or list of such ranges"""
if instance is None:
return self
return self._energy_bins
def __set__(self, instance, values):
if values is not None:
if isinstance(values, str):
values = values.replace('[', '').replace(']', '').strip()
lst = values.split(',')
self.__set__(instance, lst)
return
else:
value = values
if len(value) != 3:
raise KeyError(
"Energy_bin value has to be a tuple of 3 elements or string of 3 comma-separated numbers")
value = (float(value[0]), float(value[1]), float(value[2]))
else:
value = None
# TODO: implement single value settings according to rebin?
self._energy_bins = value
def get_abs_range(self, instance=None):
""" return energies related to incident energies.
"""
if self._incident_energy.multirep_mode(): # Relative energy
ei = self._incident_energy.get_current()
if self._incident_energy.autoEi_mode():
# we need to average ei nicely, as it will give energy jitter otherwise
ei = self._averager.roundoff(ei)
if self._energy_bins:
if self.is_range_valid():
rez = self._calc_relative_range(ei)
else:
if instance:
instance.log("*** WARNING! Got energy_bins specified as absolute values in multirep mode.\n"
" Will normalize these values by max value and treat as relative values",
"warning")
mult = self._range / self._energy_bins[2]
rez = self._calc_relative_range(ei, mult)
if self._incident_energy.autoEi_mode():
rez = self._averager.roundoff(rez)
return rez
else:
return None
else: # Absolute energy ranges
if self.is_range_valid():
return self._energy_bins
else:
if instance:
instance.log("*** WARNING! Requested maximum binning range exceeds incident energy!\n"
" Will normalize binning range by max value and treat as relative range",
"warning")
mult = self._range / self._energy_bins[2]
ei = self._incident_energy.get_current()
return self._calc_relative_range(ei, mult)
def is_range_valid(self):
"""Method verifies if binning range is consistent with incident energy """
if self._incident_energy.multirep_mode():
return self._energy_bins[2] <= self._range
else:
return self._energy_bins[2] <= self._incident_energy.get_current()
def _calc_relative_range(self, ei, range_mult=1):
""" """
mult = range_mult * ei
return (self._energy_bins[0] * mult, self._energy_bins[1] * mult, self._energy_bins[2] * mult)
def validate(self, instance, owner):
""" function verifies if the energy binning is consistent with incident energies """
ei = instance.incident_energy
ebin = instance.energy_bins
if isinstance(ei, list) or owner.incident_energy.autoEi_mode(): # ebin expected to be relative
if ebin[2] > 1:
return (False, 1,
"Binning for multiple energy range should be relative to incident energy. Got ebin_max={0} > 1\n"
+ "Energy range will be normalized and treated as relative range")
else:
if not owner.incident_energy.autoEi_mode() and ebin[2] > ei:
return (False, 2, 'Max rebin range {0:f} exceeds incident energy {1:f}'.format(ebin[2], ei))
return (True, 0, '')
# -----------------------------------------------------------------------------------------
# end EnergyBins
# -----------------------------------------------------------------------------------------
class SaveFileName(PropDescriptor):
"""Property defines default file name to save result.
By default the name is calculated from incident energy, run number and
other properties values, but user can assign its own name, which will be
used instead.
"""
def __init__(self, Name=None):
self._file_name = Name
self._custom_print = None
def __get__(self, instance, owner=None):
# getter functional interface.
if instance is None:
return self
# if custom file name provided, use it
if self._file_name:
return self._file_name
# if custom function to generate file name is proivede, use this function
if self._custom_print is not None:
return self._custom_print()
# user provided nothing.
# calculate default target file name from
# instrument, energy and run number.
if instance.instr_name:
name = instance.short_inst_name
else:
name = '_EMPTY'
sr = owner.sample_run.run_number()
if not sr:
sr = 0
try:
ei = owner.incident_energy.get_current()
name += '{0:0<5}Ei{1:_<4.2f}meV'.format(sr, ei)
if instance.sum_runs:
name += 'sum'
if owner.monovan_run.run_number():
name += '_Abs'
name = name.replace('.', 'd')
# pylint: disable=bare-except
except:
name = None
return name
def __set__(self, instance, value):
if value is None:
self._file_name = None
elif isinstance(value, collections.Callable):
self._custom_print = value
else:
self._file_name = str(value)
def set_custom_print(self, routine):
self._custom_print = routine
# end SaveFileName
# -----------------------------------------------------------------------------------------
class InstrumentDependentProp(PropDescriptor):
"""Generic property describing some aspects of instrument (e.g. name, short name etc),
which are undefined if no instrument is defined.
"""
def __init__(self, prop_name):
self._prop_name = prop_name
def __get__(self, instance, owner=None):
if instance is None:
return self
# pylint: disable=protected-access
if instance._pInstrument is None:
raise KeyError("Attempt to use uninitialized property manager")
else:
return getattr(instance, self._prop_name)
def __set__(self, instance, values):
raise AttributeError("Property {0} can not be assigned. It defined by instrument".format(self._prop_name))
# end InstrumentDependentProp
# -----------------------------------------------------------------------------------------
class VanadiumRMM(PropDescriptor):
"""Defines constant static rmm for vanadium."""
def __get__(self, instance, owner=None):
""" return rmm for vanadium """
return 50.9415
def __set__(self, instance, value):
raise AttributeError("Can not change vanadium rmm")
# end VanadiumRMM
# -----------------------------------------------------------------------------------------
# END Descriptors for NonIDF_Properties class
# -----------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------
# Descriptors, providing overloads for some complex properties in
# PropertyManager
# -----------------------------------------------------------------------------------------
class mon2NormalizationEnergyRange(PropDescriptor):
"""Energy range to integrate signal on monitor 2 when normalized by this monitor.
This class contains relative range of energies in which the monitor-2 signal should
be integrated, and returns the energy range for integration according to
formula: range = [min_range*ei,max_range*ei] where ei is incident monitor energy.
To find the actual integration ranges one should convert these values into TOF (or
convert monitor signal to energy).
"""
def __init__(self):
# default range
self._relative_range = [0.8, 1.2]
def __get__(self, instance, owner):
""" Return actual energy range from internal relative range and incident energy """
if instance is None:
return self
ei = owner.incident_energy.get_current()
return [self._relative_range[0] * ei, self._relative_range[1] * ei]
def __set__(self, instance, val):
""" set detector calibration file using various formats """
if isinstance(val, list):
self._relative_range = self._check_range(val, instance)
elif isinstance(val, str):
val = self._parce_string2list(val)
self.__set__(instance, val)
else:
raise KeyError('mon2_norm_energy_range needs to be initialized by two values.\n'
'Trying to assign value {0} of unknown type {1}'.format(val, type(val)))
#
def _check_range(self, val, instance):
""" method to check if list of values acceptable as ranges """
if len(val) != 2:
raise KeyError(
"mon2_norm_energy_range needs to be initialized by lost of two values. Got {0}".format(len(val)))
self._relative_range = (float(val[0]), float(val[1]))
ok, sev, message = self.validate(instance)
if not ok:
if sev == 1:
instance.log(message, 'warning')
else:
raise KeyError(message)
return self._relative_range
#
def _parce_string2list(self, val):
""" method splits input string containing comma into list of strings"""
value = val.strip('[]()')
val = value.split(',')
return val
def validate(self, instance, owner=None):
""" function verifies if the energy range is consistent with incident energies """
en_range = self._relative_range
if len(en_range) != 2:
return (False, 2, 'mon2_normalization_energy_range can be initialized by list of two values only.'
' Got {0} values'.format(len(range)))
result = (True, 0, '')
val1 = float(en_range[0])
if val1 < 0.1 or val1 > 0.9:
message = "Lower mon2_norm_energy_range describes lower limit of energy to integrate neutron signal after" \
" the chopper.\nThe limit is defined as (this value)*incident_energy." \
" Are you sure you want to set this_value to {0}?\n".format(val1)
if val1 > 1:
return (False, 2, message)
else:
result = (False, 1, message)
val2 = float(en_range[1])
if val2 < 1.1 or val2 > 1.9:
message = "Upper mon2_norm_energy_range describes upper limit of energy to integrate neutron signal after" \
" the chopper.\nThe limit is defined as (this value)*incident_energy." \
" Are you sure you want to set this_value to {0}?\n".format(val2)
if val2 > 1:
if result[0]:
result = (False, 1, message)
else:
result = (False, 1, result[2] + message)
else:
return (False, 2, message)
return result
# -----------------------------------------------------------------------------------------
class PropertyFromRange(PropDescriptor):
"""Generic descriptor for property, which can have one value from a list of values."""
def __init__(self, availible_values, default_value):
self._availible_values = availible_values
self.__set__(None, default_value)
def __get__(self, instance, owner):
""" Return current value for the property with range of values. """
if instance is None:
return self
return self._current_value
def __set__(self, instance, val):
if val in self._availible_values:
# pylint: disable=attribute-defined-outside-init
self._current_value = val
else:
raise KeyError(' Property can not have value {0}'.format(val))
# -----------------------------------------------------------------------------------------
class DetCalFile(PropDescriptor):
"""Provide a source of the detector calibration information.
A source can be a file, present on a data search path, a workspace
or a run number, corresponding to a file to be loaded as a
workspace.
"""
def __init__(self):
self._det_cal_file = None
self._calibrated_by_run = False
def __get__(self, instance, owner):
if instance is None:
return self
return self._det_cal_file
def __set__(self, instance, val):
""" set detector calibration file using various formats """
if val is None or isinstance(val, api.Workspace):
# nothing provided or workspace provided or filename probably provided
if str(val) in mantid.mtd:
# workspace name provided
val = mantid.mtd[str(val)]
self._det_cal_file = val
self._calibrated_by_run = False
return
if isinstance(val, str):
if val in mantid.mtd:
val = mantid.mtd[val]
self._det_cal_file = val
self._calibrated_by_run = False
return
try:
intVal = int(val)
except ValueError:
self._det_cal_file = val
self._calibrated_by_run = False
return
val = intVal
if isinstance(val, int):
# if val in instance.all_run_numbers: TODO: retrieve workspace from
# run numbers
self._det_cal_file = val
self._calibrated_by_run = True
return
raise NameError(
'Detector calibration file name can be a workspace name present in Mantid or string describing an file name')
# if Reducer.det_cal_file != None :
# if isinstance(Reducer.det_cal_file,str) and not Reducer.det_cal_file
# in mtd : # it is a file
# Reducer.log('Setting detector calibration file to
# '+Reducer.det_cal_file)
# else:
# Reducer.log('Setting detector calibration to {0}, which is probably
# a workspace '.format(str(Reducer.det_cal_file)))
# else:
# Reducer.log('Setting detector calibration to detector block info from
# '+str(sample_run))
def calibrated_by_run(self):
""" reports if the detector calibration is in a run-file or separate file(workspace)"""
return self._calibrated_by_run
# pylint: disable=unused-argument
def find_file(self, instance, **kwargs):
""" Method to find file, correspondent to
current _det_cal_file file hint
"""
if self._det_cal_file is None:
# nothing to look for
return (True, "No Detector calibration file defined")
if isinstance(self._det_cal_file, api.Workspace):
# nothing to do. Workspace used for calibration
return (True, 'Workspace {0} used for detectors calibration'.format(self._det_cal_file.name()))
dcf_val = self._det_cal_file
if isinstance(dcf_val, str): # it may be string representation of runN
try:
dcf_val = int(dcf_val)
except ValueError:
pass
if isinstance(dcf_val, int): # this is a run number
inst_short_name = instance.short_inst_name
fac = instance.facility
zero_padding = fac.instrument(inst_short_name).zeroPadding(dcf_val)
file_hint = inst_short_name + str(dcf_val).zfill(zero_padding)
try:
file_name = mantid.FileFinder.findRuns(file_hint)[0]
# pylint: disable=bare-except
except:
return (False, "Can not find run file corresponding to run N: {0}".format(file_hint))
self._det_cal_file = file_name
return (True, file_name)
# string can be a run number or a file name:
file_name = prop_helpers.findFile(self._det_cal_file)
if len(file_name) == 0: # it still can be a run number as string
try:
file_name = mantid.FileFinder.findRuns(self._det_cal_file)[0]
# pylint: disable=bare-except
except:
return (False, "Can not find file or run file corresponding to name : {0}".format(self._det_cal_file))
else:
pass
self._det_cal_file = file_name
return (True, file_name)
# end DetCalFile
# -----------------------------------------------------------------------------------------
class MapMaskFile(PropDescriptor):
"""common method to wrap around an auxiliary file name"""
def __init__(self, prop_name, file_ext, doc_string=None):
self._file_name = None
self._file_ext = file_ext
self._prop_name = prop_name
if doc_string is not None:
self.__doc__ = doc_string
def __get__(self, instance, class_type=None):
if instance is None:
return self
return self._file_name
def __set__(self, instance, value):
if value is not None:
# pylint: disable=unused-variable
fileName, fileExtension = os.path.splitext(value)
if not fileExtension:
value = value + self._file_ext
self._file_name = value
# pylint: disable=unused-argument
def find_file(self, instance, **kwargs):
""" Method to find file, correspondent to
current MapMaskFile file hint
"""
if self._file_name is None:
return (True, 'No file for {0} is defined'.format(self._prop_name))
file_name = prop_helpers.findFile(self._file_name)
if len(file_name) == 0: # it still can be a run number as string
return (False, 'No file for {0} corresponding to guess: {1} found'.format(self._prop_name, self._file_name))
else:
self._file_name = file_name
return (True, file_name)
# end MapMaskFile
# -----------------------------------------------------------------------------------------
class HardMaskPlus(prop_helpers.ComplexProperty):
"""Sets diagnostics algorithm to use hard mask file
together with all other diagnostics routines.
Assigning a mask file name to this property sets up hard_mask_file property
to the file name provided, and use_hard_mask_only property to False,
so that both hard mask file and the diagnostics procedures are used to identify
and exclude failing detectors.
"""
def __init__(self):
prop_helpers.ComplexProperty.__init__(self, ['use_hard_mask_only', 'run_diagnostics'])
def __get__(self, instance, class_type=None):
if instance is None:
return self
return instance.hard_mask_file
def __set__(self, instance, value):
if value is not None:
# pylint: disable=unused-variable
fileName, fileExtension = os.path.splitext(value)
if not fileExtension:
value = value + '.msk'
instance.hard_mask_file = value
prop_helpers.ComplexProperty.__set__(self, instance.__dict__, [False, True])
else:
prop_helpers.ComplexProperty.__set__(self, instance.__dict__, [True, False])
try:
# pylint: disable=protected-access
del instance.__changed_properties['hardmaskOnly']
# pylint: disable=bare-except
except:
pass
# -----------------------------------------------------------------------------------------
class HardMaskOnly(prop_helpers.ComplexProperty):
"""Sets diagnostics algorithm to use hard mask file and to disable all other diagnostics.
Assigning a mask file name to this property sets up hard_mask_file property
to the file name provided and use_hard_mask_only property to True, so that
only hard mask file provided is used to exclude failing detectors.
"""
def __init__(self):
prop_helpers.ComplexProperty.__init__(self, ['use_hard_mask_only', 'run_diagnostics'])
def __get__(self, instance, owner=None):
if instance is None:
return self
return prop_helpers.gen_getter(instance.__dict__, 'use_hard_mask_only')
def __set__(self, instance, value):
if isinstance(value, bool) or isinstance(value, int):
use_hard_mask_only = bool(value)
hard_mask_file = instance.hard_mask_file
elif isinstance(value, str):
if value.lower() in ['true', 'yes']:
use_hard_mask_only = True
elif value.lower() in ['false', 'no']:
use_hard_mask_only = False
else: # it is probably a hard mask file provided:
instance.hard_mask_file = value
use_hard_mask_only = True
hard_mask_file = instance.hard_mask_file
else:
use_hard_mask_only = False
instance.hard_mask_file = None
hard_mask_file = None
# if no hard mask file is there and use_hard_mask_only is True,
# diagnostics should not run
if use_hard_mask_only and hard_mask_file is None:
run_diagnostics = False
else:
run_diagnostics = True
prop_helpers.ComplexProperty.__set__(self, instance.__dict__, [use_hard_mask_only, run_diagnostics])
try:
# pylint: disable=protected-access
del instance.__changed_properties['hardmaskPlus']
# pylint: disable=bare-except
except:
pass
# end HardMaskOnly
# -----------------------------------------------------------------------------------------
class MonovanIntegrationRange(prop_helpers.ComplexProperty):
"""Integration range for monochromatic vanadium.
The calculated integral is used to estimate relative detector's efficiency.
The range can be defined either directly or as the function of the incident energy(s).
(incident_energy property).
The default settings are the range, relative to the incident energy.
To define range as relative, one needs to set this property to None.
In this case, the actual boundaries are calculated from monovan_lo_frac, monovan_lo_frac
and incident_energy properties values according to the expression:
integration_range = current_incident_energy*[monovan_lo_frac,monovan_hi_frac].
The range should be changed by changing monovan_lo_frac, monovan_hi_frac separately.
To define range as absolute, one needs to assign this property with the range requested.
In this case, the dependent properties monovan_lo_value,monovan_hi_value are set and the
actual range is calculated according to the expression:
integration_range = [monovan_lo_value,monovan_hi_value].
"""
def __init__(self, DepType=None):
if DepType:
self._rel_range = False
prop_helpers.ComplexProperty.__init__(self, ['monovan_lo_value', 'monovan_hi_value'])
else:
self._rel_range = True
prop_helpers.ComplexProperty.__init__(self, ['monovan_lo_frac', 'monovan_hi_frac'])
def __get__(self, instance, owner=None):