Skip to content

Commit

Permalink
Merge branch 'bugfix/10057_indirecttrans_python_algorithm' into develop
Browse files Browse the repository at this point in the history
Conflicts:
	Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CMakeLists.txt
	Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IndirectDataReduction.ui

Refs #10057
  • Loading branch information
DanNixon committed Sep 18, 2014
2 parents e6dde10 + 422979c commit 910d742
Show file tree
Hide file tree
Showing 11 changed files with 200 additions and 149 deletions.
1 change: 1 addition & 0 deletions Code/Mantid/Build/Jenkins/buildscript
Expand Up @@ -13,6 +13,7 @@
# Print out the versions of things we are using
###############################################################################
cmake --version
echo "SHA1=${sha1}"

###############################################################################
# OS X setup steps
Expand Down
Expand Up @@ -7,7 +7,7 @@
import os.path


class IndirectTransmissionReduction(PythonAlgorithm):
class IndirectTransmissionMonitor(PythonAlgorithm):

def category(self):
return "Workflow\\Inelastic;PythonAlgorithms;Inelastic"
Expand All @@ -16,82 +16,94 @@ def summary(self):
return "Calculates the sample transmission using the raw data files of the sample and its background or container."

def PyInit(self):
self.declareProperty(FileProperty('SampleFile', '', FileAction.Load, extensions=['raw']),
doc='Raw sample run file')
self.declareProperty(FileProperty('CanFile', '', FileAction.Load, extensions=['raw']),
doc='Raw background or can run file')
self.declareProperty(WorkspaceProperty('SampleWorkspace', '', direction=Direction.Input),
doc='Sample workspace')

self.declareProperty(WorkspaceProperty('CanWorkspace', '', direction=Direction.Input),
doc='Background/can workspace')

self.declareProperty(WorkspaceProperty('OutputWorkspace', '', direction=Direction.Output,
optional=PropertyMode.Optional),
doc='Output workspace group')

self.declareProperty(name='Verbose', defaultValue=False, doc='Output more verbose message to log')
self.declareProperty(name='Plot', defaultValue=False, doc='Plot result workspace')
self.declareProperty(name='Save', defaultValue=False, doc='Save result workspace to nexus file in the default save directory')

def PyExec(self):
from IndirectCommon import StartTime, EndTime
StartTime('IndirectTransmissionReduction')
StartTime('IndirectTransmissionMonitor')

sample_filepath = self.getProperty("SampleFile").value
can_filepath = self.getProperty("CanFile").value
sample_ws_in = self.getPropertyValue("SampleWorkspace")
can_ws_in = self.getPropertyValue("CanWorkspace")
out_ws = self.getPropertyValue('OutputWorkspace')
verbose = self.getProperty("Verbose").value
plot = self.getProperty("Plot").value
save = self.getProperty("Save").value

sample_filename = os.path.basename(sample_filepath)
ws_basename, _ = os.path.splitext(sample_filename)
ws_basename = str(sample_ws_in)

self.TransMon(ws_basename, 'Sam', sample_filepath, verbose)
self.TransMon(ws_basename, 'Can', can_filepath, verbose)
self._trans_mon(ws_basename, 'Sam', sample_ws_in)
self._trans_mon(ws_basename, 'Can', can_ws_in)

# Divide sample and can workspaces
# Generate workspace names
sam_ws = ws_basename + '_Sam'
can_ws = ws_basename + '_Can'
tr_ws = ws_basename + '_Trans'
Divide(LHSWorkspace=sam_ws, RHSWorkspace=can_ws, OutputWorkspace=tr_ws)
trans = numpy.average(mtd[tr_ws].readY(0))
trans_ws = ws_basename + '_Trans'

# Divide sample and can workspaces
Divide(LHSWorkspace=sam_ws, RHSWorkspace=can_ws, OutputWorkspace=trans_ws)
trans = numpy.average(mtd[trans_ws].readY(0))

AddSampleLog(Workspace=trans_ws, LogName='can_workspace', LogType='String', LogText=can_ws_in)

# Generate an output workspace name if none provided
if out_ws == '':
out_ws = ws_basename + '_Transmission'

# Group workspaces
trans_ws = ws_basename + '_Transmission'
group = sam_ws + ',' + can_ws + ',' + tr_ws
GroupWorkspaces(InputWorkspaces=group, OutputWorkspace=trans_ws)
group = sam_ws + ',' + can_ws + ',' + trans_ws
GroupWorkspaces(InputWorkspaces=group, OutputWorkspace=out_ws)

self.setProperty('OutputWorkspace', out_ws)

if verbose:
logger.notice('Transmission : ' + str(trans))

# Save the tranmissin workspace group to a nexus file
if save:
workdir = config['defaultsave.directory']
path = os.path.join(workdir, trans_ws + '.nxs')
SaveNexusProcessed(InputWorkspace=trans_ws, Filename=path)
path = os.path.join(workdir, out_ws + '.nxs')
SaveNexusProcessed(InputWorkspace=out_ws, Filename=path)
if verbose:
logger.notice('Output file created : ' + path)

