Skip to content

Commit

Permalink
Port reduction/instruments directory to new api. Refs #7469
Browse files Browse the repository at this point in the history
  • Loading branch information
martyngigg committed Jul 23, 2013
1 parent 3f4eb47 commit bfd1b18
Show file tree
Hide file tree
Showing 12 changed files with 113 additions and 116 deletions.
12 changes: 6 additions & 6 deletions Code/Mantid/scripts/reduction/find_data.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
from MantidFramework import *
from mantidsimple import *
import mantid.api as api
from mantid.simpleapi import *

def find_file(filename=None, startswith=None, data_dir=None):
"""
Expand All @@ -23,7 +23,7 @@ def find_file(filename=None, startswith=None, data_dir=None):
search_dirs.append(data_dir)
# The standard place would be the location of the configuration files on the SNS mount
search_dirs.append("/SNS/EQSANS/shared/instrument_configuration/")
search_dirs.extend(ConfigService().getDataSearchDirs())
search_dirs.extend(config.getDataSearchDirs())

# Look for specific file
if filename is not None:
Expand Down Expand Up @@ -79,7 +79,7 @@ def find_data(file, instrument='', allow_multiple=False):
try:
# FileFinder doesn't like dashes...
instrument=instrument.replace('-','')
f = FileFinder.findRuns(instrument+file)
f = api.FileFinder.findRuns(instrument+file)
if os.path.isfile(f[0]):
if allow_multiple:
# Mantid returns its own list object type, so make a real list out if it
Expand All @@ -92,7 +92,7 @@ def find_data(file, instrument='', allow_multiple=False):

# Third, assume a run number, without instrument name to take care of list of full paths
try:
f = FileFinder.findRuns(file)
f = api.FileFinder.findRuns(file)
if os.path.isfile(f[0]):
if allow_multiple:
# Mantid returns its own list object type, so make a real list out if it
Expand All @@ -104,5 +104,5 @@ def find_data(file, instrument='', allow_multiple=False):
pass

# If we didn't find anything, raise an exception
mtd.sendErrorMessage("\n\nCould not find a file for %s: check your reduction parameters\n\n" % str(file))
logger.error("\n\nCould not find a file for %s: check your reduction parameters\n\n" % str(file))
raise RuntimeError, "Could not find a file for %s" % str(file)
25 changes: 13 additions & 12 deletions Code/Mantid/scripts/reduction/instruments/example/ExampleRedStep.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
from MantidFramework import *
from mantidsimple import *
from mantid.kernel import *
from mantid.api import *
from mantid.simpleapi import *

class ExampleRedStep(PythonAlgorithm):

def name(self):
return "ExampleRedStep"

def PyInit(self):
self.declareWorkspaceProperty("InputWorkspace", "", Direction.Input)
self.declareProperty("OutputWorkspace", "")
self.declareAlgorithmProperty("Algorithm")
self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input))
self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output))
self.declareProperty(AlgorithmProperty("Algorithm"))

def PyExec(self):
input_ws = self.getProperty("InputWorkspace")
output_ws = self.getProperty("OutputWorkspace")
input_ws = self.getProperty("InputWorkspace").value
output_ws = self.getProperty("OutputWorkspace").value

alg = self.getProperty("Algorithm")
alg = self.getProperty("Algorithm").value
alg.setPropertyValue("InputWorkspace", str(input_ws))
alg.setPropertyValue("OutputWorkspace", output_ws)
alg.execute()

#mtd.registerPyAlgorithm(ExampleRedStep())
#AlgorithmFactory.subscribe(ExampleRedStep)

class ExampleLoader(PythonAlgorithm):

Expand All @@ -29,11 +30,11 @@ def name(self):

def PyInit(self):
self.declareProperty("Filename", "")
self.declareProperty("OutputWorkspace", "")
self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output))

def PyExec(self):
filename = self.getProperty("Filename")
output_ws = self.getProperty("OutputWorkspace")
filename = self.getProperty("Filename").value
output_ws = self.getProperty("OutputWorkspace").value
LoadAscii(filename, output_ws)

print filename, output_ws
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
"""
Simple Reducer example
"""
from MantidFramework import *
from reduction import Reducer
from reduction.instruments.example.ExampleRedStep import ExampleRedStep
from reduction.instruments.example.ExampleRedStep import ExampleLoader
# Validate_step is a decorator that allows both Python algorithms and ReductionStep objects to be passed to the Reducer.
# It also does minimal type checking to ensure that the object that is passed is valid
from reduction import validate_step, validate_loader
from mantidsimple import *
mtd.initialise()
import mantid
from mantid.simpleapi import *

class ExampleReducer(Reducer):

Expand Down Expand Up @@ -39,13 +38,13 @@ def set_first_step(self, step):
where reduction_step is a ReductionStep object
Method 2 (new): reducer.set_first_step(Algorithm, *args, **argv)
where Algorithm is an anlgorithm function from mantidsimple,
where Algorithm is an anlgorithm function from mantid.simpleapi,
following by its arguments.
For example:
reducer.set_first_step(Scale, InputWorkspace=None, OutputWorkspace=None, Factor='2.5')
The arguments follow the signature of the mantidsimple function.
The arguments follow the signature of the mantid.simpleapi function.
See original ticket for more details:
http://trac.mantidproject.org/mantid/ticket/2129l
Expand Down Expand Up @@ -99,8 +98,8 @@ def pre_process(self):
#r._first_step.setProperty("Separator", "Tab")

# Set up an algorithm to be used as part of a reduction step
alg = mtd._createAlgProxy("Scale")
alg.setPropertyValues(Factor="2.5")
alg = mantid.api.FrameworkManager.createAlgorithm("Scale")
alg.setProperty("Factor",2.5)
r.set_normalizer(alg)

# Set up the actual reduction step that will use the algorithm
Expand Down
19 changes: 9 additions & 10 deletions Code/Mantid/scripts/reduction/instruments/sans/absolute_scale.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from reduction import find_data

# Mantid imports
from mantidsimple import *
from mantid.simpleapi import *

class BaseAbsoluteScale(ReductionStep):
"""
Expand Down Expand Up @@ -71,7 +71,7 @@ def execute(self, reducer, workspace=None):
self._compute_scaling_factor(reducer)

