Skip to content

Commit

Permalink
Merge branch 'feature/5300_moments_sqw_tab' into develop
Browse files Browse the repository at this point in the history
Refs #5300

Conflicts:
	Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/ConvertToEnergy.ui
	Code/Mantid/MantidQt/CustomInterfaces/src/Indirect.cpp
  • Loading branch information
Samuel Jackson committed Feb 13, 2014
2 parents 3a41549 + 590d2f2 commit 8330000
Show file tree
Hide file tree
Showing 11 changed files with 782 additions and 135 deletions.
@@ -1,60 +1,137 @@
"""*WIKI*
Calculates the <math>n^{th}</math> moment <math>M_n</math> of <math>S(Q,w)</math> where <math>M_n</math> is the integral of <math>w^n*S(Q,w)</math> over all w for <math>n=0</math> to 4.
Calculates the <math>n^{th}</math> moment <math>M_n</math> of <math>y(Q,w)</math> where <math>M_n</math> is the integral of <math>w^n*y(Q,w)</math> over all w for <math>n=0</math> to 4.
*WIKI*"""
# Algorithm to start Bayes programs
from mantid.simpleapi import *
from mantid.api import PythonAlgorithm, AlgorithmFactory
from mantid.kernel import StringListValidator, StringMandatoryValidator
from mantid import config
import os.path
from mantid.api import PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, WorkspaceGroupProperty
from mantid.kernel import Direction
from mantid import config, logger
import sys, os.path, numpy as np

class Moments(PythonAlgorithm):

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

def PyInit(self):
self.setOptionalMessage("Calculates the nth moment of S(q,w)")
self.setWikiSummary("Calculates the nth moment of S(q,w)")
self.setOptionalMessage("Calculates the nth moment of y(q,w)")
self.setWikiSummary("Calculates the nth moment of y(q,w)")

self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File or Workspace')
self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument')
self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004']), doc='Analyser & reflection')
self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number')
self.declareProperty(MatrixWorkspaceProperty("Sample", "", Direction.Input), doc="Sample to use.")
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='MultiplyBy', defaultValue=1.0, doc='Scale factor to multiply S(Q,w). Default=1.0')
self.declareProperty('Verbose',defaultValue=True, doc='Switch Verbose Off/On')
self.declareProperty('Plot',defaultValue=True, doc='Switch Plot Off/On')
self.declareProperty('Save',defaultValue=False, doc='Switch Save result to nxs file Off/On')
self.declareProperty(name='Scale', defaultValue=1.0, doc='Scale factor to multiply y(Q,w). Default=1.0')
self.declareProperty(name='Verbose', defaultValue=False, doc='Switch Verbose Off/On')
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(WorkspaceGroupProperty("OutputWorkspace", "", Direction.Output), doc="group_workspace workspace that includes all calculated moments.")

def PyExec(self):
from IndirectCommon import CheckHistZero, CheckElimits, StartTime, EndTime, getDefaultWorkingDirectory

sample_workspace = self.getPropertyValue('Sample')
output_workspace = self.getPropertyValue('OutputWorkspace')
factor = self.getProperty('Scale').value
emin = self.getProperty('EnergyMin').value
emax = self.getProperty('EnergyMax').value
erange = [emin, emax]

Verbose = self.getProperty('Verbose').value
Plot = self.getProperty('Plot').value
Save = self.getProperty('Save').value

StartTime('Moments')
num_spectra,num_w = CheckHistZero(sample_workspace)

if Verbose:
text = 'Sample %s has %d Q values & %d w values' % (sample_workspace, num_spectra, num_w)
logger.notice(text)

x = np.asarray(mtd[sample_workspace].readX(0))
CheckElimits(erange,x)

samWS = '__moments_cropped_ws'
CropWorkspace(InputWorkspace=sample_workspace, OutputWorkspace=samWS, XMin=erange[0], XMax=erange[1])

if Verbose:
logger.notice('Energy range is %f to %f' % (erange[0], erange[1]))

if factor > 0.0:
Scale(InputWorkspace=samWS, OutputWorkspace=samWS, Factor=factor, Operation='Multiply')
if Verbose:
logger.notice('y(q,w) scaled by %f' % factor)

#calculate delta x
x = np.asarray(mtd[samWS].readX(0))
delta_x = x[1:] - x[:-1]
x = x[:-1]
#calculate moments for workspace
yM0, yM1, yM2, yM3, yM4 = [],[],[],[],[]
for index in range(num_spectra):
if Verbose:
logger.notice('group_workspace %d at Q = %d' % (index+1, index))

