Skip to content

Commit

Permalink
Moved CreateCalibrationWOrkspace to it's own algorithm
Browse files Browse the repository at this point in the history
Refs #10065
  • Loading branch information
DanNixon committed Aug 11, 2014
1 parent 9d8db81 commit 83838a3
Show file tree
Hide file tree
Showing 6 changed files with 225 additions and 188 deletions.
@@ -0,0 +1,110 @@
from mantid.kernel import *
from mantid.api import *
from mantid.simpleapi import *

import os.path


class CreateCalibrationWorkspace(DataProcessorAlgorithm):

def category(self):
return "Workflow\\Inelastic;PythonAlgorithms;Inelastic"

def summary(self):
return "Creates a calibration workspace from a White-Beam Vanadium run."

def PyInit(self):
self.declareProperty(FileProperty('InputFiles', '',
action=FileAction.Load), doc='Comma separated list of input files')

self.declareProperty(WorkspaceProperty('OutputWorkspace', '',
direction=Direction.Output), doc='Output workspace for calibration data')

self.declareProperty(name='DetectorRange', defaultValue='',
validator=StringMandatoryValidator(), doc='Range of detectors')

self.declareProperty(name='PeakRange', defaultValue='',
validator=StringMandatoryValidator(), doc='')

self.declareProperty(name='BackgroundRange', defaultValue='',
validator=StringMandatoryValidator(), doc='')

self.declareProperty(name='ScaleFactor', defaultValue='', doc='')

self.declareProperty(name='Plot', defaultValue=False, doc='Plot the calibration data')

def PyExec(self):
from mantid import logger
from IndirectCommon import StartTime, EndTime
StartTime('CreateCalibrationWorkspace')

input_files = self.getPropertyValue('InputFiles').split(',')
out_ws = self.getPropertyValue('OutputWorkspace')

peak_range = self.getPropertyValue('PeakRange').split(',')
back_range = self.getPropertyValue('BackgroundRange').split(',')
spec_range = self.getPropertyValue('DetectorRange').split(',')

intensity_scale = self.getPropertyValue('ScaleFactor')
if intensity_scale == '':
intensity_scale = None
else:
intensity_scale = float(intensity_scale)

plot = self.getProperty('Plot').value

runs = []
for in_file in input_files:
(_, filename) = os.path.split(in_file)
(root, _) = os.path.splitext(filename)
try:
Load(Filename=in_file, OutputWorkspace=root,
SpectrumMin=int(spec_range[0]), SpectrumMax=int(spec_range[1]),
LoadLogFiles=False)
runs.append(root)
except:
logger.error('Indirect: Could not load raw file: ' + in_file)

calib_ws_name = 'calibration'
if len(runs) > 1:
MergeRuns(InputWorkspaces=",".join(runs), OutputWorkspace=calib_ws_name)
factor = 1.0 / len(runs)
Scale(InputWorkspace=calib_ws_name, OutputWorkspace=calib_ws_name, Factor=factor)
else:
calib_ws_name = runs[0]

CalculateFlatBackground(InputWorkspace=calib_ws_name, OutputWorkspace=calib_ws_name,
StartX=float(back_range[0]), EndX=float(back_range[1]), Mode='Mean')

from inelastic_indirect_reduction_steps import NormaliseToUnityStep
ntu = NormaliseToUnityStep()
ntu.set_factor(intensity_scale)
ntu.set_peak_range(float(peak_range[0]), float(peak_range[1]))
ntu.execute(None, calib_ws_name)

RenameWorkspace(InputWorkspace=calib_ws_name, OutputWorkspace=out_ws)

## Add sample logs to output workspace
if intensity_scale:
AddSampleLog(Workspace=out_ws, LogName='Scale Factor', LogType='Number', LogText=str(intensity_scale))
AddSampleLog(Workspace=out_ws, LogName='Peak Min', LogType='Number', LogText=peak_range[0])
AddSampleLog(Workspace=out_ws, LogName='Peak Max', LogType='Number', LogText=peak_range[1])
AddSampleLog(Workspace=out_ws, LogName='Back Min', LogType='Number', LogText=back_range[0])
AddSampleLog(Workspace=out_ws, LogName='Back Max', LogType='Number', LogText=back_range[1])

## Remove old workspaces
if len(runs) > 1:
for run in runs:
DeleteWorkspace(Workspace=run)

logger.notice(str(plot))
if plot:
from mantidplot import plotTimeBin
plotTimeBin(out_ws, 0)

self.setProperty('OutputWorkspace', out_ws)

EndTime('CreateCalibrationWorkspace')