# Plot spectra from transmission workspace
if plot:
mtd_plot = import_mantidplot()
mtd_plot.plotSpectrum(trans_ws, 0)
mtd_plot.plotSpectrum(out_ws, 0)

EndTime('IndirectTransmissionMonitor')

EndTime('IndirectTransmissionReduction')
def _unwrap_mon(self, input_ws):
out_ws = '_unwrap_mon_out'

def UnwrapMon(self, inWS):
# Unwrap monitor - inWS contains M1,M2,S1 - outWS contains unwrapped Mon
# Unwrap s1>2 to L of S2 (M2) ie 38.76 Ouput is in wavelength
out, join = UnwrapMonitor(InputWorkspace=inWS, LRef='37.86')
out_ws = 'out'
_, join = UnwrapMonitor(InputWorkspace=input_ws, OutputWorkspace=out_ws, LRef='37.86')

# Fill bad (dip) in spectrum
RemoveBins(InputWorkspace=out_ws, OutputWorkspace=out_ws, Xmin=join-0.001, Xmax=join+0.001, Interpolation="Linear")
RemoveBins(InputWorkspace=out_ws, OutputWorkspace=out_ws, Xmin=join - 0.001, Xmax=join + 0.001, Interpolation="Linear")
FFTSmooth(InputWorkspace=out_ws, OutputWorkspace=out_ws, WorkspaceIndex=0, IgnoreXBins=True) # Smooth - FFT

DeleteWorkspace(inWS) # delete monWS
DeleteWorkspace(input_ws) # delete monWS

return out_ws

def TransMon(self, ws_basename, file_type, filename, verbose):
if verbose:
logger.notice('Raw file : ' + file_type)

LoadRaw(Filename=filename, OutputWorkspace='__m1', SpectrumMin=1, SpectrumMax=1)
LoadRaw(Filename=filename, OutputWorkspace='__m2', SpectrumMin=2, SpectrumMax=2)
LoadRaw(Filename=filename, OutputWorkspace='__det', SpectrumMin=3, SpectrumMax=3)
def _trans_mon(self, ws_basename, file_type, input_ws):
CropWorkspace(InputWorkspace=input_ws, OutputWorkspace='__m1', StartWorkspaceIndex=0, EndWorkspaceIndex=0)
CropWorkspace(InputWorkspace=input_ws, OutputWorkspace='__m2', StartWorkspaceIndex=1, EndWorkspaceIndex=1)
CropWorkspace(InputWorkspace=input_ws, OutputWorkspace='__det', StartWorkspaceIndex=2, EndWorkspaceIndex=2)

# Check for single or multiple time regimes
mon_tcb_start = mtd['__m1'].readX(0)[0]
Expand All @@ -101,22 +113,21 @@ def TransMon(self, ws_basename, file_type, filename, verbose):
mon_ws = '__Mon'

if spec_tcb_start == mon_tcb_start:
mon_ws = self.UnwrapMon('__m1') # unwrap the monitor spectrum and convert to wavelength
mon_ws = self._unwrap_mon('__m1') # unwrap the monitor spectrum and convert to wavelength
RenameWorkspace(InputWorkspace=mon_ws, OutputWorkspace='__Mon1')
else:
ConvertUnits(InputWorkspace='__m1', OutputWorkspace='__Mon1', Target="Wavelength")


ConvertUnits(InputWorkspace='__m2', OutputWorkspace='__Mon2', Target="Wavelength")

DeleteWorkspace('__m2') # delete monWS

x_in = mtd['__Mon1'].readX(0)
xmin1 = mtd['__Mon1'].readX(0)[0]
xmax1 = mtd['__Mon1'].readX(0)[len(x_in)-1]
xmax1 = mtd['__Mon1'].readX(0)[len(x_in) - 1]
x_in = mtd['__Mon2'].readX(0)
xmin2 = mtd['__Mon2'].readX(0)[0]
xmax2 = mtd['__Mon2'].readX(0)[len(x_in)-1]
xmax2 = mtd['__Mon2'].readX(0)[len(x_in) - 1]
wmin = max(xmin1, xmin2)
wmax = min(xmax1, xmax2)

Expand All @@ -128,5 +139,6 @@ def TransMon(self, ws_basename, file_type, filename, verbose):
DeleteWorkspace('__Mon1') # delete monWS
DeleteWorkspace('__Mon2') # delete monWS