y = np.asarray(mtd[samWS].readY(index))

S0 = y * delta_x
m0 = np.sum(S0)

S1 = (x * S0)
m1 = np.sum(S1) / m0
S2 = x * S1
m2 = np.sum(S2) / m0
S3 = x * S2
m3 = np.sum(S3) / m0
S4 = x * S3
m4 = np.sum(S4) / m0

if Verbose:
text = 'M0 = %f ; M2 = %f ; M4 = %f' % (m0, m2, m4)
logger.notice(text)

yM0.append(m0)
yM1.append(m1)
yM2.append(m2)
yM4.append(m4)

output_workspace = output_workspace + '_Moments'
Q = np.arange(num_spectra)
CreateWorkspace(OutputWorkspace=output_workspace+'_M0', DataX=Q, DataY=yM0,
Nspec=1, UnitX='MomentumTransfer')
CreateWorkspace(OutputWorkspace=output_workspace+'_M1', DataX=Q, DataY=yM1,
Nspec=1, UnitX='MomentumTransfer')
CreateWorkspace(OutputWorkspace=output_workspace+'_M2', DataX=Q, DataY=yM2,
Nspec=1, UnitX='MomentumTransfer')
CreateWorkspace(OutputWorkspace=output_workspace+'_M4', DataX=Q, DataY=yM4,
Nspec=1, UnitX='MomentumTransfer')

group_workspaces = output_workspace+'_M0,'+output_workspace+'_M1,'+output_workspace+'_M2,'+output_workspace+'_M4'
GroupWorkspaces(InputWorkspaces=group_workspaces,OutputWorkspace=output_workspace)
DeleteWorkspace(samWS)

if Save:
workdir = getDefaultWorkingDirectory()
opath = os.path.join(workdir,output_workspace+'.nxs')
SaveNexusProcessed(InputWorkspace=output_workspace, Filename=opath)

if Verbose:
logger.notice('Output file : ' + opath)

if Plot:
self._plot_moments(output_workspace)

self.log().information('Moments calculation')
inType = self.getPropertyValue('InputType')
prefix = self.getPropertyValue('Instrument')
ana = self.getPropertyValue('Analyser')
sn = self.getPropertyValue('SamNumber')
sam = prefix+sn+'_'+ana+'_sqw'
emin = self.getPropertyValue('EnergyMin')
emax = self.getPropertyValue('EnergyMax')
erange = [float(emin), float(emax)]
factor = self.getPropertyValue('MultiplyBy')
factor = float(factor)

verbOp = self.getProperty('Verbose').value
plotOp = self.getProperty('Plot').value
saveOp = self.getProperty('Save').value
workdir = config['defaultsave.directory']
if inType == 'File':
spath = os.path.join(workdir, sam+'.nxs') # path name for sample nxs file
self.log().notice('Input from File : '+spath)
LoadNexus(Filename=spath, OutputWorkspace=sam)
else:
self.log().notice('Input from Workspace : '+sam)
from IndirectEnergyConversion import SqwMoments
SqwMoments(sam,erange,factor,verbOp,plotOp,saveOp)
self.setProperty("OutputWorkspace", output_workspace)

EndTime('Moments')

def _plot_moments(self, inputWS):
from IndirectImport import import_mantidplot
mp = import_mantidplot()

m0_plot=mp.plotSpectrum(inputWS+'_M0',0)
m2_plot=mp.plotSpectrum([inputWS+'_M2',inputWS+'_M4'],0)