if workspace is not None:
Scale(workspace, workspace, self._scaling_factor, 'Multiply')
Scale(InputWorkspace=workspace, OutputWorkspace=workspace, Factor=self._scaling_factor, Operation='Multiply')

return "Absolute scale computed using direct beam: %6.4g" % self._scaling_factor

Expand Down Expand Up @@ -105,16 +105,16 @@ def _compute_scaling_factor(self, reducer):
if monitor_id == reducer.NORMALIZATION_MONITOR:
monitor /= 1.0e8

if mtd[data_file_ws].getRun().hasProperty("sample_detector_distance"):
sdd = mtd[data_file_ws].getRun().getProperty("sample_detector_distance").value
if mtd[data_file_ws].run().hasProperty("sample_detector_distance"):
sdd = mtd[data_file_ws].run().getProperty("sample_detector_distance").value
else:
raise RuntimeError, "AbsoluteScale could not read the sample-detector-distance"

if self._beamstop_diameter is not None:
beam_diameter = self._beamstop_diameter
else:
if mtd[data_file_ws].getRun().hasProperty("beam-diameter"):
beam_diameter = mtd[data_file_ws].getRun().getProperty("beam-diameter").value
if mtd[data_file_ws].run().hasProperty("beam-diameter"):
beam_diameter = mtd[data_file_ws].run().getProperty("beam-diameter").value
else:
raise RuntimeError, "AbsoluteScale could not read the beam radius and none was provided"

Expand All @@ -129,8 +129,7 @@ def _compute_scaling_factor(self, reducer):
'<radius val="%12.10f" />' % (beam_diameter/2000.0) + \
'</infinite-cylinder>\n'

det_finder = FindDetectorsInShape(Workspace=data_file_ws, ShapeXML=cylXML)
det_list = det_finder.getPropertyValue("DetectorList")
det_list = FindDetectorsInShape(Workspace=data_file_ws, ShapeXML=cylXML)
det_count_ws = "__absolute_scale"
GroupDetectors(InputWorkspace=data_file_ws, OutputWorkspace=det_count_ws, DetectorList=det_list, KeepUngroupedSpectra="0")
det_count = mtd[det_count_ws].readY(0)[0]
Expand All @@ -145,8 +144,8 @@ def _compute_scaling_factor(self, reducer):
# (detector count rate)/(attenuator transmission)/(monitor rate)*(pixel size/SDD)**2
self._scaling_factor = 1.0/(det_count/self._attenuator_trans/(monitor)*(pixel_size/sdd)*(pixel_size/sdd))

mtd.deleteWorkspace(data_file_ws)
mtd.deleteWorkspace(det_count_ws)
DeleteWorkspace(data_file_ws)
DeleteWorkspace(det_count_ws)



Expand Down
26 changes: 13 additions & 13 deletions Code/Mantid/scripts/reduction/instruments/sans/eqsans_load.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from sans_reduction_steps import BaseBeamFinder