# Register algorithm with Mantid
AlgorithmFactory.subscribe(IndirectTransmissionReduction)
AlgorithmFactory.subscribe(IndirectTransmissionMonitor)
Expand Up @@ -15,8 +15,8 @@ set ( TEST_PY_FILES
FindReflectometryLinesTest.py
GetEiT0atSNSTest.py
IndirectILLReductionTest.py
IndirectTransmissionReductionTest.py
IndirectTransmissionTest.py
IndirectTransmissionMonitorTest.py
LoadFullprofFileTest.py
LoadLiveDataTest.py
LoadLogPropertyTableTest.py
Expand Down
@@ -0,0 +1,48 @@
import unittest, os
import mantid
from mantid.simpleapi import *

class IndirectTransmissionMonitorTest(unittest.TestCase):

@classmethod
def setUpClass(cls):
##TODO: Create sample workspaces
sample_workspace = Load('IRS26176.RAW')
can_workspace = Load('IRS26173.RAW')

cls._sample_workspace = sample_workspace
cls._can_workspace = can_workspace

def setUp(self):
self.kwargs = {}
self.kwargs['SampleWorkspace'] = self._sample_workspace
self.kwargs['CanWorkspace'] = self._can_workspace
self.kwargs['Verbose'] = True
self.kwargs['Plot'] = False

def tearDown(self):
# Clean up saved nexus files
path = os.path.join(config['defaultsave.directory'], 'IndirectTransmissionMonitorTest.nxs')
if os.path.isfile(path):
try:
os.remove(path)
except IOError, _:
pass

def test_basic(self):
trans_workspace = IndirectTransmissionMonitor(**self.kwargs)

self.assertTrue(isinstance(trans_workspace, mantid.api.WorkspaceGroup), msg='Result should be a workspace group')
self.assertEqual(trans_workspace.size(), 3, msg='Transmission workspace group should have 3 workspaces: sample, can and transfer')

def test_nexus_save(self):
self.kwargs['Save'] = True
self.kwargs['OutputWorkspace'] = 'IndirectTransmissionMonitorTest'

IndirectTransmissionMonitor(**self.kwargs)

path = os.path.join(config['defaultsave.directory'], 'IndirectTransmissionMonitorTest.nxs')
self.assertTrue(os.path.isfile(path), msg='Transmission workspace should be saved to default save directory')

if __name__ == '__main__':
unittest.main()

This file was deleted.

Expand Up @@ -1613,40 +1613,70 @@ Later steps in the process (saving, renaming) will not be done.</string>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="1">
<widget class="MantidQt::MantidWidgets::MWRunFiles" name="transInputFile" native="true">
<property name="label" stdset="0">
<widget class="MantidQt::MantidWidgets::DataSelector" name="trans_dsSampleInput" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="autoLoad" stdset="0">
<bool>true</bool>
</property>
<property name="loadLabelText" stdset="0">
<string/>
</property>
<property name="fileExtensions" stdset="0">
<property name="workspaceSuffixes" stdset="0">
<stringlist/>
</property>
<property name="fileBrowserSuffixes" stdset="0">
<stringlist>
<string>.raw</string>
</stringlist>
</property>
<property name="showLoad" stdset="0">
<bool>false</bool>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="trans_lbSample">
<property name="text">
<string>Sample:</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="MantidQt::MantidWidgets::MWRunFiles" name="transCanFile" native="true">
<property name="label" stdset="0">
<widget class="MantidQt::MantidWidgets::DataSelector" name="trans_dsCanInput" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="autoLoad" stdset="0">
<bool>true</bool>
</property>
<property name="loadLabelText" stdset="0">
<string/>
</property>
<property name="fileExtensions" stdset="0">
<property name="workspaceSuffixes" stdset="0">
<stringlist/>
</property>
<property name="fileBrowserSuffixes" stdset="0">
<stringlist>
<string>.raw</string>
</stringlist>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>Sample File: </string>
<property name="showLoad" stdset="0">
<bool>false</bool>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_8">
<widget class="QLabel" name="trans_lbBackground">
<property name="text">
<string>Can/Background File:</string>
<string>Background:</string>
</property>
</widget>
</item>
Expand Down Expand Up @@ -2702,8 +2732,6 @@ Later steps in the process (saving, renaming) will not be done.</string>
<tabstop>slice_ckVerbose</tabstop>
<tabstop>slice_ckPlot</tabstop>
<tabstop>slice_ckSave</tabstop>
<tabstop>transInputFile</tabstop>
<tabstop>transCanFile</tabstop>
<tabstop>trans_ckVerbose</tabstop>
<tabstop>trans_ckPlot</tabstop>
<tabstop>trans_ckSave</tabstop>
Expand Down
Expand Up @@ -408,8 +408,6 @@ void IndirectDataReduction::loadSettings()
m_uiForm.ind_mapFile->readSettings(settings.group());
m_uiForm.slice_calibFile->readSettings(settings.group());
m_uiForm.moment_dsInput->readSettings(settings.group());
m_uiForm.transInputFile->readSettings(settings.group());
m_uiForm.transCanFile->readSettings(settings.group());
m_uiForm.sqw_dsSampleInput->readSettings(settings.group());
settings.endGroup();
}
Expand Down

0 comments on commit 910d742

Please sign in to comment.