Skip to content

Commit

Permalink
refs #10532 further separation in DirectEnergyConversion.
Browse files Browse the repository at this point in the history
  • Loading branch information
abuts committed Nov 25, 2014
1 parent 6b99c42 commit 4ee8424
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 85 deletions.
40 changes: 19 additions & 21 deletions Code/Mantid/scripts/Inelastic/DirectEnergyConversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,15 @@ def diagnose(self, white, **kwargs):
else:
var_name = "diag_mask"

# Check for any keywords that have not been supplied and put in the values set on reducer
for par in self.__diag_params:
arg = par.lstrip('diag_')
if arg not in kwargs:
kwargs[arg] = getattr(self, arg)
prop_man = selt.prop_man;
diag_params = prop_man.getDiagnosticsParameters();
for key,val in kwargs.iteritems():
diag_params[key]=val;
## Check for any keywords that have not been supplied and put in the values set on reducer
#for par in self.__diag_params:
# arg = par.lstrip('diag_')
# if arg not in kwargs:
# kwargs[arg] = getattr(self, arg)

# if input parameter is workspace rather then run, we want to keep it
self._keep_wb_workspace = False
Expand All @@ -120,12 +124,9 @@ def diagnose(self, white, **kwargs):
if isinstance(white,api.Workspace) : # it is workspace itself
self._keep_wb_workspace = True

# If we have a hard_mask, check the instrument name is defined
if 'hard_mask_file' in kwargs:
if 'instrument_name' not in kwargs:
kwargs['instrument_name'] = self.instr_name

if kwargs['use_hard_mask_only'] :

# TODO: primitive cache is used here. Improve
if prop_man.use_hard_mask_only:
if mtd.doesExist('hard_mask_ws'):
diag_mask = mtd['hard_mask_ws']
else: # build hard mask
Expand All @@ -137,7 +138,7 @@ def diagnose(self, white, **kwargs):
# Load
white_data = self.load_data(white,whitews_name,self._keep_wb_workspace)

