Skip to content

Commit

Permalink
Re #10803 Simplified naming for all classes involved
Browse files Browse the repository at this point in the history
(e.g. removed Direct from almost all classes as they are in Direct folder anyway)
  • Loading branch information
abuts committed Dec 15, 2014
1 parent c0a5d83 commit 4824234
Show file tree
Hide file tree
Showing 6 changed files with 604 additions and 608 deletions.
156 changes: 79 additions & 77 deletions Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py
@@ -1,43 +1,75 @@
"""
Conversion class defined for conversion to deltaE for
'direct' inelastic geometry instruments
The class defines various methods to allow users to convert their
files to DeltaE.
Usage:
>>red = DirectEnergyConversion('InstrumentName')
and then:
>>red.convert_to_energy_transfer(wb_run,sample_run,ei_guess,rebin)
or
>>red.convert_to_energy_transfer(wb_run,sample_run,ei_guess,rebin,**arguments)
or
>>red.convert_to_energy_transfer(wb_run,sample_run,ei_guess,rebin,mapfile,**arguments)
or
>>red.convert_to_energy_transfer(wb_run
Whitebeam run number or file name or workspace
sample_run sample run number or file name or workspace
ei_guess Ei guess
rebin Rebin parameters
mapfile Mapfile -- if absent/'default' the defaults from IDF are used
monovan_run If present will do the absolute units normalization. Number of additional parameters
specified in **kwargs is usually requested for this. If they are absent, program uses defaults,
but the defaults (e.g. sample_mass or sample_rmm ) are usually incorrect for a particular run.
arguments The dictionary containing additional keyword arguments.
The list of allowed additional arguments is defined in InstrName_Parameters.xml file, located in
MantidPlot->View->Preferences->Mantid->Directories->Parameter Definitions
with run numbers as input:
>>red.convert_to_energy_transfer(1000,10001,80,[-10,.1,70]) # will run on default instrument
>>red.convert_to_energy_transfer(1000,10001,80,[-10,.1,70],'mari_res', additional keywords as required)
>>red.convert_to_energy_transfer(1000,10001,80,'-10,.1,70','mari_res',fixei=True)
A detector calibration file must be specified if running the reduction with workspaces as input
namely:
>>w2=cred.onvert_to_energy_transfer('wb_wksp','run_wksp',ei,rebin_params,mapfile,det_cal_file=cal_file
,diag_remove_zero=False,norm_method='current')
from mantid.simpleapi import *
from mantid.kernel import funcreturns
from mantid import api
from mantid import geometry

import time as time
import glob,sys,os.path,math
import numpy as np

import CommonFunctions as common
import diagnostics
from PropertyManager import PropertyManager;

def setup_reducer(inst_name,reload_instrument=False):
"""
Given an instrument name or prefix this sets up a converter
object for the reduction
"""
try:
return DirectEnergyConversion(inst_name,reload_instrument)
except RuntimeError, exc:
raise RuntimeError('Unknown instrument "%s" or wrong IDF file for this instrument, cannot continue' % inst_name)


class DirectEnergyConversion(object):
"""
Performs a convert to energy assuming the provided instrument is an direct inelastic geometry instruments
The class defines various methods to allow users to convert their
files to Energy transfer
Usage:
>>red = DirectEnergyConversion('InstrumentName')
and then:
>>red.convert_to_energy(wb_run,sample_run,ei_guess,rebin)
or
>>red.convert_to_energy(wb_run,sample_run,ei_guess,rebin,**arguments)
or
>>red.convert_to_energy(wb_run,sample_run,ei_guess,rebin,mapfile,**arguments)
or
>>red.prop_man.sample_run = run number
>>red.prop_man.wb_run = Whitebeam
>>red.prop_man.incident_energy = energy guess
>>red.prop_man.energy_bins = [min_val,step,max_val]
>>red.convert_to_energy()
Where:
Whitebeam run number or file name or workspace
sample_run sample run number or file name or workspace
ei_guess suggested value for incident energy of neutrons in direct inelastic instrument
energy_bins energy binning requested for resulting spe workspace.
mapfile Mapfile -- if absent/'default' the defaults from IDF are used
monovan_run If present will do the absolute units normalization. Number of additional parameters
specified in **kwargs is usually requested for this. If they are absent, program uses defaults,
but the defaults (e.g. sample_mass or sample_rmm ) are usually incorrect for a particular run.
arguments The dictionary containing additional keyword arguments.
The list of allowed additional arguments is defined in InstrName_Parameters.xml file, located in
MantidPlot->View->Preferences->Mantid->Directories->Parameter Definitions
Usage examples:
with run numbers as input:
>>red.convert_to_energy(1000,10001,80,[-10,.1,70]) # will run on default instrument
>>red.convert_to_energy(1000,10001,80,[-10,.1,70],'mari_res', additional keywords as required)
>>red.convert_to_energy(1000,10001,80,'-10,.1,70','mari_res',fixei=True)
A detector calibration file must be specified if running the reduction with workspaces as input
namely:
>>w2=cred.onvert_to_energy_transfer('wb_wksp','run_wksp',ei,rebin_params,mapfile,det_cal_file=cal_file
,diag_remove_zero=False,norm_method='current')
All available keywords are provided in InstName_Parameters.xml file
Expand Down Expand Up @@ -90,36 +122,6 @@
hardmaskPlus=Filename :load a hardmarkfile and apply together with diag mask
hardmaskOnly=Filename :load a hardmask and use as only mask
"""


from mantid.simpleapi import *
from mantid.kernel import funcreturns
from mantid import api
from mantid import geometry

import time as time
import glob,sys,os.path,math
import numpy as np

import CommonFunctions as common
import diagnostics
from DirectPropertyManager import DirectPropertyManager;

def setup_reducer(inst_name,reload_instrument=False):
"""
Given an instrument name or prefix this sets up a converter
object for the reduction
"""
try:
return DirectEnergyConversion(inst_name,reload_instrument)
except RuntimeError, exc:
raise RuntimeError('Unknown instrument "%s" or wrong IDF file for this instrument, cannot continue' % inst_name)


class DirectEnergyConversion(object):
"""
Performs a convert to energy assuming the provided instrument is an elastic instrument
"""

def diagnose(self, white,diag_sample=None,**kwargs):
Expand Down Expand Up @@ -1298,10 +1300,10 @@ def prop_man(self):
@prop_man.setter
def prop_man(self,value):
""" Assign new instance of direct property manager to provide DirectEnergyConversion parameters """
if isinstance(value,DirectPropertyManager):
if isinstance(value,PropertyManager):
self._propMan = value;
else:
raise KeyError("Property manager can be initialized by an instance of DirectProperyManager only")
raise KeyError("Property manager can be initialized by an instance of ProperyManager only")
#---------------------------------------------------------------------------
# Behind the scenes stuff
#---------------------------------------------------------------------------
Expand Down Expand Up @@ -1334,21 +1336,21 @@ def initialise(self, instr,reload_instrument=False):
# Instrument and default parameter setup
# formats available for saving. As the reducer has to have a method to process one of this, it is private property
if not hasattr(self,'_propMan') or self._propMan is None:
if isinstance(instr,DirectPropertyManager):
if isinstance(instr,PropertyManager):
self._propMan = instr;
else:
self._propMan = DirectPropertyManager(instr);
self._propMan = PropertyManager(instr);
else:
old_name = self._propMan.instrument.getName();
if isinstance(instr,geometry._geometry.Instrument):
new_name = self._propMan.instrument.getName();
elif isinstance(instr,DirectPropertyManager):
elif isinstance(instr,PropertyManager):
new_name = instr.instr_name;
else:
new_name = instr
#end if
if old_name != new_name or reload_instrument:
self._propMan = DirectPropertyManager(new_name);
self._propMan = PropertyManager(new_name);
#end if
#

Expand All @@ -1357,7 +1359,7 @@ def setup_instrument_properties(self, workspace = None,reload_instrument=False):
instrument = workspace.getInstrument();
name = instrument.getName();
if name != self.prop_man.instr_name:
self.prop_man = DirectPropertyManager(name,workspace);
self.prop_man = PropertyManager(name,workspace);


def check_abs_norm_defaults_changed(self,changed_param_list) :
Expand Down
@@ -1,161 +1,14 @@
""" File contains classes defining the interface for Direct inelastic reduction with properties
necessary for reduction but not present in Instrument_Properties.xml file
Main example of such properties are run numbers, energy bins and incident energies.
"""

from mantid.simpleapi import *
from mantid import api
from mantid import geometry
from mantid import config
import ReductionHelpers as prop_helpers
import CommonFunctions as common
import os


#-----------------------------------------------------------------------------------------
# Descriptors, providing overloads for some complex properties in DirectReductionProperties
#-----------------------------------------------------------------------------------------
class IncidentEnergy(object):
""" descriptor for incident energy or range of incident energies to be processed """
def __init__(self):
pass
def __get__(self,instance,owner=None):
""" return incident energy or list of incident energies """
return instance._incident_energy;
def __set__(self,instance,value):
""" Set up incident energy or range of energies in various formats """
if value != None:
if isinstance(value,str):
en_list = str.split(value,',');
if len(en_list)>1:
rez = [];
for en_str in en_list:
val = float(en_str);
rez.append(val)
instance._incident_energy=rez;
else:
instance._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);

object.__setattr__(instance,'_incident_energy',rez);
else:
object.__setattr__(instance,'_incident_energy',float(value));
else:
raise KeyError("Incident energy have to be positive number of list of positive numbers. Got None")

#
inc_en=instance._incident_energy
if isinstance(inc_en,list):
for en in inc_en:
if en<= 0:
raise KeyError("Incident energy have to be positive number of list of positive numbers."+
" For input argument {0} got negative value {1}".format(value,en))
else:
if inc_en<= 0:
raise KeyError("Incident energy have to be positive number of list of positive numbers."+
" For value {0} got negative {1}".format(value,inc_en))
# end IncidentEnergy
class EnergyBins(object):
""" Property provides various energy bin possibilities """
def __get__(self,instance,owner=None):
""" binning range for the result of convertToenergy procedure or list of such ranges """
return instance._energy_bins

def __set__(self,instance,values):
if values != None:
if isinstance(values,str):
lst = str.split(values,',');
nBlocks = len(lst);
for i in xrange(0,nBlocks,3):
value = [float(lst[i]),float(lst[i+1]),float(lst[i+2])]
else:
value = values;
nBlocks = len(value);
if nBlocks%3 != 0:
raise KeyError("Energy_bin value has to be either list of n-blocks of 3 number each or string representation of this list with numbers separated by commas")
#TODO: implement single value settings according to rebin
object.__setattr__(instance,'_energy_bins',value);
#end EnergyBins
class SaveFileName(object):
""" Property defines default file name to save result to
See similar property get_sample_ws_name TODO: (leave only one)
"""
def __init__(self,Name=None):
self._file_name = Name
def __get__(self,instance,owner=None):
if self._file_name:
return self._file_name
else:
if instance.instr_name:
name = instance.short_inst_name
else:
name = '_EMPTY'
try:
sr = instance.sample_run
except:
sr = 0
try:
name +='{0:0<5}Ei{1:<4.2f}meV'.format(sr,instance.incident_energy)
if instance.sum_runs:
name +='sum'
if instance.monovan_run:
name +='_Abs'
except:
name = None
return name

def __set__(self,instance,value):
self._file_name = value
#end SaveFileName


#
class InstrumentDependentProp(object):
def __init__(self,prop_name):
self._prop_name = prop_name;
def __get__(self,instance,owner=None):
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".format(self._prop_name))
#end InstrumentDependentProp

def check_ei_bin_consistent(ei,binning_range):
""" function verifies if the energy binning is consistent with incident energies """
if isinstance(ei,list):
for en in ei:
range = binning_range[en]
if range[2]>en:
return (False,'Max rebin range {0:f} exceeds incident energy {1:f}'.format(range[2],en))
else:
if binning_range[2]>ei:
return (False,'Max rebin range {0:f} exceeds incident energy {1:f}'.format(binning_range[2],ei))

return (True,'')

#-----------------------------------------------------------------------------------------
# END Descriptors for DirectReductionProperties
#-----------------------------------------------------------------------------------------

class DirectReductionProperties(object):
""" Class contains main properties, used in reduction, and not described in
IDF
from PropertiesDescriptors import *


