Skip to content

Commit

Permalink
Refactor more indirect related algorithms
Browse files Browse the repository at this point in the history
Refs #10706
  • Loading branch information
DanNixon committed Feb 16, 2015
1 parent 945c124 commit bddddc2
Show file tree
Hide file tree
Showing 8 changed files with 244 additions and 149 deletions.
@@ -1,7 +1,9 @@
from mantid import logger, mtd
from mantid.api import PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, ITableWorkspaceProperty, PropertyMode
from mantid.api import PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, \
ITableWorkspaceProperty, PropertyMode
from mantid.kernel import Direction, IntArrayProperty
from mantid.simpleapi import CreateWorkspace, CopyLogs, CopySample, CopyInstrumentParameters, SaveNexusProcessed, CreateEmptyTableWorkspace, RenameWorkspace
from mantid.simpleapi import CreateWorkspace, CopyLogs, CopyInstrumentParameters, \
SaveNexusProcessed, CreateEmptyTableWorkspace, RenameWorkspace

import math
import os.path
Expand Down Expand Up @@ -37,7 +39,8 @@ def PyInit(self):
Direction.Output), doc='Name to call the output workspace.')

self.declareProperty(ITableWorkspaceProperty('OutputPropertiesTable', '',
Direction.Output, PropertyMode.Optional), doc='Name to call the properties output table workspace.')
Direction.Output, PropertyMode.Optional),
doc='Name to call the properties output table workspace.')


def PyExec(self):
Expand All @@ -61,8 +64,8 @@ def PyExec(self):
# Get slice bounds of array
try:
self._calculate_array_points(sample_x, sample_array_len)
except Exception as e:
raise RuntimeError('Failed to calculate array slice boundaries: %s' % e.message)
except Exception as exc:
raise RuntimeError('Failed to calculate array slice boundaries: %s' % exc.message)

max_sample_index = sample_array_len - 1
centre_range_len = self._positive_min_index + self._negative_min_index
Expand All @@ -89,8 +92,10 @@ def PyExec(self):
v_axis_data = mtd[self._sample].getAxis(1).extractValues()

# Take the values we need from the original vertical axis
min_spectrum_index = mtd[self._sample].getIndexFromSpectrumNumber(int(self._spectra_range[0]))
max_spectrum_index = mtd[self._sample].getIndexFromSpectrumNumber(int(self._spectra_range[1]))
min_spectrum_index = mtd[self._sample].getIndexFromSpectrumNumber(
int(self._spectra_range[0]))
max_spectrum_index = mtd[self._sample].getIndexFromSpectrumNumber(
int(self._spectra_range[1]))
new_v_axis_data = v_axis_data[min_spectrum_index:max_spectrum_index + 1]

# Create an empty workspace with enough storage for the new data
Expand Down Expand Up @@ -178,7 +183,8 @@ def validateInputs(self):

num_sample_spectra, _ = CheckHistZero(input_workspace_name)
min_spectra_number = mtd[input_workspace_name].getSpectrum(0).getSpectrumNo()
max_spectra_number = mtd[input_workspace_name].getSpectrum(num_sample_spectra - 1).getSpectrumNo()
max_spectra_number = mtd[input_workspace_name].getSpectrum(
num_sample_spectra - 1).getSpectrumNo()

if spec_min < min_spectra_number:
issues['SpectraRange'] = 'Minimum spectra must be greater than or equal to %d' % min_spectra_number
Expand Down Expand Up @@ -239,7 +245,8 @@ def _setup(self):
if len(self._spectra_range) == 0:
num_sample_spectra, _ = CheckHistZero(self._sample)
min_spectra_number = mtd[self._sample].getSpectrum(0).getSpectrumNo()
max_spectra_number = mtd[self._sample].getSpectrum(num_sample_spectra - 1).getSpectrumNo()
max_spectra_number = mtd[self._sample].getSpectrum(
num_sample_spectra - 1).getSpectrumNo()
self._spectra_range = [min_spectra_number, max_spectra_number]

self._output_workspace = self.getPropertyValue('OutputWorkspace')
Expand Down Expand Up @@ -298,7 +305,8 @@ def _generate_props_table(self):
props_table.addColumn('int', 'PositiveXMinIndex')
props_table.addColumn('int', 'PositiveXMaxIndex')

props_table.addRow([int(self._negative_min_index), int(self._positive_min_index), int(self._positive_max_index)])
props_table.addRow([int(self._negative_min_index), int(self._positive_min_index),
int(self._positive_max_index)])

self.setProperty('OutputPropertiesTable', self._props_output_workspace)