AlgorithmFactory.subscribe(Moments) # Register algorithm with Mantid
3 changes: 3 additions & 0 deletions Code/Mantid/MantidQt/CustomInterfaces/CMakeLists.txt
Expand Up @@ -22,6 +22,7 @@ set ( SRC_FILES
src/IndirectLoadAsciiTab.cpp
src/IndirectNeutron.cpp
src/IndirectMolDyn.cpp
src/IndirectMoments.cpp
src/JumpFit.cpp
src/MSDFit.cpp
src/MuonAnalysis.cpp
Expand Down Expand Up @@ -76,6 +77,7 @@ set ( INC_FILES
inc/MantidQtCustomInterfaces/IndirectLoadAsciiTab.h
inc/MantidQtCustomInterfaces/IndirectNeutron.h
inc/MantidQtCustomInterfaces/IndirectMolDyn.h
inc/MantidQtCustomInterfaces/IndirectMoments.h
inc/MantidQtCustomInterfaces/JumpFit.h
inc/MantidQtCustomInterfaces/MSDFit.h
inc/MantidQtCustomInterfaces/MuonAnalysis.h
Expand Down Expand Up @@ -127,6 +129,7 @@ set ( MOC_FILES inc/MantidQtCustomInterfaces/Background.h
inc/MantidQtCustomInterfaces/IndirectLoadAsciiTab.h
inc/MantidQtCustomInterfaces/IndirectNeutron.h
inc/MantidQtCustomInterfaces/IndirectMolDyn.h
inc/MantidQtCustomInterfaces/IndirectMoments.h
inc/MantidQtCustomInterfaces/JumpFit.h
inc/MantidQtCustomInterfaces/MSDFit.h
inc/MantidQtCustomInterfaces/MuonAnalysis.h
Expand Down
@@ -1,8 +1,40 @@
#ifndef MANTID_CUSTOMINTERFACES_C2ETAB_H_
#define MANTID_CUSTOMINTERFACES_C2ETAB_H_

#include "MantidAPI/AlgorithmManager.h"
#include "MantidAPI/AnalysisDataService.h"
#include "MantidKernel/System.h"
#include "MantidQtAPI/MantidQwtMatrixWorkspaceData.h"
#include "MantidQtCustomInterfaces/ConvertToEnergy.h"
#include "MantidQtMantidWidgets/RangeSelector.h"

#include <QMap>
#include <QDoubleValidator>
#include <QtDoublePropertyManager>
#include <QtIntPropertyManager>
#include <QtTreePropertyBrowser>

#include <qwt_plot.h>
#include <qwt_plot_curve.h>


// Suppress a warning coming out of code that isn't ours
#if defined(__INTEL_COMPILER)
#pragma warning disable 1125
#elif defined(__GNUC__)
#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
#pragma GCC diagnostic push
#endif
#pragma GCC diagnostic ignored "-Woverloaded-virtual"
#endif
#include "DoubleEditorFactory.h"
#if defined(__INTEL_COMPILER)
#pragma warning enable 1125
#elif defined(__GNUC__)
#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6 )
#pragma GCC diagnostic pop
#endif
#endif

namespace MantidQt
{
Expand Down Expand Up @@ -46,9 +78,40 @@ namespace CustomInterfaces
void setupTab();
void validateTab();

protected:
// Run the load algorithm with the given file name and output name
bool loadFile(const QString& filename, const QString& outputName);
/// Function to plot a workspace to the miniplot using a workspace name
void plotMiniPlot(const QString& workspace, size_t index);
/// Function to plot a workspace to the miniplot using a workspace pointer
void plotMiniPlot(const Mantid::API::MatrixWorkspace_const_sptr & workspace, size_t wsIndex);
/// Function to get the range of the curve displayed on the mini plot
std::pair<double,double> getCurveRange();
/// Function to set the range limits of the plot
void setPlotRange(QtProperty* min, QtProperty* max, const std::pair<double, double>& bounds);
/// Function to set the range selector on the mini plot
void setMiniPlotGuides(QtProperty* lower, QtProperty* upper, const std::pair<double, double>& bounds);

/// Plot of the input
QwtPlot* m_plot;
/// Curve on the plot
QwtPlotCurve* m_curve;
/// Range selector widget for mini plot
MantidQt::MantidWidgets::RangeSelector* m_rangeSelector;
/// Tree of the properties
QtTreePropertyBrowser* m_propTree;
/// Internal list of the properties
QMap<QString, QtProperty*> m_properties;
/// Double manager to create properties
QtDoublePropertyManager* m_dblManager;
/// Double editor facotry for the properties browser
DoubleEditorFactory* m_dblEdFac;

signals:
void runAsPythonScript(const QString & code, bool no_output);
/// Send signal to parent window to show a message box to user
void showMessageBox(const QString& message);
/// Run a python script
void runAsPythonScript(const QString & code, bool no_output);

private:
/// Overidden by child class.
Expand All @@ -60,6 +123,7 @@ namespace CustomInterfaces

protected:
Ui::ConvertToEnergy m_uiForm;

};
} // namespace CustomInterfaces
} // namespace Mantid
Expand Down

0 comments on commit 8330000

Please sign in to comment.