diag_mask= LoadMask(Instrument=self.instr_name,InputFile=kwargs['hard_mask_file'],
diag_mask= LoadMask(Instrument=self.instr_name,InputFile=prop_man.hard_mask_file,
OutputWorkspace='hard_mask_ws')
MaskDetectors(Workspace=white_data, MaskedWorkspace=diag_mask)
diag_mask,masked_list = ExtractMask(InputWorkspace=white_data)
Expand All @@ -147,21 +148,18 @@ def diagnose(self, white, **kwargs):

# Get the white beam vanadium integrals
whiteintegrals = self.do_white(white, None, None,None) # No grouping yet
if 'second_white' in kwargs:
second_white = kwargs['second_white']
if second_white is None:
del kwargs['second_white']
else:
other_whiteintegrals = self.do_white(second_white, None, None,None) # No grouping yet
kwargs['second_white'] = other_whiteintegrals
if prop_man.second_white:
second_white = prop_man.second_white;
other_whiteintegrals = self.do_white(second_white, None, None,None) # No grouping yet
prop_man.second_white = other_whiteintegrals;


# Get the background/total counts from the sample if present
if 'sample' in kwargs:
sample = kwargs['sample']
del kwargs['sample']
# If the bleed test is requested then we need to pass in the sample_run as well
if kwargs.get('bleed_test', False):
if prop_man.bleed_test:
kwargs['sample_run'] = sample

# Set up the background integrals
Expand All @@ -178,7 +176,7 @@ def diagnose(self, white, **kwargs):
total_counts = Integration(result_ws, IncludePartialBins=True)
background_int = ConvertUnits(background_int, "Energy", AlignBins=0)
self.log("Diagnose: finished convertUnits ")
background_int *= self.scale_factor
background_int *= prop_man.scale_factor;
diagnostics.normalise_background(background_int, whiteintegrals, kwargs.get('second_white',None))
kwargs['background_int'] = background_int
kwargs['sample_counts'] = total_counts
Expand Down
125 changes: 69 additions & 56 deletions Code/Mantid/scripts/Inelastic/DirectPropertyManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ def __init__(self,InsturmentName,run_number=None,wb_run_number=None):
object.__setattr__(self,'_log_level','notice');
object.__setattr__(self,'_log_to_mantid',True);

object.__setattr__(self,'_psi',float('NaN'));
object.__setattr__(self,'_second_white',None);

#end

def getDefaultParameterValue(self,par_name):
Expand All @@ -60,8 +63,18 @@ def instr_name(self):
return name[0:3];
@property
def psi(self):
return 0;
""" rotation angle (not available from IDF)"""
return self._psi;

@psi.setter
def psi(self,value):
"""set rotation angle (not available from IDF). This value will be saved into NXSpe file"""
self._psi = value

@property
def seclond_white(self):
""" Second white beam currently unused in workflow """
return self._second_white;

@property
def incident_energy(self):
Expand Down Expand Up @@ -278,9 +291,23 @@ def __set__(self,instance,value):
fileName, fileExtension = os.path.splitext(value)
if (not fileExtension):
value=value+self._file_ext;
else:
if self._field_name=='hard_mask_file':
if instance.use_hard_mask_only:
instance.run_diagnostics = False;

prop_helpers.gen_setter(instance.__dict__,self._field_name,value);
#end MapMaskFile

class HardMaskOnly(object):
def __get__(self,instance,type=None):
return prop_helpers.gen_getter(instance.__dict__,'use_hard_mask_only');
def __set__(self,instance,value):
prop_helpers.gen_setter(instance.__dict__,'use_hard_mask_only',value);
if not(value) and instance.hard_mask_file is None:
instance.run_diagnostics = False;
#end HardMaskOnly

class MonovanIntegrationRange(object):
""" integration range for monochromatic vanadium
Expand Down Expand Up @@ -405,6 +432,26 @@ def __set__(self,instance,value):
instance.__dict__['save_format'].add(value);
#end SaveFormat

class DiagSpectra(object):
""" class describes spectra list which can be used in diagnostics """
def __get__(self,instance,type=None):
try:
return prop_helpers.gen_getter(instance.__dict__,'spectra_to_monitors_list');
except KeyError:
return None
def __set__(self,instance,spectra_list):
self.diag_spectra.split(";")
bank_spectra = []
for b in banks:
token = b.split(",") # b = "(,)"
if len(token) != 2:
raise ValueError("Invalid bank spectra specification in diag %s" % self.diag_spectra)
start = int(token[0].lstrip('('))
end = int(token[1].rstrip(')'))
bank_spectra.append((start,end))
#end DiagSpectra



#-----------------------------------------------------------------------------------------
# END Descriptors, Direct property manager itself
Expand Down Expand Up @@ -442,7 +489,7 @@ def __init__(self,InstrumentName,run_number=None,wb_run_number=None):
del param_list['synonims']
#end


# set up properties which have default parameters
param_list = prop_helpers.build_properties_dict(param_list,self.__subst_dict)
self.__dict__.update(param_list)

Expand All @@ -453,7 +500,7 @@ def __init__(self,InstrumentName,run_number=None,wb_run_number=None):

# properties with allowed values
self.__prop_allowed_values['normalise_method']=[None,'monitor-1','monitor-2','current'] # 'uamph', peak -- disabled/unknown at the moment
self.__prop_allowed_values['deltaE_mode']=['direct'] # I do not think we should try other modes
self.__prop_allowed_values['deltaE_mode']=['direct'] # I do not think we should try other modes here


# properties with special(overloaded and non-standard) setters/getters: Properties name dictionary returning tuple(getter,setter)
Expand All @@ -463,7 +510,7 @@ def __init__(self,InstrumentName,run_number=None,wb_run_number=None):
# list of the parameters which should usually be changed by user and if not, user should be warn about it.
self.__abs_units_par_to_change=['sample_mass','sample_rmm']
# list of the parameters which should always be taken from IDF unless explicitly set from elsewhere. These parameters MUST have setters and getters
self.__idf_param_located =['ei_mon_spectra']
#self.__idf_param_located =['ei_mon_spectra']
# dictionary of the special setters & getters:

# list of the properties which have been changed:
Expand Down Expand Up @@ -503,8 +550,13 @@ def __setattr__(self,name0,val):
#end

# redefine generic substitutions for None
if type(val) is str and (val is 'None' or val is 'none' or len(val) == 0):
val = None;
if type(val) is str :
val = val.lower()
if (val == 'none' or len(val) == 0):
val = None;
if val == 'default':
val = self.getDefaultParameterValue(name0);

if type(val) is list and len(val) == 0:
val = None;

Expand Down Expand Up @@ -564,7 +616,10 @@ def getChangedProperties(self):
spectra_to_monitors_list = SpectraToMonitorsList();
#
save_format = SaveFormat();

#
use_hard_mask_only = HardMaskOnly();
#
diag_spectra = DiagSpectra();



Expand Down Expand Up @@ -597,60 +652,18 @@ def background_test_range(self,value):



def _set_input_parameters(self,synonims,composite_keys_set,composite_keys_subst,**kwargs):
""" Method analyzes input parameters list, substitutes the synonyms in this list with predefined synonyms
and sets the existing class parameters with its non-default values taken from input
def set_input_parameters(self,**kwargs):
""" Set input properties from a dictionary of parameters
returns the list of changed properties.
Auxiliary methods used in old interface.
Returns the list of changed properties.
"""

properties_changed=[];
for par_name,value in kwargs.items() :

if par_name in synonims :
par_name = synonims[par_name]
# may be a problem, one tries to set up non-existing value
if not (hasattr(self,par_name) or hasattr(self,'_'+par_name)):
# it still can be a composite key which sets parts of the composite property
if par_name in self.composite_keys_subst :
composite_prop_name,index,nc = composite_keys_subst[par_name]
val = getattr(self,composite_prop_name)
val[index] = value;
setattr(self,composite_prop_name,val)
properties_changed.append(composite_prop_name)
continue
else:
raise KeyError("Attempt to set unknown parameter: "+par_name)
# whole composite key is modified by input parameters
if par_name in composite_keys_set :
default_value = getattr(self,par_name) # get default value
if isinstance(value,str) and value.lower()[0:7] == 'default' : # Property changed but default value requested explicitly
value = default_value
if type(default_value) != type(value):
raise KeyError("Attempt to change range property: "+par_name+" of type : "+str(type(default_value))+ " with wrong type value: "+str(type(value)))
if len(default_value) != len(value) :
raise KeyError("Attempt to change range property : "+par_name+" with default value: ["+",".join(str(vv) for vv in val)+
"] to wrong length value: ["+",".join(str(vv) for vv in value)+"]\n")
else:
setattr(self,par_name,value)
properties_changed.append(par_name)
continue

# simple case of setting simple value
if isinstance(value,str) and value.lower()[0:7] == 'default' : # Property changed but default value requested explicitly
value = getattr(self,par_name)


setattr(self,par_name,value)
properties_changed.append(par_name)

# some properties have collective meaning
if self.use_hard_mask_only and self.hard_mask_file is None:
if self.run_diagnostics:
self.run_diagnostics=False;
properties_changed.append('run_diagnostics');

return properties_changed
setattr(self,par_name,value);

return self.getChangedProperties();



Expand Down
8 changes: 0 additions & 8 deletions Code/Mantid/scripts/test/DirectEnergyConversionTest.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,14 +104,6 @@ def test_save_formats(self):



#def test_set_non_default_wrong_value(self):
# tReducer = self.reducer
# # should do nothing as already initialized above
# tReducer.initialise("MAP")

# # non-existing property can not be set!
# self.assertRaises(KeyError,tReducer.set_input_parameters,non_existing_property="Something_Meaningfull")

#def test_set_non_default_simple_value(self):
# tReducer = self.reducer
# # should do nothing as already initialized above
Expand Down

0 comments on commit 4ee8424

Please sign in to comment.