# Mantid imports
from mantidsimple import *
from mantid.simpleapi import *

class LoadRun(ReductionStep):
"""
Expand Down Expand Up @@ -152,10 +152,10 @@ def delete_workspaces(cls, workspace):
# Delete the beam hole transmission workspace if it exists
if mtd[workspace].getRun().hasProperty("transmission_ws"):
trans_ws = mtd[workspace].getRun().getProperty("transmission_ws").value
if mtd.workspaceExists(trans_ws):
mtd.deleteWorkspace(trans_ws)
if mtd.workspaceExists(workspace):
mtd.deleteWorkspace(workspace)
if mtd.doesExist(trans_ws):
DeleteWorkspace(trans_ws)
if mtd.doesExist(workspace):
DeleteWorkspace(workspace)

def execute(self, reducer, workspace):
output_str = ""
Expand All @@ -182,15 +182,15 @@ def execute(self, reducer, workspace):
def _load_data_file(file_name, wks_name):
# Check whether we are processing an event workspace or whether
# we need to load a file
if mtd.workspaceExists(file_name) \
if mtd.doesExist(file_name) \
and mtd[file_name].getAxis(0).getUnit().name()=="TOF":
input_ws = file_name
filepath = None
else:
filepath = find_data(file_name, instrument=reducer.instrument.name())
input_ws = None

l = EQSANSLoad(Filename=filepath,
results = EQSANSLoad(Filename=filepath,
InputWorkspace=input_ws,
OutputWorkspace=wks_name,
UseConfigBeam=use_config_beam,
Expand All @@ -210,7 +210,7 @@ def _load_data_file(file_name, wks_name):
LoadMonitors=self._load_monitors,
ReductionProperties=reducer.get_reduction_table_name()
)
return l.getPropertyValue("OutputMessage")
return results[-1] # return output message

# Check whether we have a list of files that need merging
# Make sure we process a list of files written as a string
Expand All @@ -226,24 +226,24 @@ def _load_data_file(file_name, wks_name):
Plus(LHSWorkspace=workspace,
RHSWorkspace='__tmp_wksp',
OutputWorkspace=workspace)
if mtd.workspaceExists('__tmp_wksp'):
mtd.deleteWorkspace('__tmp_wksp')
if mtd.doesExist('__tmp_wksp'):
DeleteWorkspace('__tmp_wksp')
else:
output_str += "Loaded %s\n" % data_file
output_str += _load_data_file(data_file, workspace)

mantid[workspace].getRun().addProperty_str("event_ws", workspace, True)
mtd[workspace].getRun().addProperty("event_ws", workspace, True)

if mtd[workspace].getRun().hasProperty("beam_center_x") and \
mtd[workspace].getRun().hasProperty("beam_center_y"):
beam_center_x = mtd[workspace].getRun().getProperty("beam_center_x").value
beam_center_y = mtd[workspace].getRun().getProperty("beam_center_y").value
if type(reducer._beam_finder) is BaseBeamFinder:
reducer.set_beam_finder(BaseBeamFinder(beam_center_x, beam_center_y))
mantid.sendLogMessage("Setting beam center to [%-6.1f, %-6.1f]" % (beam_center_x, beam_center_y))
logger.notice("Setting beam center to [%-6.1f, %-6.1f]" % (beam_center_x, beam_center_y))

# Remove the dirty flag if it existed
reducer.clean(workspace)
mtd[workspace].getRun().addProperty_int("loaded_by_eqsans_reduction", 1, True)
mtd[workspace].getRun().addProperty("loaded_by_eqsans_reduction", 1, True)

return output_str
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import absolute_scale
import hfir_instrument
from reduction.find_data import find_data
import mantidsimple
import mantid.simpleapi as api

## List of user commands ######################################################
def DirectBeamCenter(datafile):
Expand Down Expand Up @@ -56,7 +56,7 @@ def NoSensitivityCorrection():

def DarkCurrent(datafile):
datafile = find_data(datafile, instrument=ReductionSingleton().instrument.name())
ReductionSingleton().set_dark_current_subtracter(mantidsimple.HFIRDarkCurrentSubtraction,
ReductionSingleton().set_dark_current_subtracter(api.HFIRDarkCurrentSubtraction,
InputWorkspace=None, Filename=datafile,
OutputWorkspace=None,
ReductionProperties=ReductionSingleton().get_reduction_table_name())
Expand All @@ -65,7 +65,7 @@ def NoDarkCurrent():
ReductionSingleton().set_dark_current_subtracter(None)

def SolidAngle(detector_tubes=False):
ReductionSingleton().set_solid_angle_correcter(mantidsimple.SANSSolidAngleCorrection, InputWorkspace=None, OutputWorkspace=None,
ReductionSingleton().set_solid_angle_correcter(api.SANSSolidAngleCorrection, InputWorkspace=None, OutputWorkspace=None,
DetectorTubes=detector_tubes,
ReductionProperties=ReductionSingleton().get_reduction_table_name())

Expand Down Expand Up @@ -309,7 +309,7 @@ def ResetWavelength():
ReductionSingleton().get_data_loader().set_wavelength()

def IQxQy(nbins=100):
ReductionSingleton().set_IQxQy(mantidsimple.EQSANSQ2D, InputWorkspace=None,
ReductionSingleton().set_IQxQy(api.EQSANSQ2D, InputWorkspace=None,
NumberOfBins=nbins)

def NoIQxQy(nbins=100):
Expand All @@ -331,7 +331,7 @@ def DivideByThickness(thickness=1.0):
if thickness is None or thickness == 1.0:
ReductionSingleton().set_geometry_correcter(None)
else:
ReductionSingleton().set_geometry_correcter(mantidsimple.NormaliseByThickness, InputWorkspace=None, OutputWorkspace=None, SampleThickness=thickness)
ReductionSingleton().set_geometry_correcter(api.NormaliseByThickness, InputWorkspace=None, OutputWorkspace=None, SampleThickness=thickness)

def BckDivideByThickness(thickness=1.0):
print "Background thickness can no longer be set: only the final sample-minus-data workspace can be divided by the sample thickness."
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from reduction import Instrument
import MantidFramework
import mantid

class HFIRSANS(Instrument):
"""
Expand All @@ -16,9 +16,9 @@ def __init__(self, instrument_id="BIOSANS") :