# Register algorithm with Mantid
AlgorithmFactory.subscribe(CreateCalibrationWorkspace)
Expand Up @@ -7,6 +7,7 @@ set ( TEST_PY_FILES
ConjoinSpectraTest.py
CorrectLogTimesTest.py
CreateLeBailFitInputTest.py
CreateCalibrationWorkspaceTest.py
CreateWorkspaceTest.py
DakotaChiSquaredTest.py
DSFinterpTest.py
Expand Down
@@ -0,0 +1,17 @@
import unittest
import mantid


class CreateCalibrationWorkspaceTest(unittest.TestCase):

def setUp(self):
pass

def tearDown(self):
pass

def test_simple(self):
pass

if __name__ == "__main__":
unittest.main()
100 changes: 52 additions & 48 deletions Code/Mantid/MantidQt/CustomInterfaces/src/IndirectCalibration.cpp
Expand Up @@ -160,63 +160,67 @@ namespace CustomInterfaces

void IndirectCalibration::run()
{
using namespace Mantid::API;

QString file = m_uiForm.cal_leRunNo->getFirstFilename();
QString filenames = "[r'"+m_uiForm.cal_leRunNo->getFilenames().join("', r'")+"']";

QString reducer = "from mantid.simpleapi import SaveNexus\n"
"from inelastic_indirect_reduction_steps import CreateCalibrationWorkspace\n"
"calib = CreateCalibrationWorkspace()\n"
"calib.set_files(" + filenames + ")\n"
"calib.set_detector_range(" + m_uiForm.leSpectraMin->text() + "-1, " + m_uiForm.leSpectraMax->text() + "-1)\n"
"calib.set_parameters(" + m_properties["CalBackMin"]->valueText() + ","
+ m_properties["CalBackMax"]->valueText() + ","
+ m_properties["CalPeakMin"]->valueText() + ","
+ m_properties["CalPeakMax"]->valueText() + ")\n"
"calib.set_analyser('" + m_uiForm.cbAnalyser->currentText() + "')\n"
"calib.set_reflection('" + m_uiForm.cbReflection->currentText() + "')\n";

//Scale values by arbitrary scalar if requested
QString filenames = m_uiForm.cal_leRunNo->getFilenames().join(",");

std::string outputWorkspaceName = "out_ws"; //TODO

//TODO: Preregister workspace name

IAlgorithm_sptr calibrationAlg = AlgorithmManager::Instance().create("CreateCalibrationWorkspace", -1);
calibrationAlg->initialize();

calibrationAlg->setProperty("InputFiles", filenames.toStdString());
calibrationAlg->setProperty("OutputWorkspace", outputWorkspaceName);

QString detectorRange = m_uiForm.leSpectraMin->text() + "," + m_uiForm.leSpectraMax->text();
QString peakRange = m_properties["CalPeakMin"]->valueText() + "," + m_properties["CalPeakMax"]->valueText();
QString backgroundRange = m_properties["CalBackMin"]->valueText() + "," + m_properties["CalBackMax"]->valueText();

calibrationAlg->setProperty("DetectorRange", detectorRange.toStdString());
calibrationAlg->setProperty("PeakRange", peakRange.toStdString());
calibrationAlg->setProperty("BackgroundRange", backgroundRange.toStdString());

calibrationAlg->setProperty("Plot", m_uiForm.cal_ckPlotResult->isChecked());

if(m_uiForm.cal_ckIntensityScaleMultiplier->isChecked())
{
QString scale = m_uiForm.cal_leIntensityScaleMultiplier->text();
if(scale.isEmpty())
{
scale = "1.0";
}
reducer += "calib.set_intensity_scale("+scale+")\n";
}

reducer += "calib.execute(None, None)\n"
"result = calib.result_workspace()\n"
"print result\n";
scale = "1.0";
calibrationAlg->setProperty("ScaleFactor", scale.toStdString());
}

if( m_uiForm.cal_ckSave->isChecked() )
{
reducer +=
"SaveNexus(InputWorkspace=result, Filename=result+'.nxs')\n";
}
if( m_uiForm.cal_ckSave->isChecked() )
{
IAlgorithm_sptr saveAlg = AlgorithmManager::Instance().create("SaveNexus", -1);
saveAlg->initialize();

if ( m_uiForm.cal_ckPlotResult->isChecked() )
{
reducer += "from mantidplot import plotTimeBin\n"
"plotTimeBin(result, 0)\n";
}
saveAlg->setProperty("InputWorkspace", outputWorkspaceName);
saveAlg->setProperty("Filename", outputWorkspaceName + ".nxs");

QString pyOutput = m_pythonRunner.runPythonCode(reducer).trimmed();
//TODO: Add to batch queue
}

if ( pyOutput == "" )
{
emit showMessageBox("An error occurred creating the calib file.\n");
}
else
{
if ( m_uiForm.cal_ckRES->isChecked() )
{
createRESfile(filenames);
}
m_uiForm.ind_calibFile->setFileTextWithSearch(pyOutput + ".nxs");
m_uiForm.ckUseCalib->setChecked(true);
}
//TODO: Run batch
runAlgorithm(calibrationAlg);

//TODO: Move this to a slot
/* if ( pyOutput == "" ) */
/* { */
/* emit showMessageBox("An error occurred creating the calib file.\n"); */
/* } */
/* else */
/* { */
/* if ( m_uiForm.cal_ckRES->isChecked() ) */
/* { */
/* createRESfile(filenames); */
/* } */
/* m_uiForm.ind_calibFile->setFileTextWithSearch(pyOutput + ".nxs"); */
/* m_uiForm.ckUseCalib->setChecked(true); */
/* } */
}

bool IndirectCalibration::validate()
Expand Down
@@ -0,0 +1,45 @@
.. algorithm::

.. summary::

.. alias::

.. properties::

Description
-----------

TODO

Usage
-----
**Example - create calibration workspace for IRIS**

.. include:: ../usagedata-note.txt

.. testcode:: ExCreateCalibrationWorkspaceSimple

import os

# Create a calibration workspace
cal_ws = CreateCalibrationWorkspace(InputFiles='IRS38633.raw', DetectorRange='3,53', PeakRange='62500,65000', BackgroundRange='59000,61500')

# Save the workspace to a NeXus file
calib_file = 'iris_calibration.nxs'
SaveNexus(InputWorkspace=cal_ws, Filename=calib_file)

# Check the output file
print "File Exists:", os.path.exists(calib_file)

Output:

.. testoutput:: ExCreateCalibrationWorkspaceSimple

File Exists: True

.. testcleanup:: ExCreateCalibrationWorkspaceSimple

os.remove(calib_file)


.. categories::

0 comments on commit 83838a3

Please sign in to comment.