class NonIDF_Properties(object):
""" Class defines the interface for main properties, used in reduction, and not described in
IDF ( Instrument_Properties.xml file)
These properties are main set of properties, user have to set up
for reduction to work with defaults.
The example of such properties are run numbers, energy bins and incident energies.
"""

# logging levels available for user
Expand Down Expand Up @@ -218,11 +71,13 @@ def getDefaultParameterValue(self,par_name):
""" method to get default parameter value, specified in IDF """
return prop_helpers.get_default_parameter(self.instrument,par_name);
#-----------------------------------------------------------------------------
# Complex properties with personal descriptors
#-----------------------------------------------------------------------------
incident_energy = IncidentEnergy()
#
energy_bins = EnergyBins()
#
save_file_name = SaveFileName()
save_file_name = SaveFileName()
#
instr_name = InstrumentDependentProp('_instr_name')
short_inst_name = InstrumentDependentProp('_short_instr_name')
Expand Down Expand Up @@ -412,7 +267,7 @@ def _set_instrument_and_facility(self,Instrument,run_workspace=None):
def log(self, msg,level="notice"):
"""Send a log message to the location defined
"""
lev,logger = DirectReductionProperties.log_options[level]
lev,logger = NonIDF_Properties.log_options[level]
if self._log_to_mantid:
logger(msg)
else:
Expand Down

0 comments on commit 4824234

Please sign in to comment.