def get_incident_mon(self, workspace, option):
if option == HFIRSANS.NORMALIZATION_TIME:
return int(MantidFramework.mtd[workspace].getInstrument().getNumberParameter("default-incident-timer-spectrum")[0])
return int(mantid.mtd[workspace].getInstrument().getNumberParameter("default-incident-timer-spectrum")[0])
elif option == HFIRSANS.NORMALIZATION_MONITOR:
return int(MantidFramework.mtd[workspace].getInstrument().getNumberParameter("default-incident-monitor-spectrum")[0])
return int(mantid.mtd[workspace].getInstrument().getNumberParameter("default-incident-monitor-spectrum")[0])
return -1

def get_default_beam_center(self, workspace=None):
Expand Down Expand Up @@ -97,12 +97,12 @@ def _get_pixel_info(self, workspace):
@param workspace: workspace to extract the pixel information from
"""
## Number of detector pixels in X
nx_pixels = int(MantidFramework.mtd[workspace].getInstrument().getNumberParameter("number-of-x-pixels")[0])
nx_pixels = int(mantid.mtd[workspace].getInstrument().getNumberParameter("number-of-x-pixels")[0])
## Number of detector pixels in Y
ny_pixels = int(MantidFramework.mtd[workspace].getInstrument().getNumberParameter("number-of-y-pixels")[0])
ny_pixels = int(mantid.mtd[workspace].getInstrument().getNumberParameter("number-of-y-pixels")[0])
## Pixel size in mm
pixel_size_x = MantidFramework.mtd[workspace].getInstrument().getNumberParameter("x-pixel-size")[0]
pixel_size_y = MantidFramework.mtd[workspace].getInstrument().getNumberParameter("y-pixel-size")[0]
pixel_size_x = mantid.mtd[workspace].getInstrument().getNumberParameter("x-pixel-size")[0]
pixel_size_y = mantid.mtd[workspace].getInstrument().getNumberParameter("y-pixel-size")[0]

return nx_pixels, ny_pixels, pixel_size_x, pixel_size_y

Expand All @@ -120,8 +120,8 @@ def get_aperture_distance(self, workspace):
@param workspace: workspace to get the aperture distance from
"""
try:
nguides = MantidFramework.mtd[workspace].getRun().getProperty("number-of-guides").value
apertures_lst = MantidFramework.mtd[workspace].getInstrument().getStringParameter("aperture-distances")[0]
nguides = mantid.mtd[workspace].run().getProperty("number-of-guides").value
apertures_lst = mantid.mtd[workspace].getInstrument().getStringParameter("aperture-distances")[0]
apertures = apertures_lst.split(',')
# Note that they are in reverse order, the first item is for 8 guides
# and the last item is for 0 guide.
Expand Down

0 comments on commit bfd1b18

Please sign in to comment.