Expand Down
Expand Up @@ -124,7 +124,9 @@ def PyExec(self):
if k in self._ions:
partial_ions[k] = v

partial_workspaces, sum_workspace = self._compute_partial_ion_workflow(partial_ions, frequencies, eigenvectors, weights)
partial_workspaces, sum_workspace = self._compute_partial_ion_workflow(
partial_ions, frequencies,
eigenvectors, weights)

if self._sum_contributions:
# Discard the partial workspaces
Expand All @@ -147,7 +149,9 @@ def PyExec(self):

eigenvectors = file_data[4]

partial_workspaces, sum_workspace = self._compute_partial_ion_workflow(self._ion_dict, frequencies, eigenvectors, weights)
partial_workspaces, sum_workspace = self._compute_partial_ion_workflow(
self._ion_dict, frequencies,
eigenvectors, weights)

# Discard the partial workspaces
for partial_ws in partial_workspaces:
Expand Down Expand Up @@ -288,7 +292,8 @@ def _compute_partial_ion_workflow(self, partial_ions, frequencies, eigenvectors,
scattering_x_section = mtd[self._ws_name].mutableSample().getMaterial().totalScatterXSection()

if self._scale_by_cross_section != 'None':
Scale(InputWorkspace=self._ws_name, OutputWorkspace=self._ws_name, Operation='Multiply', Factor=scattering_x_section)
Scale(InputWorkspace=self._ws_name, OutputWorkspace=self._ws_name,
Operation='Multiply', Factor=scattering_x_section)

partial_workspaces.append(partial_ws_name)
RenameWorkspace(self._ws_name, OutputWorkspace=partial_ws_name)
Expand All @@ -300,9 +305,11 @@ def _compute_partial_ion_workflow(self, partial_ions, frequencies, eigenvectors,
sum_workspace = '__dos_sum'

# Collect spectra into a single workspace
AppendSpectra(OutputWorkspace=sum_workspace, InputWorkspace1=partial_workspaces[0], InputWorkspace2=partial_workspaces[1])
AppendSpectra(OutputWorkspace=sum_workspace, InputWorkspace1=partial_workspaces[0],
InputWorkspace2=partial_workspaces[1])
for ws_idx in xrange(2, len(partial_workspaces)):
AppendSpectra(OutputWorkspace=sum_workspace, InputWorkspace1=sum_workspace, InputWorkspace2=partial_workspaces[ws_idx])
AppendSpectra(OutputWorkspace=sum_workspace, InputWorkspace1=sum_workspace,
InputWorkspace2=partial_workspaces[ws_idx])

# Sum all spectra
SumSpectra(InputWorkspace=sum_workspace, OutputWorkspace=total_workspace)
Expand Down
Expand Up @@ -40,18 +40,21 @@ def PyInit(self):
self.declareProperty(name='Range2Start', defaultValue='', doc='Range 2 start')
self.declareProperty(name='Range2End', defaultValue='', doc='Range 2 end')

self.declareProperty(name='SampleEnvironmentLogName', defaultValue='sample', doc='Name of the sample environment log entry')
self.declareProperty(name='SampleEnvironmentLogName', defaultValue='sample',
doc='Name of the sample environment log entry')

self.declareProperty(WorkspaceProperty('OutputInQ', '', Direction.Output),
doc='Output workspace in Q')

self.declareProperty(WorkspaceProperty('OutputInQSquared', '', Direction.Output),
doc='Output workspace in Q Squared')

self.declareProperty(WorkspaceProperty('OutputELF', '', Direction.Output, PropertyMode.Optional),
self.declareProperty(WorkspaceProperty('OutputELF', '', Direction.Output,
PropertyMode.Optional),
doc='Output workspace ELF')

self.declareProperty(WorkspaceProperty('OutputELT', '', Direction.Output, PropertyMode.Optional),
self.declareProperty(WorkspaceProperty('OutputELT', '', Direction.Output,
PropertyMode.Optional),
doc='Output workspace ELT')

self.declareProperty(name='Plot', defaultValue=False, doc='Plot result spectra')
Expand All @@ -71,13 +74,13 @@ def validateInputs(self):

if range_2_start != '':
try:
val = float(range_2_start)
_ = float(range_2_start)
except ValueError:
issues['Range2Start'] = 'Range 2 start is not a double number'

if range_2_end != '':
try:
val = float(range_2_end)
_ = float(range_2_end)
except ValueError:
issues['Range2End'] = 'Range 2 end is not a double number'

Expand Down Expand Up @@ -110,9 +113,12 @@ def PyExec(self):
q2_ws = '__' + input_ws + '_q2'

if self._range_2_start != '' and self._range_2_end != '':
ElasticWindow(InputWorkspace=input_ws, OutputInQ=q_ws, OutputInQSquared=q2_ws,
Range1Start=self._range_1_start, Range1End=self._range_1_end,
Range2Start=float(self._range_2_start), Range2End=float(self._range_2_end))
ElasticWindow(InputWorkspace=input_ws,
OutputInQ=q_ws, OutputInQSquared=q2_ws,
Range1Start=self._range_1_start,
Range1End=self._range_1_end,
Range2Start=float(self._range_2_start),
Range2End=float(self._range_2_end))
else:
ElasticWindow(InputWorkspace=input_ws, OutputInQ=q_ws, OutputInQSquared=q2_ws,
Range1Start=self._range_1_start, Range1End=self._range_1_end)
Expand All @@ -139,13 +145,19 @@ def PyExec(self):
RenameWorkspace(InputWorkspace=q2_workspaces[0], OutputWorkspace=self._q2_workspace)
else:
# Append the spectra of the first two workspaces
AppendSpectra(InputWorkspace1=q_workspaces[0], InputWorkspace2=q_workspaces[1], OutputWorkspace=self._q_workspace)
AppendSpectra(InputWorkspace1=q2_workspaces[0], InputWorkspace2=q2_workspaces[1], OutputWorkspace=self._q2_workspace)
AppendSpectra(InputWorkspace1=q_workspaces[0], InputWorkspace2=q_workspaces[1],
OutputWorkspace=self._q_workspace)
AppendSpectra(InputWorkspace1=q2_workspaces[0], InputWorkspace2=q2_workspaces[1],
OutputWorkspace=self._q2_workspace)

# Append to the spectra of each remaining workspace
for idx in range(2, len(input_workspace_names)):
AppendSpectra(InputWorkspace1=self._q_workspace, InputWorkspace2=q_workspaces[idx], OutputWorkspace=self._q_workspace)
AppendSpectra(InputWorkspace1=self._q2_workspace, InputWorkspace2=q2_workspaces[idx], OutputWorkspace=self._q2_workspace)
AppendSpectra(InputWorkspace1=self._q_workspace,
InputWorkspace2=q_workspaces[idx],
OutputWorkspace=self._q_workspace)
AppendSpectra(InputWorkspace1=self._q2_workspace,
InputWorkspace2=q2_workspaces[idx],
OutputWorkspace=self._q2_workspace)

# Delete the output workspaces from the ElasticWindow algorithms
for q_ws in q_workspaces:
Expand Down Expand Up @@ -193,12 +205,14 @@ def PyExec(self):
if self._elt_workspace != '':
logger.information('Creating ELT workspace')

# If the ELT workspace was not already created then create it here, otherwise just clone it
# If the ELT workspace was not already created then create it here,
# otherwise just clone it
if self._elf_workspace == '':
Transpose(InputWorkspace=self._q_workspace, OutputWorkspace=self._elt_workspace)
SortXAxis(InputWorkspace=self._elt_workspace, OutputWorkspace=self._elt_workspace)
else:
CloneWorkspace(InputWorkspace=self._elf_workspace, OutputWorkspace=self._elt_workspace)
CloneWorkspace(InputWorkspace=self._elf_workspace,
OutputWorkspace=self._elt_workspace)

_normalize_to_lowest_temp(self._elt_workspace)

Expand Down
@@ -1,6 +1,6 @@
from mantid.simpleapi import *
from mantid.api import PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, PropertyMode
from mantid.kernel import StringListValidator, StringMandatoryValidator, Direction, logger
from mantid.kernel import Direction, logger
from mantid import config
import math
import os
Expand All @@ -20,9 +20,12 @@ def PyInit(self):
optional=PropertyMode.Mandatory, direction=Direction.Input),
doc="Name for the Resolution workspace.")

self.declareProperty(name='EnergyMin', defaultValue=-0.5, doc='Minimum energy for fit. Default=-0.5')
self.declareProperty(name='EnergyMax', defaultValue=0.5, doc='Maximum energy for fit. Default=0.5')
self.declareProperty(name='NumBins', defaultValue=1, doc='Decrease total number of spectrum points by this ratio through merging of intensities from neighbouring bins. Default=1')
self.declareProperty(name='EnergyMin', defaultValue=-0.5,
doc='Minimum energy for fit. Default=-0.5')
self.declareProperty(name='EnergyMax', defaultValue=0.5,
doc='Maximum energy for fit. Default=0.5')
self.declareProperty(name='NumBins', defaultValue=1,
doc='Decrease total number of spectrum points by this ratio through merging of intensities from neighbouring bins. Default=1')

self.declareProperty(MatrixWorkspaceProperty('ParameterWorkspace', '',
direction=Direction.Output, optional=PropertyMode.Optional),
Expand All @@ -32,9 +35,12 @@ def PyInit(self):
direction=Direction.Output, optional=PropertyMode.Optional),
doc='Output workspace')

self.declareProperty(name='Plot', defaultValue=False, doc='Switch Plot Off/On')
self.declareProperty(name='Save', defaultValue=False, doc='Switch Save result to nxs file Off/On')
self.declareProperty(name='DryRun', defaultValue=False, doc='Only calculate and output the parameters')
self.declareProperty(name='Plot', defaultValue=False,
doc='Switch Plot Off/On')
self.declareProperty(name='Save', defaultValue=False,
doc='Switch Save result to nxs file Off/On')
self.declareProperty(name='DryRun', defaultValue=False,
doc='Only calculate and output the parameters')


def PyExec(self):
Expand Down Expand Up @@ -110,7 +116,8 @@ def _calculate_parameters(self):
"""
Calculates the Fury parameters and saves in a table workspace.
"""
CropWorkspace(InputWorkspace=self._sample, OutputWorkspace='__Fury_sample_cropped', Xmin=self._e_min, Xmax=self._e_max)
CropWorkspace(InputWorkspace=self._sample, OutputWorkspace='__Fury_sample_cropped',
Xmin=self._e_min, Xmax=self._e_max)
x_data = mtd['__Fury_sample_cropped'].readX(0)
number_input_points = len(x_data) - 1
num_bins = number_input_points / self._number_points_per_bin
Expand All @@ -135,7 +142,8 @@ def _calculate_parameters(self):

except (AttributeError, IndexError):
resolution = 0.0175
logger.warning('Could not get resolution from IPF, using default value: %f' % resolution)
logger.warning('Could not get resolution from IPF, using default value: %f' % (
resolution))

resolution_bins = int(round((2 * resolution) / self._e_width))

Expand Down Expand Up @@ -178,10 +186,14 @@ def _plot_output(self):


def _add_logs(self):
AddSampleLog(Workspace=self._output_workspace, LogName='fury_resolution_ws', LogType='String', LogText=self._resolution)
AddSampleLog(Workspace=self._output_workspace, LogName='fury_rebin_emin', LogType='Number', LogText=str(self._e_min))
AddSampleLog(Workspace=self._output_workspace, LogName='fury_rebin_ewidth', LogType='Number', LogText=str(self._e_width))
AddSampleLog(Workspace=self._output_workspace, LogName='fury_rebin_emax', LogType='Number', LogText=str(self._e_max))
AddSampleLog(Workspace=self._output_workspace, LogName='fury_resolution_ws',
LogType='String', LogText=self._resolution)
AddSampleLog(Workspace=self._output_workspace, LogName='fury_rebin_emin',
LogType='Number', LogText=str(self._e_min))
AddSampleLog(Workspace=self._output_workspace, LogName='fury_rebin_ewidth',
LogType='Number', LogText=str(self._e_width))
AddSampleLog(Workspace=self._output_workspace, LogName='fury_rebin_emax',
LogType='Number', LogText=str(self._e_max))


def _fury(self):
Expand All @@ -197,7 +209,8 @@ def _fury(self):
CheckHistSame(self._sample, 'Sample', self._resolution, 'Resolution')

rebin_param = str(self._e_min) + ',' + str(self._e_width) + ',' + str(self._e_max)
Rebin(InputWorkspace=self._sample, OutputWorkspace='__sam_rebin', Params=rebin_param, FullBinsOnly=True)
Rebin(InputWorkspace=self._sample, OutputWorkspace='__sam_rebin', Params=rebin_param,
FullBinsOnly=True)

Rebin(InputWorkspace=self._resolution, OutputWorkspace='__res_data', Params=rebin_param)
Integration(InputWorkspace='__res_data', OutputWorkspace='__res_int')
Expand All @@ -223,7 +236,8 @@ def _fury(self):
# Crop nonsense values off workspace
binning = int(math.ceil(mtd[self._output_workspace].blocksize() / 2.0))
bin_v = mtd[self._output_workspace].dataX(0)[binning]
CropWorkspace(InputWorkspace=self._output_workspace, OutputWorkspace=self._output_workspace, XMax=bin_v)
CropWorkspace(InputWorkspace=self._output_workspace, OutputWorkspace=self._output_workspace,
XMax=bin_v)

# Clean up resolution workspaces
DeleteWorkspace('__res_data')
Expand Down

0 comments on commit bddddc2

Please sign in to comment.