From c93857459328845a14c3ea537516e3bfa0a0e00c Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Fri, 19 Sep 2014 13:51:44 +0100 Subject: [PATCH 001/414] Add first cut at integrating S. Millers' system monitor. At the moment it requires psutil to work. Refs #9843 --- Code/Mantid/MantidPlot/CMakeLists.txt | 22 +- Code/Mantid/MantidPlot/SysMon/README.md | 25 + Code/Mantid/MantidPlot/SysMon/SysMon.pyw | 106 +++ Code/Mantid/MantidPlot/SysMon/__init__.py | 0 Code/Mantid/MantidPlot/SysMon/config.py | 16 + Code/Mantid/MantidPlot/SysMon/sysmon.py | 224 ++++++ Code/Mantid/MantidPlot/SysMon/sysmon_tools.py | 391 ++++++++++ Code/Mantid/MantidPlot/SysMon/ui_sysmon.py | 377 ++++++++++ Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui | 670 ++++++++++++++++++ .../MantidPlot/SysMon/ui_sysmonMainWindow.py | 69 ++ .../MantidPlot/SysMon/ui_sysmonMainWindow.ui | 81 +++ .../MantidPlot/src/ApplicationWindow.cpp | 44 +- .../Mantid/MantidPlot/src/ApplicationWindow.h | 23 +- .../MantidPlot/src/Mantid/MantidDock.cpp | 51 +- Code/Mantid/MantidPlot/src/Mantid/MantidUI.h | 28 +- Code/Mantid/MantidPlot/src/qti.sip | 10 +- 16 files changed, 2076 insertions(+), 61 deletions(-) create mode 100644 Code/Mantid/MantidPlot/SysMon/README.md create mode 100755 Code/Mantid/MantidPlot/SysMon/SysMon.pyw create mode 100644 Code/Mantid/MantidPlot/SysMon/__init__.py create mode 100644 Code/Mantid/MantidPlot/SysMon/config.py create mode 100644 Code/Mantid/MantidPlot/SysMon/sysmon.py create mode 100644 Code/Mantid/MantidPlot/SysMon/sysmon_tools.py create mode 100644 Code/Mantid/MantidPlot/SysMon/ui_sysmon.py create mode 100644 Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui create mode 100644 Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.py create mode 100644 Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.ui diff --git a/Code/Mantid/MantidPlot/CMakeLists.txt b/Code/Mantid/MantidPlot/CMakeLists.txt index 8a3b45f4a3d0..20ffa62bc0a5 100644 --- a/Code/Mantid/MantidPlot/CMakeLists.txt +++ b/Code/Mantid/MantidPlot/CMakeLists.txt @@ -847,6 +847,20 @@ copy_python_files_to_dir ( "${IPY_FILES}" ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/ipython_widget IPYTHON_INSTALL_FILES ) +# IPython scripts +set( SYSMON_FILES + __init__.py + config.py + sysmon.py + sysmon_tools.py + ui_sysmon.py + ui_sysmon.ui +) +copy_python_files_to_dir ( "${SYSMON_FILES}" + ${CMAKE_CURRENT_SOURCE_DIR}/SysMon + ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/SysMon + SYSMON_INSTALL_FILES ) + ########################################################################### # MantidPlot executable ########################################################################### @@ -854,7 +868,7 @@ copy_python_files_to_dir ( "${IPY_FILES}" add_executable ( MantidPlot ${WIN_CONSOLE} MACOSX_BUNDLE ${ALL_SRC} src/main.cpp ${INC_FILES} ${QTIPLOT_C_SRC} ${UI_HDRS} ${RES_FILES} ${MANTID_RC_FILE} - ${PYTHON_INSTALL_FILES} ${MTDPLOT_INSTALL_FILES} ${IPYTHON_INSTALL_FILES} + ${PYTHON_INSTALL_FILES} ${MTDPLOT_INSTALL_FILES} ${IPYTHON_INSTALL_FILES} ${SYSMON_INSTALL_FILES} ) # Library dependencies @@ -923,9 +937,9 @@ set ( MANTIDPLOT_TEST_PY_FILES MantidPlot2DPlotTest.py MantidPlotProxiesTest.py MantidPlotPythonImportTest.py - MantidPlotFoldersTest.py - MantidPlotMdiSubWindowTest.py - MantidPlotTiledWindowTest.py + MantidPlotFoldersTest.py + MantidPlotMdiSubWindowTest.py + MantidPlotTiledWindowTest.py ) if ( 0 ) diff --git a/Code/Mantid/MantidPlot/SysMon/README.md b/Code/Mantid/MantidPlot/SysMon/README.md new file mode 100644 index 000000000000..8ef2ab770d04 --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/README.md @@ -0,0 +1,25 @@ +SysMon +====== + +Python qt system monitor which utilizes the Python psutil and platform modules to provide system information for display. + +This application has been adapted to work with psutil version 1 and version 2 modules as there are some command syntax changes between these two versions. + +The SysMon user interface has been divided into a main window which imports the tabs to make a standalone application, or the tabs can be imported into other applications as a QWidget. Thus there are separate .ui files corresponding to each. + +The code which imports the tabs into the main program resides in SysMon.pyw. This is where to look to see how to include the tabs into your own application. All files except SysMon.pyw and ui_sysmonMainWindow.* will be required when tabs are incorporated in other applications. + +The following command line arguments have been added: + --help to print out the help message. + --nompl to run the application minus matplotlib in support of the current MantidPlot (removes those tabs requiring matplotlib). + --custom to enable the custom menubar item in the standalone application (currently supports checking Matlab license status on SNS analysis computers). + +To run as a standalone application via the corresponding command lines: + *Change to the folder containing the Sysmon software, then: + *DOS: python SysMon.pyw + *Linux: ./SysMon.pyw + +The standalone application been tested on Windows and RHEL Linux, but not on Mac yet. + +Note that configuration and global constants and variables now reside in config.py. + diff --git a/Code/Mantid/MantidPlot/SysMon/SysMon.pyw b/Code/Mantid/MantidPlot/SysMon/SysMon.pyw new file mode 100755 index 000000000000..4fd044de0cbe --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/SysMon.pyw @@ -0,0 +1,106 @@ +#!/usr/bin/python +""" +SysMon.pyw +Initial application development 03Sep14 by S. Miller +The application utilizes the psutil and platform python modules to provide system information +for display via text fields, a table and Matplotlib plots. + +The application utilizes a timer with user selectable timer intervals to update information +provided to the application. +""" +import config +import sys + +#parse args - doing it here as config structure needs to be filled prior to importing sysmon +if ['--nompl'] == [s for s in sys.argv if '--nompl' in s]: + #case to not use matplotlib + config.nompl=True +else: + #case to use matplotlib (default case) + config.nompl=False + +if ['--help'] == [s for s in sys.argv if '--help' in s]: + print "SysMon Help" + print "--help - this message" + print "--nompl - flag to disable using matplotlib, also disables History and Users tabs" + print "--custom: - flag to use facility specific options" + sys.exit() + +if ['--custom'] == [s for s in sys.argv if '--custom' in s]: + config.custom=True + +from PyQt4 import QtGui + +from ui_sysmonMainWindow import * +#from ui_sysmonTabs import * +from sysmon import * + +class SysMonMainWindow(QtGui.QMainWindow): + + def __init__(self, parent=None): + #setup main window + QtGui.QMainWindow.__init__(self, parent) + self.setWindowTitle("System Status") + self.ui = Ui_MainWindow() #defined from ui_sysmon.py + self.ui.setupUi(self) + #setup tabs - class imported from sysmon.py + self.sysmontabs=SysMon(self) + self.setCentralWidget(self.sysmontabs) + + #setup menu bar actions + self.connect(self.ui.actionExit, QtCore.SIGNAL('triggered()'), self.confirmExit) #define function to confirm and perform exit + self.connect(self.ui.actionAbout, QtCore.SIGNAL('triggered()'), self.About) + self.connect(self.ui.actionCheck_Matlab_Licenses, QtCore.SIGNAL('triggered()'), self.updateMatlab) + + #check if custom menu bar enabled via command line flag --custom and if not, remove it as it's built by default from Qt + if not(config.custom): + self.ui.menubar.removeAction(self.ui.menuCustom.menuAction()) + + + #define methods for menu bar options + def confirmExit(self): + reply = QtGui.QMessageBox.question(self, 'Message', + "Are you sure to quit?", QtGui.QMessageBox.Yes | + QtGui.QMessageBox.No, QtGui.QMessageBox.No) + + if reply == QtGui.QMessageBox.Yes: + #close application + self.close() + else: + #do nothing and return + pass + + def About(self): + dialog=QtGui.QMessageBox(self) + dialog.setText("PyQt4 System Monitoring Application V0.02") + info='Application Info: \n\r * Changing the Update Rate Clears plots \n\r * It may take one full new update cycle for changes to take effect \n\r * Update rate shown in History plot xaxis label \n\r * Process tab CPU percentage can be greater than 100 when more than a single core is involved' + dialog.setDetailedText(info) #give full info in detailed text + dialog.exec_() + + def updateMatlab(self): + #run license server command to extract license info + info=commands.getstatusoutput(config.matlabchk) + info=str(info[1]) #seem to need to make this a string for Linux to work properly + #test if info string contains MATLAB info + if info.find("MATLAB") < 0: + #case where no license server found + outstr="No Matlab License Server Found to Check" + else: + indx0=info.find("Users of MATLAB:") + indx1=info.find("licenses in use") + if indx0 > -1 and indx1 > -1: + outstr=info[indx0:indx1+15+1] + else: + outstr="Unable to determine Matlab license information" + dialog=QtGui.QMessageBox(self) + #print "outstr: "+outstr + dialog.setText(outstr) + dialog.setDetailedText(info) #give full info in detailed text + dialog.exec_() + +if __name__=="__main__": + app = QtGui.QApplication(sys.argv) + sysmon = SysMonMainWindow() + sysmon.show() + + sys.exit(app.exec_()) \ No newline at end of file diff --git a/Code/Mantid/MantidPlot/SysMon/__init__.py b/Code/Mantid/MantidPlot/SysMon/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/Code/Mantid/MantidPlot/SysMon/config.py b/Code/Mantid/MantidPlot/SysMon/config.py new file mode 100644 index 000000000000..508ba68e711b --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/config.py @@ -0,0 +1,16 @@ + +#global definitions for constants and variables + +#Tab indices: +SYST_TAB=0 +HIST_TAB=1 +PROC_TAB=2 +USER_TAB=3 +OPTS_TAB=4 + +#Global Variables: +psutilVer=0 #flag for the version of psutil being used +nompl=False +mplLoaded=False #flag for matplotlib loading +custom=False +matlabchk='lmstat -S -c 27010@licenses1.sns.gov' \ No newline at end of file diff --git a/Code/Mantid/MantidPlot/SysMon/sysmon.py b/Code/Mantid/MantidPlot/SysMon/sysmon.py new file mode 100644 index 000000000000..1f6ce7662002 --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/sysmon.py @@ -0,0 +1,224 @@ + + +import sys, os, time +import re +import config #application constants and variables +import psutil +#check psutil version as command syntax changes between version 1 and version 2 +ver=psutil.__version__ +verChk1=re.match('1.[0-9].[0-9]',ver) #latest psutil version 1 is 1.2.1 - using positional numeric wildcards to check sub versions +#thus the check is for version 1 as version 2 and following versions are still evolving +#match returns a string if a match is found else returns NoneType +if verChk1 != None: + config.psutilVer=1 +else: + config.psutilVer=2 + +from ui_sysmon import * +from sysmon_tools import * + + +import platform +import commands + +try: + _fromUtf8 = QtCore.QString.fromUtf8 +except AttributeError: + _fromUtf8 = lambda s: s + +class SysMon(QtGui.QWidget): + + def __init__(self, parent=None): + QtGui.QWidget.__init__(self, parent) + self.ui = Ui_Form() #defined from ui_sysmon.py + self.ui.setupUi(self) + self.ui.progressBarStatusMemory.setStyleSheet("QProgressBar {width: 25px;border: 1px solid black; border-radius: 3px; background: white;text-align: center;padding: 0px;}" + +"QProgressBar::chunk:horizontal {background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #00CCEE, stop: 0.3 #00DDEE, stop: 0.6 #00EEEE, stop:1 #00FFEE);}") + self.ui.progressBarStatusCPU.setStyleSheet("QProgressBar {width: 25px;border: 1px solid black; border-radius: 3px; background: white;text-align: center;padding: 0px;}" + +"QProgressBar::chunk:horizontal {background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #00CCEE, stop: 0.3 #00DDEE, stop: 0.6 #00EEEE, stop:1 #00FFEE);}") + + #setup timer to enable periodic events such as status update checks + self.ctimer = QtCore.QTimer() + self.ctimer.start(2000) #time in mSec - set repetitive timer of 2 seconds + QtCore.QObject.connect(self.ctimer, QtCore.SIGNAL("timeout()"), self.constantUpdate) + + #update rate actions + QtCore.QObject.connect(self.ui.radioButton1Sec, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update1Sec) + QtCore.QObject.connect(self.ui.radioButton2Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update2Sec) + QtCore.QObject.connect(self.ui.radioButton5Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update5Sec) + QtCore.QObject.connect(self.ui.radioButton10Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update10Sec) + self.update=2 #set default to 2 seconds update rate + + #duration actions + QtCore.QObject.connect(self.ui.radioButton60Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update60Duration) + QtCore.QObject.connect(self.ui.radioButton300Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update300Duration) + QtCore.QObject.connect(self.ui.radioButton600Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update600Duration) + QtCore.QObject.connect(self.ui.radioButton3600Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update3600Duration) + self.duration=60 #set default plot duration to 60 seconds + + QtCore.QObject.connect(self.ui.pushButtonUpdate, QtCore.SIGNAL('clicked(bool)'), self.updateProcesses) + + #Initialize System Tab + self.ui.tabWidget.setCurrentIndex(config.SYST_TAB) + self.ui.labelComputerName.setText("Computer Name: "+platform.node()) + if platform.os.name == 'nt': + info=platform.win32_ver() + oslabel="Windows "+info[0]+" Version: "+info[1] + elif platform.os.name == 'posix': + info=platform.linux_distribution() + oslabel=info[0]+" Version: "+info[1] + elif platform.os.name == 'mac': + info=platform.mac_ver() + oslabel=info[0]+" Version: "+info[1] + else: + oslabel=" " + + self.ui.labelOS.setText("Operating System: "+oslabel) + info=platform.uname() + self.ui.labelProcFam.setText("Processor Family: "+info[5]) + + #determine the number of users on the computer + userInfo=psutil.get_users() if config.psutilVer==1 else psutil.users() + lst=[] + for item in userInfo: + lst.append(item.name) + uusers=set(lst) + Nuusers=len(uusers) + self.ui.labelNUsers.setText("Number of Users Logged On: "+str(Nuusers)) + + #determine the computer uptime + if config.psutilVer == 1: + uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.BOOT_TIME)) + else: + uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.boot_time())) + self.ui.labelUptime.setText("System Uptime: "+uptime) + + if config.mplLoaded: + #if matplotlib loaded OK, initialize plotting + #Initialize History Tab + self.ui.tabWidget.setCurrentIndex(config.HIST_TAB) + #Place Matplotlib figure within the GUI frame + #create drawing canvas + # a figure instance to plot on + + matplotlib.rc_context({'toolbar':False}) + #initialize figure 1 and its canvas for cpu and memory history plots + self.ui.figure = plt.figure(1) + # the Canvas Widget displays the `figure` + # it takes the `figure` instance as a parameter to __init__ + self.ui.canvas = FigureCanvas(self.ui.figure) + layout=QtGui.QVBoxLayout(self.ui.framePlot) + layout.addWidget(self.ui.canvas) + self.ui.layout=layout + + #initialize figure 2 and its canvas for user usage bar chart + self.ui.figure2 = plt.figure(2) + self.ui.canvas2 = FigureCanvas(self.ui.figure2) + layout2=QtGui.QVBoxLayout(self.ui.frameBar) + layout2.addWidget(self.ui.canvas2) + self.ui.layout2=layout2 + + + else: + #if matplotlib not loaded, remove the tabs that depend upon it + self.removeMPLTabs() + + #initialize history plot arrays - easier just to initialize these even if not doing plotting in case when matplotlib not available. + Nsamples=3600 + self.ui.Nsamples=Nsamples + #need one extra sample to fill the plotting interval + self.ui.cpu=np.zeros(Nsamples+1) + self.ui.mem=np.zeros(Nsamples+1) + self.ui.dt=[None]*(Nsamples+1) + + self.ui.tabWidget.setTabsClosable(False) #disable the ability to close tabs once state of matplotlib is handled + + #initialize the process table + self.doUpdates=True #flag for updating the process tab table + updateProcTable(self,config) + + #upon initialization completion, set System tab (first tab on left) as the visible tab + self.ui.tabWidget.setCurrentIndex(config.SYST_TAB) + + def constantUpdate(self): + #redirct to global function + constantUpdateActor(self,config) + + def update1Sec(self): + self.update=1 + self.ctimer.stop() + self.ctimer.start(1000) + #clear persistent arrays when update rate changed + self.ui.cpu=self.ui.cpu*0 + self.ui.mem=self.ui.mem*0 + self.ui.dt=[None]*self.ui.Nsamples + + def update2Sec(self): + self.update=2 + self.ctimer.stop() + self.ctimer.start(2000) + #clear persistent arrays when update rate changed + self.ui.cpu=self.ui.cpu*0 + self.ui.mem=self.ui.mem*0 + self.ui.dt=[None]*self.ui.Nsamples + + def update5Sec(self): + self.update=5 + self.ctimer.stop() + self.ctimer.start(5000) + #clear persistent arrays when update rate changed + self.ui.cpu=self.ui.cpu*0 + self.ui.mem=self.ui.mem*0 + self.ui.dt=[None]*self.ui.Nsamples + + def update10Sec(self): + self.update=10 + self.ctimer.stop() + self.ctimer.start(10000) + #clear persistent arrays when update rate changed + self.ui.cpu=self.ui.cpu*0 + self.ui.mem=self.ui.mem*0 + self.ui.dt=[None]*self.ui.Nsamples + + def update60Duration(self): + self.duration=60 + def update300Duration(self): + self.duration=300 + def update600Duration(self): + self.duration=600 + def update3600Duration(self): + self.duration=3600 + + def updateProcesses(self): + if self.doUpdates == True: + #case to toggle to False + self.doUpdates=False + self.ui.pushButtonUpdate.setText('Continue') + else: + #case where updates must be off + self.doUpdates=True + self.ui.pushButtonUpdate.setText('Hold Updates') + + def resizeEvent(self,resizeEvent): + print "resizing" + sz=self.ui.tableWidgetProcess.size() + w=sz.width() + self.ui.tableWidgetProcess.setColumnWidth(0,3*w/20) + self.ui.tableWidgetProcess.setColumnWidth(1,5*w/20) + self.ui.tableWidgetProcess.setColumnWidth(2,3*w/20) + self.ui.tableWidgetProcess.setColumnWidth(3,3*w/20) + self.ui.tableWidgetProcess.setColumnWidth(4,6*w/20) + + def removeMPLTabs(self): + #In case matplotlib not available, remove tabs requiring this + #Note to developers - removing tabs changes the tab index numbers! + #Keep this in mind regarding setting and using tab indices + self.ui.tabWidget.removeTab(config.HIST_TAB) #History tab + config.HIST_TAB=-1 + config.PROC_TAB-=1 + config.USER_TAB-=1 + config.OPTS_TAB-=1 + self.ui.tabWidget.removeTab(config.USER_TAB) #Users tab - originally tab 3, but becomes tab 2 once history tab is removed + config.USER_TAB=-1 + config.OPTS_TAB-=1 + self.ui.tabWidget.setTabsClosable(False) diff --git a/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py b/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py new file mode 100644 index 000000000000..2e8d9eabb004 --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py @@ -0,0 +1,391 @@ +import psutil +from PyQt4 import Qt, QtCore, QtGui +import datetime +import numpy as np +import config + +#check if command line flag --nompl set to disable matplotlib +if not(config.nompl): + try: + import matplotlib + if matplotlib.get_backend() != 'QT4Agg': + matplotlib.use('QT4Agg') + from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas + from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as NavigationToolbar + import matplotlib.pyplot as plt + config.mplLoaded=True + # print "matplotlib try successful" + except: + # print "matplotlib except case" + #case where matplotlib not available - need to know this for handling plotting tabs + config.mplLoaded=False + pass +else: + config.mplLoaded=False #use this flag to test case when matplotlib is not available + +def constantUpdateActor(self,config): + + #check duration + Ndur=self.duration + + #update global variables + + #mode to show status in percentage + cpu_stats = psutil.cpu_times_percent(interval=0,percpu=False) #syntax seems to be same for psutil versions 1 and 2 + percentcpubusy = 100.0 - cpu_stats.idle + self.ui.progressBarStatusCPU.setValue(round(percentcpubusy)) + percentmembusy=psutil.virtual_memory().percent + self.ui.progressBarStatusMemory.setValue(round(percentmembusy)) + Ncpus=len(psutil.cpu_percent(percpu=True)) + self.ui.Ncpus=Ncpus + totalcpustr='CPU Count: '+str(Ncpus) +# print "Total CPU str: ",totalcpustr + self.ui.labelCPUCount.setText(totalcpustr) + totalmem=int(round(float(psutil.virtual_memory().total)/(1024*1024*1024))) #psutil syntax OK for both versions +# print "Total Mem: ",totalmem + self.ui.labelMemUsage.setText('Memory Usage: '+str(totalmem*percentmembusy/100)+' GB') + self.ui.totalmem=totalmem + totalmemstr='Max Mem: '+str(totalmem)+' GB' +# print "Total Mem str: ",totalmemstr + self.ui.labelMaxMem.setText(totalmemstr) +# print "** config.mplLoaded: ",config.mplLoaded + + if config.mplLoaded: + #update first position with most recent value overwriting oldest value which has been shifted to first position + self.ui.cpu=np.roll(self.ui.cpu,1) + self.ui.cpu[0]=percentcpubusy + self.ui.mem=np.roll(self.ui.mem,1) + self.ui.mem[0]=percentmembusy + # self.ui.dt=np.roll(self.ui.dt,1) + # self.ui.dt[0]=datetime.datetime.now() + + # update system tab + if self.ui.tabWidget.currentIndex() == config.SYST_TAB: + #determine the computer uptime + if config.psutilVer == 1: + uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.BOOT_TIME)) + else: + uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.boot_time())) + self.ui.labelUptime.setText("System Uptime: "+uptime) + + + + #update the number of users each time interval as well + userInfo=psutil.get_users() if config.psutilVer == 1 else psutil.users() + lst=[] + for item in userInfo: + lst.append(item.name) + uusers=set(lst) + Nuusers=len(uusers) + self.ui.labelNUsers.setText("Number of Users Logged On: "+str(Nuusers)) + + #update the history plot + if self.ui.tabWidget.currentIndex() == config.HIST_TAB: + #only update history plot if tab is active + font = {'family' : 'sans-serif', + 'weight' : 'bold', + 'size' : 10} + matplotlib.rc('font', **font) + + xtime=range(0,self.ui.Nsamples+1,self.update) + + Npts=Ndur/self.update + + plt.figure(self.ui.figure.number) #make plot figure active + plt.clf() #clear figure each time for rolling updates to show + plt.plot(xtime[0:Npts+1],self.ui.cpu[0:Npts+1],color='Blue',label='CPU Busy') + plt.plot(xtime[0:Npts+1],self.ui.mem[0:Npts+1],color='Green',label='Mem Busy') + plt.title('Composite CPU and Memory Activity',fontsize=10,fontweight='bold') + plt.ylabel('% Busy',fontsize=9.5,fontweight='bold') + + if self.update == 1: + xlab="Seconds with 1 Second Updates" + elif self.update == 2: + xlab="Seconds with 2 Second Updates" + elif self.update == 5: + xlab="Seconds with 5 Second Updates" + elif self.update == 10: + xlab="Seconds with 10 Second Updates" + plt.xlabel(xlab,fontsize=9.5,fontweight='bold') + plt.legend(loc="upper right",prop={'size':9}) + plt.xlim([0,Ndur]) + self.ui.canvas.draw() + + #update the process table + if self.ui.tabWidget.currentIndex() == config.PROC_TAB: + #only update process table if tab is active + updateProcTable(self,config) + + #update the Users bar chart + if self.ui.tabWidget.currentIndex() == config.USER_TAB: + #only update bar chart if the tab is active. + updateUserChart(self,config) + + + +def updateProcTable(self,config): + if self.doUpdates==True: + table=self.ui.tableWidgetProcess + #first remove all rows + Nrows=table.rowCount() + for row in range(Nrows): + table.removeRow(0) + + #get the processes + pidList=psutil.get_pid_list() if config.psutilVer == 1 else psutil.pids() + Npids=len(pidList) + + #now add rows to the table according to the number of processes + # for row in range(Npids): + # table.insertRow(0) + + #now populate the table + row=0 #table row counter incremented for each row added to the process table + rout=0 #counter for number of rows to remove due to invalid processes + memtot=psutil.virtual_memory() #psutil syntax OK for both versions + + #determine which column has been selected for sorting + column_sorted=table.horizontalHeader().sortIndicatorSection() + order = table.horizontalHeader().sortIndicatorOrder() + #temporarily set sort column to outside column range so that table items can be filled properly + table.sortItems(5,order=QtCore.Qt.AscendingOrder) + #print table.horizontalHeader().sortIndicatorSection() + + #create empty dictionaries to be used by the process table + d_user={} + d_cpu={} + d_mem={} + d_name={} + + #fill the dictionaries - seems to need to be done faster than within loop which also fills the table...not sure why... + for proc in psutil.process_iter(): + cpupct=proc.get_cpu_percent(interval=0) if config.psutilVer == 1 else proc.cpu_percent(interval=0) + memVal=float(int(float(proc.get_memory_percent())*100.0))/100.0 if config.psutilVer == 1 else float(int(float(proc.memory_percent())*100.0))/100.0 + try: + #don't update dictionaries if name gives an access denied error when checking process name + pname=proc.name if config.psutilVer == 1 else proc.name() + d_user.update({proc.pid:proc.username}) if config.psutilVer == 1 else d_user.update({proc.pid:proc.username()}) + d_cpu.update({proc.pid:cpupct}) + d_mem.update({proc.pid:memVal}) + d_name.update({proc.pid:pname}) + except: + pass #place holder + + #now fill the table for display + for proc in d_user.keys(): + #print "proc: ",proc," type: ",type(proc) + pid=int(proc) + #print "pid: ",pid + + table.insertRow(0) + #print "inserting row" + #set process id + item=QtGui.QTableWidgetItem() + item.setData(QtCore.Qt.DisplayRole,pid) + table.setItem(0,0,item) + #set username + #print " d_user[proc]: ",d_user[proc]," proc: ",proc + table.setItem(0,1,QtGui.QTableWidgetItem(d_user[proc])) + #set CPU % + item=QtGui.QTableWidgetItem() + item.setData(QtCore.Qt.DisplayRole,d_cpu[proc]) + table.setItem(0,2,item) + #set memory % + item=QtGui.QTableWidgetItem() + item.setData(QtCore.Qt.DisplayRole,d_mem[proc]) + table.setItem(0,3,item) + #set process name + table.setItem(0,4,QtGui.QTableWidgetItem(d_name[proc])) + row+=1 + + + # for row in range(rout): + # table.removeRow(Npids-row) + #restore sort to previously selected column + #table.sortItems(column_sorted,order=QtCore.Qt.AscendingOrder) + table.sortItems(column_sorted,order=order) + self.ui.labelLastUpdate.setText("Last Update: "+str(datetime.datetime.now())) + +def updateUserChart(self,config): + + font = {'family' : 'sans-serif', + 'weight' : 'bold', + 'size' : 9} + + matplotlib.rc('font', **font) + + f=plt.figure(self.ui.figure2.number) + +# self.ui.figure2=plt.figure(2) + plt.clf() + plt.cla() +# f.gca().cla() + + #create empty dictionaries to be used by the process table + d_user={} + d_cpu={} + d_mem={} + d_name={} + #fill the dictionaries - seems to need to be done faster than within loop which also fills the table...not sure why... + for proc in psutil.process_iter(): + cpupct=proc.get_cpu_percent(interval=0) if config.psutilVer == 1 else proc.cpu_percent(interval=0) + memVal=float(int(float(proc.get_memory_percent())*100.0))/100.0 if config.psutilVer == 1 else float(int(float(proc.memory_percent())*100.0))/100.0 + try: + #don't update dictionaries if name gives an access denied error when checking process name + pname=proc.name if config.psutilVer == 1 else proc.name() + d_user.update({proc.pid:proc.username}) if config.psutilVer == 1 else d_user.update({proc.pid:proc.username()}) + d_cpu.update({proc.pid:cpupct}) + d_mem.update({proc.pid:memVal}) + d_name.update({proc.pid:pname}) + except: + pass #place holder + + users=d_user.values() + users_unique=list(set(users)) #use set() to find unique users then convert the resulting set to a list via list() + Nusers=len(users_unique) + + #create cpu and memory by users dictionaries + cpu_by_users={} + mem_by_users={} + for u in range(Nusers): + cpu_by_users.update({users_unique[u]:0}) + mem_by_users.update({users_unique[u]:0}) + #apparently update does not order keys in sequence to users_unique + #thus need to re-create users_unique according to the order of the users + #in the cpu and mem dictionary keys + users_unique=list(cpu_by_users.keys()) + + #fill cpu and memory dictionaries sequencing thru each PID + for pid in d_user.keys(): + user=d_user[pid] + cpu_by_users[user]=cpu_by_users[user] + d_cpu[pid] + mem_by_users[user]=mem_by_users[user] + d_mem[pid] + + #now convert to a list which we can index + cpu_by_users_lst=cpu_by_users.values() + mem_by_users_lst=mem_by_users.values() + + width=0.85 + + colors=['b','g','r','c','m','y','gray','hotpink','brown','k'] + Nmax=len(colors) #don't want to have more users than colors... + + if self.ui.radioButtonCPU.isChecked(): + sortBy='cpu' + elif self.ui.radioButtonMem.isChecked(): + sortBy='mem' + else: + print "invalid radio button selection - using CPU sort as default" + sortBy='cpu' + #sortBy='cpu' # 'cpu' or 'mem' - use for debugging + #create sort index + if sortBy=='cpu': + indx=sorted(range(len(cpu_by_users_lst)), key=cpu_by_users_lst.__getitem__,reverse=True) + elif sortBy=='mem': + indx=sorted(range(len(mem_by_users_lst)), key=mem_by_users_lst.__getitem__,reverse=True) + else: + print 'Incorrect sort parameter' + #sort lists + cpu_by_users_sorted=[cpu_by_users_lst[x] for x in indx] + mem_by_users_sorted=[mem_by_users_lst[x] for x in indx] + users_unique_sorted=[users_unique[x] for x in indx] + + #restrict the number of users we'll show to Nmax + if Nusers > Nmax: + #replace the Nmaxth - 1 element with the total of the values from index Nmax - 1 to the end of the list + cpu_by_users_sorted[Nmax-1]=sum(cpu_by_users_sorted[Nmax-1:]) + mem_remaining=sum(mem_by_users_sorted[Nmax-1:]) + users_unique_sorted[Nmax-1]='Remaining' + Nshow=Nmax + else: + Nshow=Nusers + + if min(cpu_by_users_sorted) < 0: + print " *** cp_by_users_sorted has values less than zero" + print cpu_by_users_sorted + print " ***" + if min(mem_by_users_sorted) < 0: + print " *** mem_by_users_sorted has values less than zero" + print mem_by_users_sorted + print " ***" + + #range check the values of the sorted lists - may not be necessary, just being cautious... + tst=np.array(cpu_by_users_sorted)<0 #need an array for summing + indx=cpu_by_users_sorted<0 #need bool list for indexing + if sum(tst) > 0: + print "cpu_by_users < 0: ",sum(indx) + cpu_by_users_sorted[indx]=0 + tst=np.array(cpu_by_users_sorted)>self.ui.Ncpus*100 + indx=cpu_by_users_sorted>self.ui.Ncpus*100 + if sum(tst) > 0: + print "cpu_by_users > Ncpus*100: ",sum(indx) + cpu_by_users_sorted[indx]=self.ui.Ncpus*100 + tst=np.array(mem_by_users_sorted)<0 + indx=mem_by_users_sorted<0 + if sum(tst) > 0: + print "mem_by_users < 0: ",sum(indx) + mem_by_users_sorted[indx]=0 + tst=np.array(mem_by_users_sorted)>self.ui.totalmem + indx=mem_by_users_sorted>self.ui.totalmem + if sum(tst) > 0: + print "mem_by_users > totalmem: ",sum(indx) + mem_by_users_sorted[indx]=self.ui.totalmem + + + p=[] #list to contain plot objects for use by the legend + ind=np.arange(2) + + + for u in range(Nshow): + if u == 0: + p.append(plt.bar(ind,(cpu_by_users_sorted[u],mem_by_users_sorted[u]),width,bottom=(0,0),color=colors[u])) + else: + p.append(plt.bar(ind,(cpu_by_users_sorted[u],mem_by_users_sorted[u]),width,bottom=(sum(cpu_by_users_sorted[0:u]),sum(mem_by_users_sorted[0:u])),color=colors[u])) + + plt.title('CPU and Memory Usage by User',fontsize=10,fontweight='bold') + + #remove default yaxis ticks then redraw them via ax1 and ax2 below + frame=plt.gca() + frame.axes.get_yaxis().set_ticks([]) + plt.xticks(np.arange(2)+width/2.,('CPU','Mem'),fontsize=9,fontweight='bold') + ymaxCPU=round(int((sum(cpu_by_users_sorted[0:Nshow])+100)/100)*100) + ymaxMEM=round(int((sum(mem_by_users_sorted[0:Nshow])+100)/100)*100) + ymax=max([ymaxCPU,ymaxMEM,100]) +# plt.ylim([0,ymax]) + + #compute composite % + ylab=np.arange(6)/5.0*float(ymax)/float(self.ui.Ncpus) + ylab=ylab*10 + tmp=ylab.astype('int') + tmp1=tmp.astype('float') + tmp1=tmp1/10 + ylab1=tmp1 + + ax1=plt.twinx() + ax1.set_ylabel('Composite CPU Percent',fontsize=9,fontweight='bold') + ax1.yaxis.set_ticks_position('left') + ax1.yaxis.set_label_position('left') + ax1.set_yticks(ylab1) + + usersLegend=users_unique_sorted[0:Nshow] + #reverse legend print order to have legend correspond with the order data are placed in the bar chart + usersLegend.reverse() + p.reverse() + plt.legend(p,usersLegend) + + + #place second y axis label on plot + ylab2=np.arange(5)/4.0*float(ymax) + ax2=plt.twinx() + ax2.set_ylabel('Percent',fontsize=9,fontweight='bold') + ax2.set_yticks(ylab2) + #ax2.set_yticks(ylab2) + ax2.yaxis.set_ticks_position('right') + ax2.yaxis.set_label_position('right') + + self.ui.canvas2.draw() + +def reLayout(self): + tmpWidget=QtGui.QWidget() + tmpWidget.setLayout(self.ui.layout2) + tmpLayout = QtGui.QVBoxLayout(self.ui.frameBar) \ No newline at end of file diff --git a/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py new file mode 100644 index 000000000000..cb543a389d72 --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py @@ -0,0 +1,377 @@ +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file '../../Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui' +# +# Created: Fri Sep 19 12:44:16 2014 +# by: PyQt4 UI code generator 4.10.4 +# +# WARNING! All changes made in this file will be lost! + +from PyQt4 import QtCore, QtGui + +try: + _fromUtf8 = QtCore.QString.fromUtf8 +except AttributeError: + def _fromUtf8(s): + return s + +try: + _encoding = QtGui.QApplication.UnicodeUTF8 + def _translate(context, text, disambig): + return QtGui.QApplication.translate(context, text, disambig, _encoding) +except AttributeError: + def _translate(context, text, disambig): + return QtGui.QApplication.translate(context, text, disambig) + +class Ui_Form(object): + def setupUi(self, Form): + Form.setObjectName(_fromUtf8("Form")) + Form.resize(230, 331) + Form.setMaximumSize(QtCore.QSize(16777215, 16777215)) + self.horizontalLayout = QtGui.QHBoxLayout(Form) + self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) + self.tabWidget = QtGui.QTabWidget(Form) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth()) + self.tabWidget.setSizePolicy(sizePolicy) + self.tabWidget.setObjectName(_fromUtf8("tabWidget")) + self.tab = QtGui.QWidget() + self.tab.setObjectName(_fromUtf8("tab")) + self.verticalLayout = QtGui.QVBoxLayout(self.tab) + self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) + self.scrollArea = QtGui.QScrollArea(self.tab) + self.scrollArea.setWidgetResizable(True) + self.scrollArea.setObjectName(_fromUtf8("scrollArea")) + self.scrollAreaWidgetContents = QtGui.QWidget() + self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 320, 293)) + self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents")) + self.verticalLayout_2 = QtGui.QVBoxLayout(self.scrollAreaWidgetContents) + self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) + self.groupBox_3 = QtGui.QGroupBox(self.scrollAreaWidgetContents) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().hasHeightForWidth()) + self.groupBox_3.setSizePolicy(sizePolicy) + self.groupBox_3.setMinimumSize(QtCore.QSize(0, 0)) + self.groupBox_3.setObjectName(_fromUtf8("groupBox_3")) + self.gridLayout_4 = QtGui.QGridLayout(self.groupBox_3) + self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4")) + self.gridLayout_7 = QtGui.QGridLayout() + self.gridLayout_7.setObjectName(_fromUtf8("gridLayout_7")) + self.labelComputerName = QtGui.QLabel(self.groupBox_3) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.labelComputerName.sizePolicy().hasHeightForWidth()) + self.labelComputerName.setSizePolicy(sizePolicy) + self.labelComputerName.setMinimumSize(QtCore.QSize(0, 0)) + self.labelComputerName.setObjectName(_fromUtf8("labelComputerName")) + self.gridLayout_7.addWidget(self.labelComputerName, 0, 0, 1, 1) + self.labelOS = QtGui.QLabel(self.groupBox_3) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.labelOS.sizePolicy().hasHeightForWidth()) + self.labelOS.setSizePolicy(sizePolicy) + self.labelOS.setMinimumSize(QtCore.QSize(0, 0)) + self.labelOS.setObjectName(_fromUtf8("labelOS")) + self.gridLayout_7.addWidget(self.labelOS, 1, 0, 1, 1) + self.labelProcFam = QtGui.QLabel(self.groupBox_3) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.labelProcFam.sizePolicy().hasHeightForWidth()) + self.labelProcFam.setSizePolicy(sizePolicy) + self.labelProcFam.setMinimumSize(QtCore.QSize(0, 0)) + self.labelProcFam.setObjectName(_fromUtf8("labelProcFam")) + self.gridLayout_7.addWidget(self.labelProcFam, 2, 0, 1, 1) + self.labelNUsers = QtGui.QLabel(self.groupBox_3) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.labelNUsers.sizePolicy().hasHeightForWidth()) + self.labelNUsers.setSizePolicy(sizePolicy) + self.labelNUsers.setMinimumSize(QtCore.QSize(0, 0)) + self.labelNUsers.setObjectName(_fromUtf8("labelNUsers")) + self.gridLayout_7.addWidget(self.labelNUsers, 3, 0, 1, 1) + self.labelUptime = QtGui.QLabel(self.groupBox_3) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.labelUptime.sizePolicy().hasHeightForWidth()) + self.labelUptime.setSizePolicy(sizePolicy) + self.labelUptime.setMinimumSize(QtCore.QSize(0, 0)) + self.labelUptime.setObjectName(_fromUtf8("labelUptime")) + self.gridLayout_7.addWidget(self.labelUptime, 4, 0, 1, 1) + self.gridLayout_4.addLayout(self.gridLayout_7, 0, 0, 1, 1) + self.groupBox_5 = QtGui.QGroupBox(self.groupBox_3) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.groupBox_5.sizePolicy().hasHeightForWidth()) + self.groupBox_5.setSizePolicy(sizePolicy) + self.groupBox_5.setMinimumSize(QtCore.QSize(0, 0)) + font = QtGui.QFont() + font.setBold(False) + font.setUnderline(False) + font.setWeight(50) + self.groupBox_5.setFont(font) + self.groupBox_5.setObjectName(_fromUtf8("groupBox_5")) + self.gridLayout_6 = QtGui.QGridLayout(self.groupBox_5) + self.gridLayout_6.setObjectName(_fromUtf8("gridLayout_6")) + self.labelMemUsage = QtGui.QLabel(self.groupBox_5) + font = QtGui.QFont() + font.setUnderline(False) + self.labelMemUsage.setFont(font) + self.labelMemUsage.setObjectName(_fromUtf8("labelMemUsage")) + self.gridLayout_6.addWidget(self.labelMemUsage, 0, 0, 1, 1) + self.labelCPUCount = QtGui.QLabel(self.groupBox_5) + self.labelCPUCount.setObjectName(_fromUtf8("labelCPUCount")) + self.gridLayout_6.addWidget(self.labelCPUCount, 3, 0, 1, 1) + self.labelMaxMem = QtGui.QLabel(self.groupBox_5) + self.labelMaxMem.setObjectName(_fromUtf8("labelMaxMem")) + self.gridLayout_6.addWidget(self.labelMaxMem, 1, 0, 1, 1) + self.label_102 = QtGui.QLabel(self.groupBox_5) + font = QtGui.QFont() + font.setUnderline(False) + self.label_102.setFont(font) + self.label_102.setObjectName(_fromUtf8("label_102")) + self.gridLayout_6.addWidget(self.label_102, 2, 0, 1, 1) + self.progressBarStatusCPU = QtGui.QProgressBar(self.groupBox_5) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.progressBarStatusCPU.sizePolicy().hasHeightForWidth()) + self.progressBarStatusCPU.setSizePolicy(sizePolicy) + self.progressBarStatusCPU.setProperty("value", 24) + self.progressBarStatusCPU.setObjectName(_fromUtf8("progressBarStatusCPU")) + self.gridLayout_6.addWidget(self.progressBarStatusCPU, 2, 1, 2, 1) + self.progressBarStatusMemory = QtGui.QProgressBar(self.groupBox_5) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.progressBarStatusMemory.sizePolicy().hasHeightForWidth()) + self.progressBarStatusMemory.setSizePolicy(sizePolicy) + self.progressBarStatusMemory.setProperty("value", 24) + self.progressBarStatusMemory.setObjectName(_fromUtf8("progressBarStatusMemory")) + self.gridLayout_6.addWidget(self.progressBarStatusMemory, 0, 1, 2, 1) + self.gridLayout_4.addWidget(self.groupBox_5, 1, 0, 1, 1) + self.verticalLayout_2.addWidget(self.groupBox_3) + self.scrollArea.setWidget(self.scrollAreaWidgetContents) + self.verticalLayout.addWidget(self.scrollArea) + self.tabWidget.addTab(self.tab, _fromUtf8("")) + self.tab_2 = QtGui.QWidget() + self.tab_2.setObjectName(_fromUtf8("tab_2")) + self.horizontalLayout_2 = QtGui.QHBoxLayout(self.tab_2) + self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) + self.framePlot = QtGui.QFrame(self.tab_2) + self.framePlot.setFrameShape(QtGui.QFrame.StyledPanel) + self.framePlot.setFrameShadow(QtGui.QFrame.Raised) + self.framePlot.setObjectName(_fromUtf8("framePlot")) + self.horizontalLayout_2.addWidget(self.framePlot) + self.tabWidget.addTab(self.tab_2, _fromUtf8("")) + self.tab_3 = QtGui.QWidget() + self.tab_3.setObjectName(_fromUtf8("tab_3")) + self.verticalLayout_3 = QtGui.QVBoxLayout(self.tab_3) + self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3")) + self.horizontalLayout_3 = QtGui.QHBoxLayout() + self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3")) + self.labelLastUpdate = QtGui.QLabel(self.tab_3) + self.labelLastUpdate.setMinimumSize(QtCore.QSize(0, 0)) + self.labelLastUpdate.setMaximumSize(QtCore.QSize(300, 16777215)) + self.labelLastUpdate.setObjectName(_fromUtf8("labelLastUpdate")) + self.horizontalLayout_3.addWidget(self.labelLastUpdate) + self.verticalLayout_3.addLayout(self.horizontalLayout_3) + self.tableWidgetProcess = QtGui.QTableWidget(self.tab_3) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) + sizePolicy.setHorizontalStretch(100) + sizePolicy.setVerticalStretch(100) + sizePolicy.setHeightForWidth(self.tableWidgetProcess.sizePolicy().hasHeightForWidth()) + self.tableWidgetProcess.setSizePolicy(sizePolicy) + self.tableWidgetProcess.setMinimumSize(QtCore.QSize(0, 0)) + self.tableWidgetProcess.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) + self.tableWidgetProcess.setRowCount(10) + self.tableWidgetProcess.setColumnCount(5) + self.tableWidgetProcess.setObjectName(_fromUtf8("tableWidgetProcess")) + item = QtGui.QTableWidgetItem() + self.tableWidgetProcess.setHorizontalHeaderItem(0, item) + item = QtGui.QTableWidgetItem() + self.tableWidgetProcess.setHorizontalHeaderItem(1, item) + item = QtGui.QTableWidgetItem() + self.tableWidgetProcess.setHorizontalHeaderItem(2, item) + item = QtGui.QTableWidgetItem() + self.tableWidgetProcess.setHorizontalHeaderItem(3, item) + item = QtGui.QTableWidgetItem() + self.tableWidgetProcess.setHorizontalHeaderItem(4, item) + self.tableWidgetProcess.horizontalHeader().setDefaultSectionSize(57) + self.tableWidgetProcess.horizontalHeader().setSortIndicatorShown(True) + self.tableWidgetProcess.horizontalHeader().setStretchLastSection(True) + self.tableWidgetProcess.verticalHeader().setVisible(False) + self.tableWidgetProcess.verticalHeader().setDefaultSectionSize(20) + self.tableWidgetProcess.verticalHeader().setStretchLastSection(True) + self.verticalLayout_3.addWidget(self.tableWidgetProcess) + self.horizontalLayout_7 = QtGui.QHBoxLayout() + self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7")) + spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) + self.horizontalLayout_7.addItem(spacerItem) + self.pushButtonUpdate = QtGui.QPushButton(self.tab_3) + self.pushButtonUpdate.setMinimumSize(QtCore.QSize(0, 0)) + self.pushButtonUpdate.setMaximumSize(QtCore.QSize(80, 15)) + font = QtGui.QFont() + font.setPointSize(7) + self.pushButtonUpdate.setFont(font) + self.pushButtonUpdate.setObjectName(_fromUtf8("pushButtonUpdate")) + self.horizontalLayout_7.addWidget(self.pushButtonUpdate) + self.verticalLayout_3.addLayout(self.horizontalLayout_7) + self.tabWidget.addTab(self.tab_3, _fromUtf8("")) + self.tab_5 = QtGui.QWidget() + self.tab_5.setObjectName(_fromUtf8("tab_5")) + self.verticalLayout_6 = QtGui.QVBoxLayout(self.tab_5) + self.verticalLayout_6.setObjectName(_fromUtf8("verticalLayout_6")) + self.groupBox = QtGui.QGroupBox(self.tab_5) + self.groupBox.setObjectName(_fromUtf8("groupBox")) + self.horizontalLayout_6 = QtGui.QHBoxLayout(self.groupBox) + self.horizontalLayout_6.setContentsMargins(-1, 3, -1, 2) + self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6")) + self.radioButtonCPU = QtGui.QRadioButton(self.groupBox) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.radioButtonCPU.sizePolicy().hasHeightForWidth()) + self.radioButtonCPU.setSizePolicy(sizePolicy) + self.radioButtonCPU.setMinimumSize(QtCore.QSize(0, 0)) + self.radioButtonCPU.setObjectName(_fromUtf8("radioButtonCPU")) + self.horizontalLayout_6.addWidget(self.radioButtonCPU) + self.radioButtonMem = QtGui.QRadioButton(self.groupBox) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.radioButtonMem.sizePolicy().hasHeightForWidth()) + self.radioButtonMem.setSizePolicy(sizePolicy) + self.radioButtonMem.setMinimumSize(QtCore.QSize(0, 0)) + self.radioButtonMem.setChecked(True) + self.radioButtonMem.setObjectName(_fromUtf8("radioButtonMem")) + self.horizontalLayout_6.addWidget(self.radioButtonMem) + self.verticalLayout_6.addWidget(self.groupBox) + self.frameBar = QtGui.QFrame(self.tab_5) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Expanding) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.frameBar.sizePolicy().hasHeightForWidth()) + self.frameBar.setSizePolicy(sizePolicy) + self.frameBar.setFrameShape(QtGui.QFrame.StyledPanel) + self.frameBar.setFrameShadow(QtGui.QFrame.Raised) + self.frameBar.setObjectName(_fromUtf8("frameBar")) + self.verticalLayout_6.addWidget(self.frameBar) + self.tabWidget.addTab(self.tab_5, _fromUtf8("")) + self.tab_4 = QtGui.QWidget() + self.tab_4.setObjectName(_fromUtf8("tab_4")) + self.horizontalLayout_4 = QtGui.QHBoxLayout(self.tab_4) + self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4")) + self.scrollArea_2 = QtGui.QScrollArea(self.tab_4) + self.scrollArea_2.setWidgetResizable(True) + self.scrollArea_2.setObjectName(_fromUtf8("scrollArea_2")) + self.scrollAreaWidgetContents_2 = QtGui.QWidget() + self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 303, 244)) + self.scrollAreaWidgetContents_2.setObjectName(_fromUtf8("scrollAreaWidgetContents_2")) + self.horizontalLayout_5 = QtGui.QHBoxLayout(self.scrollAreaWidgetContents_2) + self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5")) + self.groupBox_6 = QtGui.QGroupBox(self.scrollAreaWidgetContents_2) + self.groupBox_6.setMinimumSize(QtCore.QSize(0, 0)) + self.groupBox_6.setObjectName(_fromUtf8("groupBox_6")) + self.verticalLayout_5 = QtGui.QVBoxLayout(self.groupBox_6) + self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5")) + self.radioButton60Secs = QtGui.QRadioButton(self.groupBox_6) + self.radioButton60Secs.setChecked(True) + self.radioButton60Secs.setObjectName(_fromUtf8("radioButton60Secs")) + self.verticalLayout_5.addWidget(self.radioButton60Secs) + self.radioButton300Secs = QtGui.QRadioButton(self.groupBox_6) + self.radioButton300Secs.setObjectName(_fromUtf8("radioButton300Secs")) + self.verticalLayout_5.addWidget(self.radioButton300Secs) + self.radioButton600Secs = QtGui.QRadioButton(self.groupBox_6) + self.radioButton600Secs.setObjectName(_fromUtf8("radioButton600Secs")) + self.verticalLayout_5.addWidget(self.radioButton600Secs) + self.radioButton3600Secs = QtGui.QRadioButton(self.groupBox_6) + self.radioButton3600Secs.setObjectName(_fromUtf8("radioButton3600Secs")) + self.verticalLayout_5.addWidget(self.radioButton3600Secs) + spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) + self.verticalLayout_5.addItem(spacerItem1) + self.horizontalLayout_5.addWidget(self.groupBox_6) + self.groupBox_4 = QtGui.QGroupBox(self.scrollAreaWidgetContents_2) + self.groupBox_4.setMinimumSize(QtCore.QSize(0, 0)) + self.groupBox_4.setObjectName(_fromUtf8("groupBox_4")) + self.verticalLayout_4 = QtGui.QVBoxLayout(self.groupBox_4) + self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4")) + self.radioButton1Sec = QtGui.QRadioButton(self.groupBox_4) + self.radioButton1Sec.setObjectName(_fromUtf8("radioButton1Sec")) + self.verticalLayout_4.addWidget(self.radioButton1Sec) + self.radioButton2Secs = QtGui.QRadioButton(self.groupBox_4) + self.radioButton2Secs.setChecked(True) + self.radioButton2Secs.setObjectName(_fromUtf8("radioButton2Secs")) + self.verticalLayout_4.addWidget(self.radioButton2Secs) + self.radioButton5Secs = QtGui.QRadioButton(self.groupBox_4) + self.radioButton5Secs.setObjectName(_fromUtf8("radioButton5Secs")) + self.verticalLayout_4.addWidget(self.radioButton5Secs) + self.radioButton10Secs = QtGui.QRadioButton(self.groupBox_4) + self.radioButton10Secs.setObjectName(_fromUtf8("radioButton10Secs")) + self.verticalLayout_4.addWidget(self.radioButton10Secs) + spacerItem2 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) + self.verticalLayout_4.addItem(spacerItem2) + self.horizontalLayout_5.addWidget(self.groupBox_4) + self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2) + self.horizontalLayout_4.addWidget(self.scrollArea_2) + self.tabWidget.addTab(self.tab_4, _fromUtf8("")) + self.horizontalLayout.addWidget(self.tabWidget) + + self.retranslateUi(Form) + self.tabWidget.setCurrentIndex(0) + QtCore.QMetaObject.connectSlotsByName(Form) + + def retranslateUi(self, Form): + Form.setWindowTitle(_translate("Form", "Form", None)) + self.groupBox_3.setTitle(_translate("Form", "System Info", None)) + self.labelComputerName.setText(_translate("Form", "Computer Name: ", None)) + self.labelOS.setText(_translate("Form", "Operating System:", None)) + self.labelProcFam.setText(_translate("Form", "Processor Family:", None)) + self.labelNUsers.setText(_translate("Form", "Number of Users Logged On:", None)) + self.labelUptime.setText(_translate("Form", "System Uptime: ", None)) + self.groupBox_5.setTitle(_translate("Form", "Composite System Status", None)) + self.labelMemUsage.setText(_translate("Form", "Memory Usage", None)) + self.labelCPUCount.setText(_translate("Form", "CPU count:", None)) + self.labelMaxMem.setText(_translate("Form", "Max Mem:", None)) + self.label_102.setText(_translate("Form", "Composite CPU Usage", None)) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("Form", "System", None)) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("Form", "History", None)) + self.labelLastUpdate.setText(_translate("Form", "Last Update: ", None)) + self.tableWidgetProcess.setSortingEnabled(True) + item = self.tableWidgetProcess.horizontalHeaderItem(0) + item.setText(_translate("Form", "PID", None)) + item = self.tableWidgetProcess.horizontalHeaderItem(1) + item.setText(_translate("Form", "USER", None)) + item = self.tableWidgetProcess.horizontalHeaderItem(2) + item.setText(_translate("Form", "CPU%", None)) + item = self.tableWidgetProcess.horizontalHeaderItem(3) + item.setText(_translate("Form", "MEM%", None)) + item = self.tableWidgetProcess.horizontalHeaderItem(4) + item.setText(_translate("Form", "NAME", None)) + self.pushButtonUpdate.setText(_translate("Form", "Hold Updates", None)) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("Form", "Processes", None)) + self.groupBox.setTitle(_translate("Form", "Sort", None)) + self.radioButtonCPU.setText(_translate("Form", "CPU", None)) + self.radioButtonMem.setText(_translate("Form", "Memory", None)) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_5), _translate("Form", "Users", None)) + self.groupBox_6.setTitle(_translate("Form", "Display Period", None)) + self.radioButton60Secs.setText(_translate("Form", "60 Seconds", None)) + self.radioButton300Secs.setText(_translate("Form", "300 Seconds", None)) + self.radioButton600Secs.setText(_translate("Form", "600 Seconds", None)) + self.radioButton3600Secs.setText(_translate("Form", "3600 Seconds", None)) + self.groupBox_4.setTitle(_translate("Form", "Update Rate", None)) + self.radioButton1Sec.setText(_translate("Form", "1 Second", None)) + self.radioButton2Secs.setText(_translate("Form", "2 Seconds", None)) + self.radioButton5Secs.setText(_translate("Form", "5 Seconds", None)) + self.radioButton10Secs.setText(_translate("Form", "10 Seconds", None)) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), _translate("Form", "Options", None)) + diff --git a/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui new file mode 100644 index 000000000000..2dfbc897f680 --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui @@ -0,0 +1,670 @@ + + + Form + + + + 0 + 0 + 230 + 331 + + + + + 16777215 + 16777215 + + + + Form + + + + + + + 0 + 0 + + + + 0 + + + + System + + + + + + true + + + + + 0 + 0 + 320 + 293 + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + System Info + + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + Computer Name: + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + Operating System: + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + Processor Family: + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + Number of Users Logged On: + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + System Uptime: + + + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 50 + false + false + + + + Composite System Status + + + + + + + false + + + + Memory Usage + + + + + + + CPU count: + + + + + + + Max Mem: + + + + + + + + false + + + + Composite CPU Usage + + + + + + + + 0 + 0 + + + + 24 + + + + + + + + 0 + 0 + + + + 24 + + + + + + + + + + + + + + + + + + History + + + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + + + Processes + + + + + + + + + 0 + 0 + + + + + 300 + 16777215 + + + + Last Update: + + + + + + + + + + 100 + 100 + + + + + 0 + 0 + + + + QAbstractItemView::NoEditTriggers + + + true + + + 10 + + + 5 + + + 57 + + + true + + + true + + + false + + + 20 + + + true + + + + + + + + + + + + + + PID + + + + + USER + + + + + CPU% + + + + + MEM% + + + + + NAME + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 80 + 15 + + + + + 7 + + + + Hold Updates + + + + + + + + + + Users + + + + + + Sort + + + + 3 + + + 2 + + + + + + 0 + 0 + + + + + 0 + 0 + + + + CPU + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + Memory + + + true + + + + + + + + + + + 0 + 0 + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + + + Options + + + + + + true + + + + + 0 + 0 + 303 + 244 + + + + + + + + 0 + 0 + + + + Display Period + + + + + + 60 Seconds + + + true + + + + + + + 300 Seconds + + + + + + + 600 Seconds + + + + + + + 3600 Seconds + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + 0 + 0 + + + + Update Rate + + + + + + 1 Second + + + + + + + 2 Seconds + + + true + + + + + + + 5 Seconds + + + + + + + 10 Seconds + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + + + + + + + + diff --git a/Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.py b/Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.py new file mode 100644 index 000000000000..a7c6a67caaf2 --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'ui_sysmonMainWindow.ui' +# +# Created: Wed Sep 17 15:59:14 2014 +# by: PyQt4 UI code generator 4.8.3 +# +# WARNING! All changes made in this file will be lost! + +from PyQt4 import QtCore, QtGui + +try: + _fromUtf8 = QtCore.QString.fromUtf8 +except AttributeError: + _fromUtf8 = lambda s: s + +class Ui_MainWindow(object): + def setupUi(self, MainWindow): + MainWindow.setObjectName(_fromUtf8("MainWindow")) + MainWindow.resize(427, 323) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) + MainWindow.setSizePolicy(sizePolicy) + MainWindow.setMinimumSize(QtCore.QSize(336, 282)) + self.centralwidget = QtGui.QWidget(MainWindow) + self.centralwidget.setObjectName(_fromUtf8("centralwidget")) + self.gridLayout = QtGui.QGridLayout(self.centralwidget) + self.gridLayout.setObjectName(_fromUtf8("gridLayout")) + MainWindow.setCentralWidget(self.centralwidget) + self.statusbar = QtGui.QStatusBar(MainWindow) + self.statusbar.setObjectName(_fromUtf8("statusbar")) + MainWindow.setStatusBar(self.statusbar) + self.menubar = QtGui.QMenuBar(MainWindow) + self.menubar.setGeometry(QtCore.QRect(0, 0, 427, 21)) + self.menubar.setObjectName(_fromUtf8("menubar")) + self.menuFile = QtGui.QMenu(self.menubar) + self.menuFile.setObjectName(_fromUtf8("menuFile")) + self.menuHelp = QtGui.QMenu(self.menubar) + self.menuHelp.setObjectName(_fromUtf8("menuHelp")) + self.menuCustom = QtGui.QMenu(self.menubar) + self.menuCustom.setObjectName(_fromUtf8("menuCustom")) + MainWindow.setMenuBar(self.menubar) + self.actionExit = QtGui.QAction(MainWindow) + self.actionExit.setObjectName(_fromUtf8("actionExit")) + self.actionAbout = QtGui.QAction(MainWindow) + self.actionAbout.setObjectName(_fromUtf8("actionAbout")) + self.actionCheck_Matlab_Licenses = QtGui.QAction(MainWindow) + self.actionCheck_Matlab_Licenses.setObjectName(_fromUtf8("actionCheck_Matlab_Licenses")) + self.menuFile.addAction(self.actionExit) + self.menuHelp.addAction(self.actionAbout) + self.menuCustom.addAction(self.actionCheck_Matlab_Licenses) + self.menubar.addAction(self.menuFile.menuAction()) + self.menubar.addAction(self.menuHelp.menuAction()) + self.menubar.addAction(self.menuCustom.menuAction()) + + self.retranslateUi(MainWindow) + QtCore.QMetaObject.connectSlotsByName(MainWindow) + + def retranslateUi(self, MainWindow): + MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "System Monitor", None, QtGui.QApplication.UnicodeUTF8)) + self.menuFile.setTitle(QtGui.QApplication.translate("MainWindow", "File", None, QtGui.QApplication.UnicodeUTF8)) + self.menuHelp.setTitle(QtGui.QApplication.translate("MainWindow", "Help", None, QtGui.QApplication.UnicodeUTF8)) + self.menuCustom.setTitle(QtGui.QApplication.translate("MainWindow", "Custom", None, QtGui.QApplication.UnicodeUTF8)) + self.actionExit.setText(QtGui.QApplication.translate("MainWindow", "Exit", None, QtGui.QApplication.UnicodeUTF8)) + self.actionAbout.setText(QtGui.QApplication.translate("MainWindow", "About", None, QtGui.QApplication.UnicodeUTF8)) + self.actionCheck_Matlab_Licenses.setText(QtGui.QApplication.translate("MainWindow", "Check Matlab Licenses", None, QtGui.QApplication.UnicodeUTF8)) + diff --git a/Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.ui b/Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.ui new file mode 100644 index 000000000000..75196f8911a9 --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.ui @@ -0,0 +1,81 @@ + + + MainWindow + + + + 0 + 0 + 427 + 323 + + + + + 0 + 0 + + + + + 336 + 282 + + + + System Monitor + + + + + + + + + 0 + 0 + 427 + 21 + + + + + File + + + + + + Help + + + + + + Custom + + + + + + + + + + Exit + + + + + About + + + + + Check Matlab Licenses + + + + + + diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 9bef2715e1ac..191ac4fd666d 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -179,8 +179,9 @@ //Mantid #include "ScriptingWindow.h" -#include "Mantid/MantidUI.h" #include "Mantid/MantidAbout.h" +#include "Mantid/MantidDock.h" +#include "Mantid/MantidUI.h" #include "Mantid/PeakPickerTool.h" #include "Mantid/ManageCustomMenus.h" #include "Mantid/ManageInterfaceCategories.h" @@ -433,6 +434,10 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args) explorerSplitter->setSizes( splitterSizes << 45 << 45); explorerWindow->hide(); + // Other docked widgets + m_interpreterDock = new QDockWidget(this); + m_sysMonitorDock = new QDockWidget(this); + // Needs to be done after initialization of dock windows, // because we now use QDockWidget::toggleViewAction() createActions(); @@ -562,7 +567,7 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args) setScriptingLanguage(defaultScriptingLang); m_iface_script = NULL; - m_interpreterDock = new QDockWidget(this); + // -- IPython docked widget -- m_interpreterDock->setObjectName("interpreterDock"); // this is needed for QMainWindow::restoreState() m_interpreterDock->setWindowTitle("Script Interpreter"); runPythonScript("from ipython_widget import *\nw = _qti.app._getInterpreterDock()\nw.setWidget(MantidIPythonWidget())",false,true,true); @@ -572,6 +577,33 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args) addDockWidget( Qt::BottomDockWidgetArea, m_interpreterDock ); } + // Algorithms, Workspaces & SysMonitor + if ( !restoreDockWidget(mantidUI->m_exploreMantid)) + { + addDockWidget(Qt::RightDockWidgetArea, mantidUI->m_exploreMantid); + } + if ( !restoreDockWidget(mantidUI->m_exploreAlgorithms)) + { + addDockWidget(Qt::RightDockWidgetArea, mantidUI->m_exploreAlgorithms); + } + m_sysMonitorDock->setObjectName("systemMonitor"); // this is needed for QMainWindow::restoreState() + m_sysMonitorDock->setWindowTitle("System Monitor"); + runPythonScript("from SysMon import sysmon\n" + "w = sysmon.SysMon(_qti.app._getSysMonitorDock())\n" + "_qti.app._getSysMonitorDock().setWidget(w)", + false,true,true); + if ( !restoreDockWidget(m_sysMonitorDock)) + { + // Setting the max width to 300 and then to -1 later seems to + // be the only way that I found to get the dock to have a decent initial + // size but then still be resizable. + m_sysMonitorDock->setMaximumWidth(300); + addDockWidget(Qt::RightDockWidgetArea, m_sysMonitorDock); + m_sysMonitorDock->setMaximumWidth(-1); + } + tabifyDockWidget(mantidUI->m_exploreAlgorithms, m_sysMonitorDock); // first, second in that order on tabs + mantidUI->m_exploreAlgorithms->raise(); + loadCustomActions(); // Nullify catalogSearch @@ -598,13 +630,13 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args) { const Mantid::Kernel::FacilityInfo& facilityInfo = config.getFacility(facility); const Mantid::Kernel::InstrumentInfo& instrumentInfo = config.getInstrument(instrument); - g_log.information()<<"Default facility '" << facilityInfo.name() + g_log.information()<<"Default facility '" << facilityInfo.name() << "', instrument '" << instrumentInfo.name() << "'" << std::endl; } catch (Mantid::Kernel::Exception::NotFoundError&) { //failed to find the facility or instrument - g_log.error()<<"Could not find your default facility '" << facility + g_log.error()<<"Could not find your default facility '" << facility <<"' or instrument '" << instrument << "' in facilities.xml, showing please select again." << std::endl; showFirstTimeSetup(); } @@ -1198,6 +1230,10 @@ void ApplicationWindow::initMainMenu() mantidUI->addMenuItems(view); + view->insertSeparator(); + m_sysMonitorDock->toggleViewAction()->setChecked(false); + view->addAction(m_sysMonitorDock->toggleViewAction()); + view->insertSeparator(); toolbarsMenu = view->addMenu(tr("&Toolbars")); view->addAction(actionShowConfigureDialog); diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.h b/Code/Mantid/MantidPlot/src/ApplicationWindow.h index 5de461c6140a..1b6c59ccfc72 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.h +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.h @@ -238,7 +238,7 @@ public slots: void onScriptExecuteError(const QString & message, const QString & scriptName, int lineNumber); /// Runs an arbitrary lump of python code, return true/false on success/failure. bool runPythonScript(const QString & code, bool async = false, bool quiet=false, bool redirect=true); - + QList windowsList() const; QList getAllWindows() const; void updateWindowLists(MdiSubWindow *w); @@ -607,8 +607,8 @@ public slots: //! Creates a new empty multilayer plot MultiLayer* newGraph(const QString& caption = tr("Graph")); - /// Prepares MultiLayer for plotting - creates if necessary, clears, applies initial settings - MultiLayer* prepareMultiLayer(bool& isNew, MultiLayer* window, const QString& newWindowName = "Graph", + /// Prepares MultiLayer for plotting - creates if necessary, clears, applies initial settings + MultiLayer* prepareMultiLayer(bool& isNew, MultiLayer* window, const QString& newWindowName = "Graph", bool clearWindow = false); //! \name Reading from a Project File @@ -1020,12 +1020,12 @@ public slots: //@{ //! show scripting language selection dialog void showScriptingLangDialog(); - //! switches to the given scripting language; + //! switches to the given scripting language; bool setScriptingLanguage(const QString &lang); void scriptsDirPathChanged(const QString& path); //@} - + void makeToolbarsMenu(); void savetoNexusFile(); @@ -1105,7 +1105,7 @@ public slots: private slots: //! \name Initialization //@{ - + void setToolbars(); void displayToolbars(); void insertTranslatedStrings(); @@ -1321,7 +1321,7 @@ public slots: bool applyCurveStyleToMantid; ///< if true defaultCurveStyle, defaultSymbolSize are applyed to MantidCurves /// if true all errors are drawn on new plots with error bars, for a particular graph can be overridden /// form Add Error bars dialog - bool drawAllErrors; + bool drawAllErrors; QFont appFont, plot3DTitleFont, plot3DNumbersFont, plot3DAxesFont; QFont tableTextFont, tableHeaderFont, plotAxesFont, plotLegendFont, plotNumbersFont, plotTitleFont; QColor tableBkgdColor, tableTextColor, tableHeaderColor; @@ -1355,7 +1355,8 @@ public slots: QString defaultScriptingLang; QDockWidget *m_interpreterDock; - + QDockWidget *m_sysMonitorDock; + QSet allCategories() const { return m_allCategories; } private: @@ -1414,7 +1415,7 @@ public slots: QWidget* catalogSearch; QMenu *windowsMenu, *foldersMenu, *view, *graph, *fileMenu, *format, *edit, *recent, *interfaceMenu; - + QMenu *help, *plot2DMenu, *analysisMenu, *multiPeakMenu, *icat; QMenu *matrixMenu, *plot3DMenu, *plotDataMenu, *tablesDepend, *scriptingMenu; QMenu *tableMenu, *fillMenu, *normMenu, *newMenu, *exportPlotMenu, *smoothMenu, *filterMenu, *decayMenu,*saveMenu,*openMenu, *toolbarsMenu; @@ -1497,7 +1498,7 @@ public slots: QList d_user_actions; QList d_user_menus; //Mantid - + QList m_interfaceActions; /// list of mantidmatrix windows opened from project file. @@ -1516,7 +1517,7 @@ public slots: QList m_floatingWindows; // To block activating new window when a floating window is in process of resetting flags bool blockWindowActivation; - /// + /// bool m_enableQtiPlotFitting; #ifdef SHARED_MENUBAR diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp index 7afd72387f57..34762962e1e0 100644 --- a/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp +++ b/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp @@ -43,7 +43,6 @@ MantidDockWidget::MantidDockWidget(MantidUI *mui, ApplicationWindow *parent) : setObjectName("exploreMantid"); // this is needed for QMainWindow::restoreState() setMinimumHeight(150); setMinimumWidth(200); - parent->addDockWidget( Qt::RightDockWidgetArea, this ); QFrame *f = new QFrame(this); setWidget(f); @@ -65,13 +64,13 @@ MantidDockWidget::MantidDockWidget(MantidUI *mui, ApplicationWindow *parent) : buttonLayout->addWidget(m_sortButton); m_workspaceFilter = new MantidQt::MantidWidgets::LineEditWithClear(); - m_workspaceFilter->setPlaceholderText("Filter Workspaces"); - m_workspaceFilter->setToolTip("Type here to filter the workspaces"); + m_workspaceFilter->setPlaceholderText("Filter Workspaces"); + m_workspaceFilter->setToolTip("Type here to filter the workspaces"); connect(m_workspaceFilter, SIGNAL(textChanged(const QString&)), this, SLOT(filterWorkspaceTree(const QString&))); QVBoxLayout * layout = new QVBoxLayout(); - f->setLayout(layout); + f->setLayout(layout); layout->setSpacing(0); layout->setMargin(0); layout->addLayout(buttonLayout); @@ -189,7 +188,7 @@ void MantidDockWidget::createWorkspaceMenuActions() connect(m_showMDPlot, SIGNAL(activated()), m_mantidUI, SLOT(showMDPlot())); m_showListData = new QAction(tr("List Data"), this); - connect(m_showListData, SIGNAL(activated()), m_mantidUI, SLOT(showListData())); + connect(m_showListData, SIGNAL(activated()), m_mantidUI, SLOT(showListData())); m_showSpectrumViewer = new QAction(tr("Show Spectrum Viewer"), this); connect(m_showSpectrumViewer, SIGNAL(activated()), m_mantidUI, SLOT(showSpectrumViewer())); @@ -668,7 +667,7 @@ void MantidDockWidget::filterWorkspaceTree(const QString &text) //show all items QTreeWidgetItemIterator it(m_tree); - while (*it) + while (*it) { (*it)->setHidden(false); ++it; @@ -691,7 +690,7 @@ void MantidDockWidget::filterWorkspaceTree(const QString &text) { expanded << item->text(0); } - else + else { //expand everything that is at the top level (as we lazy load this is required) item->setExpanded(true); @@ -700,12 +699,12 @@ void MantidDockWidget::filterWorkspaceTree(const QString &text) //filter based on the string QTreeWidgetItemIterator it(m_tree,QTreeWidgetItemIterator::All); - while (*it) + while (*it) { QTreeWidgetItem *item = (*it); QVariant userData = item->data(0, Qt::UserRole); - if (!userData.isNull() ) + if (!userData.isNull() ) { Workspace_sptr workspace = userData.value(); if (workspace) @@ -756,10 +755,10 @@ void MantidDockWidget::filterWorkspaceTree(const QString &text) //make children of visible groups visible for (auto itGroup = visibleGroups.begin(); itGroup != visibleGroups.end(); ++itGroup) { - QTreeWidgetItem *group = (*itGroup); + QTreeWidgetItem *group = (*itGroup); for (int i = 0; i < group->childCount(); i++) { - QTreeWidgetItem *child = group->child(i); + QTreeWidgetItem *child = group->child(i); if (child->isHidden()) { //I was previously hidden, show me @@ -797,7 +796,7 @@ void MantidDockWidget::clickedWorkspace(QTreeWidgetItem* item, int) } void MantidDockWidget::workspaceSelected() -{ +{ QList selectedItems=m_tree->selectedItems(); if(selectedItems.isEmpty()) return; QString wsName=selectedItems[0]->text(0); @@ -820,7 +819,7 @@ void MantidDockWidget::deleteWorkspaces() if(m->workspaceName().isEmpty()) return; if(m_ads.doesExist(m->workspaceName().toStdString())) - { + { m_mantidUI->deleteWorkspace(m->workspaceName()); } return; @@ -893,7 +892,7 @@ void MantidDockWidget::saveToProgram(const QString & name) } //Check to see if mandatory information is included - if ((programKeysAndDetails.count("name") != 0) && (programKeysAndDetails.count("target") != 0) && (programKeysAndDetails.count("saveusing") != 0)) + if ((programKeysAndDetails.count("name") != 0) && (programKeysAndDetails.count("target") != 0) && (programKeysAndDetails.count("saveusing") != 0)) { std::string expTarget = Poco::Path::expand(programKeysAndDetails.find("target")->second); @@ -1057,7 +1056,7 @@ void MantidDockWidget::popupMenu(const QPoint & pos) } // Add the items that are appropriate for the type - if( MatrixWorkspace_const_sptr matrixWS = boost::dynamic_pointer_cast(ws) ) + if( MatrixWorkspace_const_sptr matrixWS = boost::dynamic_pointer_cast(ws) ) { addMatrixWorkspaceMenuItems(menu, matrixWS); } @@ -1073,7 +1072,7 @@ void MantidDockWidget::popupMenu(const QPoint & pos) { addPeaksWorkspaceMenuItems(menu, peaksWS); } - else if( boost::dynamic_pointer_cast(ws) ) + else if( boost::dynamic_pointer_cast(ws) ) { addWorkspaceGroupMenuItems(menu); } @@ -1120,16 +1119,16 @@ void MantidDockWidget::popupMenu(const QPoint & pos) connect(m_program,SIGNAL(activated()),m_programMapper,SLOT(map())); //Send name of program when clicked m_programMapper->setMapping(m_program, name); - m_saveToProgram->addAction(m_program); + m_saveToProgram->addAction(m_program); // Set first pass to false so that it doesn't set up another menu entry for all programs. firstPass = false; } - } + } } //Tell the button what to listen for and what to do once clicked (if there is anything to connect it will be set to false) - if (firstPass == false) + if (firstPass == false) connect(m_programMapper, SIGNAL(mapped(const QString &)), this, SLOT(saveToProgram(const QString &))); //Rename is valid for all workspace types @@ -1352,11 +1351,11 @@ void MantidTreeWidget::dragEnterEvent(QDragEnterEvent *de) void MantidTreeWidget::dropEvent(QDropEvent *de) { QStringList filenames; - const QMimeData *mimeData = de->mimeData(); - if (mimeData->hasUrls()) + const QMimeData *mimeData = de->mimeData(); + if (mimeData->hasUrls()) { QList urlList = mimeData->urls(); - for (int i = 0; i < urlList.size(); ++i) + for (int i = 0; i < urlList.size(); ++i) { QString fName = urlList[i].toLocalFile(); if (fName.size()>0) @@ -1367,7 +1366,7 @@ void MantidTreeWidget::dropEvent(QDropEvent *de) } de->acceptProposedAction(); - for (int i = 0; i < filenames.size(); ++i) + for (int i = 0; i < filenames.size(); ++i) { try { @@ -1382,7 +1381,7 @@ void MantidTreeWidget::dropEvent(QDropEvent *de) catch (std::runtime_error& error) { treelog.error()<<"Failed to Load the file "< > MantidTreeWidget::chooseSpectrumFromSelected() return spectrumToPlot; } - // Else, one or more workspaces + // Else, one or more workspaces MantidWSIndexDialog *dio = new MantidWSIndexDialog(m_mantidUI, 0, selectedMatrixWsNameList); dio->exec(); return dio->getPlots(); @@ -1716,7 +1715,6 @@ AlgorithmDockWidget::AlgorithmDockWidget(MantidUI *mui, ApplicationWindow *w): setObjectName("exploreAlgorithms"); // this is needed for QMainWindow::restoreState() setMinimumHeight(150); setMinimumWidth(200); - w->addDockWidget( Qt::RightDockWidgetArea, this );//*/ //Add the AlgorithmSelectorWidget m_selector = new MantidQt::MantidWidgets::AlgorithmSelectorWidget(this); @@ -1829,4 +1827,3 @@ void AlgorithmDockWidget::hideProgressBar() //-------------------- ----------------------// - diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h b/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h index 5f7f9194029f..b64a7c3d45ca 100644 --- a/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h +++ b/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h @@ -192,7 +192,7 @@ class MantidUI:public QObject void showAlgWidget(bool on = true); /// Plot a 1D graph for an integrated mdworkspace - MultiLayer* plotMDList(const QStringList& wsNames, const int plotAxis, + MultiLayer* plotMDList(const QStringList& wsNames, const int plotAxis, const Mantid::API::MDNormalization normalization, const bool showError, MultiLayer* plotWindow = NULL, bool clearWindow = false); @@ -239,7 +239,7 @@ class MantidUI:public QObject /// Create a table showing detector information for the given workspace and indices and optionally the data for that detector Table* createDetectorTable(const QString & wsName, const std::vector& indices, bool include_data = false); /// Create the instrument detector table from a MatrixWorkspace - Table* createDetectorTable(const QString & wsName, const Mantid::API::MatrixWorkspace_sptr & ws, + Table* createDetectorTable(const QString & wsName, const Mantid::API::MatrixWorkspace_sptr & ws, const std::vector& indices, bool include_data = false); /// Create a table of detectors from a PeaksWorkspace Table* createDetectorTable(const QString & wsName, const Mantid::API::IPeaksWorkspace_sptr & ws); @@ -253,7 +253,7 @@ class MantidUI:public QObject void renameWorkspace(QStringList = QStringList()); /** - * Set the currently used fit property browser. Is needed because e.g. Muon Analysis is using its + * Set the currently used fit property browser. Is needed because e.g. Muon Analysis is using its * own fit browser. * @param newBrowser The browser to be used. If is null, is set to default one. */ @@ -281,7 +281,7 @@ class MantidUI:public QObject */ void savedatainNexusFormat(const std::string& fileName,const std::string & wsName); - /** load data from nexus file.This method is useful + /** load data from nexus file.This method is useful when a project is opened from mantidplot */ void loaddataFromNexusFile(const std::string& wsname,const std::string& fileName,bool project=false); @@ -300,6 +300,15 @@ class MantidUI:public QObject public: + // QMainWindow needs the dock widgets to be accessible + MantidDockWidget *m_exploreMantid; // Dock window for manipulating workspaces + AlgorithmDockWidget *m_exploreAlgorithms; // Dock window for using algorithms + RemoteClusterDockWidget *m_exploreRemoteTasks; // Dock window for using remote tasks + /// Current fit property browser being used + MantidQt::MantidWidgets::FitPropertyBrowser* m_fitFunction; + /// Default fit property browser (the one docked on the left) + MantidQt::MantidWidgets::FitPropertyBrowser* m_defaultFitFunction; + signals: // These signals are to be fired from methods run in threads other than the main one @@ -463,11 +472,11 @@ class MantidUI:public QObject void handleRenameWorkspace(Mantid::API::WorkspaceRenameNotification_ptr pNf); Poco::NObserver m_renameObserver; - //handles notification send by Groupworkspaces algorithm + //handles notification send by Groupworkspaces algorithm void handleGroupWorkspaces(Mantid::API::WorkspacesGroupedNotification_ptr pNf); Poco::NObserver m_groupworkspacesObserver; - //handles notification send by UnGroupworkspaces algorithm + //handles notification send by UnGroupworkspaces algorithm void handleUnGroupWorkspace(Mantid::API::WorkspaceUnGroupingNotification_ptr pNf); Poco::NObserver m_ungroupworkspaceObserver; @@ -498,13 +507,6 @@ class MantidUI:public QObject // Private variables ApplicationWindow *m_appWindow; // QtiPlot main ApplicationWindow - MantidDockWidget *m_exploreMantid; // Dock window for manipulating workspaces - AlgorithmDockWidget *m_exploreAlgorithms; // Dock window for using algorithms - RemoteClusterDockWidget *m_exploreRemoteTasks; // Dock window for using remote tasks - /// Current fit property browser being used - MantidQt::MantidWidgets::FitPropertyBrowser* m_fitFunction; - /// Default fit property browser (the one docked on the left) - MantidQt::MantidWidgets::FitPropertyBrowser* m_defaultFitFunction; QAction *actionCopyRowToTable; QAction *actionCopyRowToGraph; diff --git a/Code/Mantid/MantidPlot/src/qti.sip b/Code/Mantid/MantidPlot/src/qti.sip index ac8ddf4dfe69..6e13fc1d2d37 100644 --- a/Code/Mantid/MantidPlot/src/qti.sip +++ b/Code/Mantid/MantidPlot/src/qti.sip @@ -1083,9 +1083,9 @@ public: %End Matrix* newMatrix(); Matrix* newMatrix(const QString&, int=32, int=32); - + TiledWindow *newTiledWindow(); - + MultiLayer *plot(const QString&) /PyName=graph/; %MethodCode sipRes = sipCpp->current_folder->graph(*a0, false); @@ -1167,6 +1167,12 @@ public: sipRes = sipCpp->m_interpreterDock; %End + // Required for setting the SysMon widget + QDockWidget _getSysMonitorDock(); +%MethodCode + sipRes = sipCpp->m_sysMonitorDock; +%End + // folders Folder *activeFolder(); %MethodCode From e59fb62ec8f1d28de3fe6d30383d20463bedaecd Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Fri, 19 Sep 2014 14:32:04 +0100 Subject: [PATCH 002/414] Add a check for the psutil package The system monitor is only made available if this package is present. Refs #9843 --- .../MantidPlot/src/ApplicationWindow.cpp | 63 +++++++++++++------ .../Mantid/MantidPlot/src/ApplicationWindow.h | 2 + 2 files changed, 46 insertions(+), 19 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 191ac4fd666d..0400d6a8ed8a 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -436,7 +436,7 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args) // Other docked widgets m_interpreterDock = new QDockWidget(this); - m_sysMonitorDock = new QDockWidget(this); + if(psutilPresent()) m_sysMonitorDock = new QDockWidget(this); // Needs to be done after initialization of dock windows, // because we now use QDockWidget::toggleViewAction() @@ -586,23 +586,26 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args) { addDockWidget(Qt::RightDockWidgetArea, mantidUI->m_exploreAlgorithms); } - m_sysMonitorDock->setObjectName("systemMonitor"); // this is needed for QMainWindow::restoreState() - m_sysMonitorDock->setWindowTitle("System Monitor"); - runPythonScript("from SysMon import sysmon\n" - "w = sysmon.SysMon(_qti.app._getSysMonitorDock())\n" - "_qti.app._getSysMonitorDock().setWidget(w)", - false,true,true); - if ( !restoreDockWidget(m_sysMonitorDock)) + if(psutilPresent()) { - // Setting the max width to 300 and then to -1 later seems to - // be the only way that I found to get the dock to have a decent initial - // size but then still be resizable. - m_sysMonitorDock->setMaximumWidth(300); - addDockWidget(Qt::RightDockWidgetArea, m_sysMonitorDock); - m_sysMonitorDock->setMaximumWidth(-1); + m_sysMonitorDock->setObjectName("systemMonitor"); // this is needed for QMainWindow::restoreState() + m_sysMonitorDock->setWindowTitle("System Monitor"); + runPythonScript("from SysMon import sysmon\n" + "w = sysmon.SysMon(_qti.app._getSysMonitorDock())\n" + "_qti.app._getSysMonitorDock().setWidget(w)", + false, true, true); + if ( !restoreDockWidget(m_sysMonitorDock)) + { + // Setting the max width to 300 and then to -1 later seems to + // be the only way that I found to get the dock to have a decent initial + // size but then still be resizable. + m_sysMonitorDock->setMaximumWidth(300); + addDockWidget(Qt::RightDockWidgetArea, m_sysMonitorDock); + m_sysMonitorDock->setMaximumWidth(-1); + } + tabifyDockWidget(mantidUI->m_exploreAlgorithms, m_sysMonitorDock); // first, second in that order on tabs + mantidUI->m_exploreAlgorithms->raise(); } - tabifyDockWidget(mantidUI->m_exploreAlgorithms, m_sysMonitorDock); // first, second in that order on tabs - mantidUI->m_exploreAlgorithms->raise(); loadCustomActions(); @@ -1230,9 +1233,12 @@ void ApplicationWindow::initMainMenu() mantidUI->addMenuItems(view); - view->insertSeparator(); - m_sysMonitorDock->toggleViewAction()->setChecked(false); - view->addAction(m_sysMonitorDock->toggleViewAction()); + if(psutilPresent()) + { + view->insertSeparator(); + m_sysMonitorDock->toggleViewAction()->setChecked(false); + view->addAction(m_sysMonitorDock->toggleViewAction()); + } view->insertSeparator(); toolbarsMenu = view->addMenu(tr("&Toolbars")); @@ -16662,6 +16668,25 @@ bool ApplicationWindow::runPythonScript(const QString & code, bool async, return success; } +/// @return True if the psuitl python module is present and importable otherwise return false +bool ApplicationWindow::psutilPresent() +{ + static bool checkPerformed(false); + static bool pkgPresent(false); + + if(!checkPerformed) + { + g_log.debug("Checking for psutil\n"); + using Mantid::Kernel::Logger; + bool verbose = g_log.is(Logger::Priority::PRIO_DEBUG); + pkgPresent = runPythonScript("import psutil", false, false, verbose); + if(pkgPresent) g_log.debug() << "Found psutil package"; + else g_log.debug() << "Unable to find psutil package"; + checkPerformed = true; + } + + return pkgPresent; +} bool ApplicationWindow::validFor2DPlot(Table *table) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.h b/Code/Mantid/MantidPlot/src/ApplicationWindow.h index 1b6c59ccfc72..0a4adca650d1 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.h +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.h @@ -238,6 +238,8 @@ public slots: void onScriptExecuteError(const QString & message, const QString & scriptName, int lineNumber); /// Runs an arbitrary lump of python code, return true/false on success/failure. bool runPythonScript(const QString & code, bool async = false, bool quiet=false, bool redirect=true); + /// Checks for the presence of the Python psutil module for the system monitor widget + bool psutilPresent(); QList windowsList() const; QList getAllWindows() const; From 666e9bfbb3064c58f1623b329849936cd5899c87 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Fri, 19 Sep 2014 17:28:40 +0100 Subject: [PATCH 003/414] Fix order in which psutil check is applied. The scripting environment needs to have been started before we can check for the package. Refs #9843 --- .../MantidPlot/src/ApplicationWindow.cpp | 31 ++++++++++++++----- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 0400d6a8ed8a..a643d4b13020 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -436,7 +436,7 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args) // Other docked widgets m_interpreterDock = new QDockWidget(this); - if(psutilPresent()) m_sysMonitorDock = new QDockWidget(this); + m_sysMonitorDock = new QDockWidget(this); // Needs to be done after initialization of dock windows, // because we now use QDockWidget::toggleViewAction() @@ -605,6 +605,24 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args) } tabifyDockWidget(mantidUI->m_exploreAlgorithms, m_sysMonitorDock); // first, second in that order on tabs mantidUI->m_exploreAlgorithms->raise(); + + } + else + { + // Remove menu item + auto actions = view->actions(); + auto itr = actions.constBegin(); + auto iend = actions.constEnd(); + for(; itr != iend; ++itr) + { + if(*itr == m_sysMonitorDock->toggleViewAction()) break; + } + // Move back for the separator + if(itr != actions.constBegin()) --itr; + view->removeAction(*itr); + ++itr; + view->removeAction(*itr); + delete m_sysMonitorDock; } loadCustomActions(); @@ -1233,12 +1251,11 @@ void ApplicationWindow::initMainMenu() mantidUI->addMenuItems(view); - if(psutilPresent()) - { - view->insertSeparator(); - m_sysMonitorDock->toggleViewAction()->setChecked(false); - view->addAction(m_sysMonitorDock->toggleViewAction()); - } + // System monitor (might get removed later after check) + view->insertSeparator(); + m_sysMonitorDock->toggleViewAction()->setChecked(false); + view->addAction(m_sysMonitorDock->toggleViewAction()); + view->insertSeparator(); toolbarsMenu = view->addMenu(tr("&Toolbars")); From 04c574420718614e4d85a25ad4db05f63582f685 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Tue, 23 Sep 2014 07:55:29 +0100 Subject: [PATCH 004/414] Install the SysMon utility to include it in the package Refs #9843 --- Code/Mantid/MantidPlot/CMakeLists.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/CMakeLists.txt b/Code/Mantid/MantidPlot/CMakeLists.txt index 20ffa62bc0a5..731f74d95fad 100644 --- a/Code/Mantid/MantidPlot/CMakeLists.txt +++ b/Code/Mantid/MantidPlot/CMakeLists.txt @@ -847,7 +847,7 @@ copy_python_files_to_dir ( "${IPY_FILES}" ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/ipython_widget IPYTHON_INSTALL_FILES ) -# IPython scripts +# SysMon scripts set( SYSMON_FILES __init__.py config.py @@ -1005,6 +1005,9 @@ endforeach() foreach(PY_FILE ${IPY_FILES} ) install ( FILES ipython_widget/${PY_FILE} DESTINATION ${BIN_DIR}/ipython_widget ) endforeach() +foreach(PY_FILE ${SYSMON_FILES} ) + install ( FILES SysMon/${PY_FILE} DESTINATION ${BIN_DIR}/SysMon ) +endforeach() if ( APPLE ) configure_file ( ${CMAKE_CURRENT_SOURCE_DIR}/FixBundle.cmake.in From f18d79b8ff43f0709bc4e5d2abe99f9cdc463cbd Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Tue, 23 Sep 2014 16:06:24 +0100 Subject: [PATCH 005/414] Don't use negative sizes in the max width settings. Refs #9843 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index a643d4b13020..cb639704e6af 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -601,7 +601,7 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args) // size but then still be resizable. m_sysMonitorDock->setMaximumWidth(300); addDockWidget(Qt::RightDockWidgetArea, m_sysMonitorDock); - m_sysMonitorDock->setMaximumWidth(-1); + m_sysMonitorDock->setMaximumWidth(QWIDGETSIZE_MAX); // reset it } tabifyDockWidget(mantidUI->m_exploreAlgorithms, m_sysMonitorDock); // first, second in that order on tabs mantidUI->m_exploreAlgorithms->raise(); From 68c021ccbf466abf4eddbc5b0caf34cd622c8579 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Wed, 1 Oct 2014 15:46:51 +0100 Subject: [PATCH 006/414] Updating to SysMon v0.23 Refs #9843 --- Code/Mantid/MantidPlot/SysMon/config.py | 12 +- Code/Mantid/MantidPlot/SysMon/sysmon.py | 42 ++- Code/Mantid/MantidPlot/SysMon/sysmon_tools.py | 251 ++++++++++++------ Code/Mantid/MantidPlot/SysMon/ui_sysmon.py | 157 +++++------ Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui | 93 ++++--- 5 files changed, 345 insertions(+), 210 deletions(-) diff --git a/Code/Mantid/MantidPlot/SysMon/config.py b/Code/Mantid/MantidPlot/SysMon/config.py index 508ba68e711b..f52dcf1e520e 100644 --- a/Code/Mantid/MantidPlot/SysMon/config.py +++ b/Code/Mantid/MantidPlot/SysMon/config.py @@ -1,7 +1,7 @@ #global definitions for constants and variables -#Tab indices: +#Tab indices - based upon the order of the tabs as built via Qt and these must be the same as the Qt GUI. SYST_TAB=0 HIST_TAB=1 PROC_TAB=2 @@ -10,7 +10,11 @@ #Global Variables: psutilVer=0 #flag for the version of psutil being used -nompl=False +nompl=False #Flag to indicate if using matplotlib - True, then do not use plots, False, then try to use matplotlib plots mplLoaded=False #flag for matplotlib loading -custom=False -matlabchk='lmstat -S -c 27010@licenses1.sns.gov' \ No newline at end of file +custom=False #flag to indicate if the custom interface is to be used (usually not) +matlabchk='lmstat -S -c 27010@licenses1.sns.gov' #text command to status the Matlab license server (only for custom mode with SysMon.pyw) +basefontsize=9 #basic font size when GUI is at minimum size +fscl=0.5 #scale factor for font size change with GUI resizing - less than one, font size slower than GUI size change, and greater than one font size faster than GUI size change +pltFont=9 #initial font size for matplotlib plots +linewidth=1 #initial line widths for matplotlib plots \ No newline at end of file diff --git a/Code/Mantid/MantidPlot/SysMon/sysmon.py b/Code/Mantid/MantidPlot/SysMon/sysmon.py index 1f6ce7662002..d62254f7cff0 100644 --- a/Code/Mantid/MantidPlot/SysMon/sysmon.py +++ b/Code/Mantid/MantidPlot/SysMon/sysmon.py @@ -1,5 +1,5 @@ - + import sys, os, time import re import config #application constants and variables @@ -32,6 +32,7 @@ def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_Form() #defined from ui_sysmon.py self.ui.setupUi(self) + self.ui.parent=parent self.ui.progressBarStatusMemory.setStyleSheet("QProgressBar {width: 25px;border: 1px solid black; border-radius: 3px; background: white;text-align: center;padding: 0px;}" +"QProgressBar::chunk:horizontal {background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #00CCEE, stop: 0.3 #00DDEE, stop: 0.6 #00EEEE, stop:1 #00FFEE);}") self.ui.progressBarStatusCPU.setStyleSheet("QProgressBar {width: 25px;border: 1px solid black; border-radius: 3px; background: white;text-align: center;padding: 0px;}" @@ -39,7 +40,7 @@ def __init__(self, parent=None): #setup timer to enable periodic events such as status update checks self.ctimer = QtCore.QTimer() - self.ctimer.start(2000) #time in mSec - set repetitive timer of 2 seconds + self.ctimer.start(2000) #time in mSec - set default update timer cycle to 2 seconds QtCore.QObject.connect(self.ctimer, QtCore.SIGNAL("timeout()"), self.constantUpdate) #update rate actions @@ -130,13 +131,15 @@ def __init__(self, parent=None): self.ui.cpu=np.zeros(Nsamples+1) self.ui.mem=np.zeros(Nsamples+1) self.ui.dt=[None]*(Nsamples+1) + self.ui.cpuMe=np.zeros(Nsamples+1) + self.ui.memMe=np.zeros(Nsamples+1) self.ui.tabWidget.setTabsClosable(False) #disable the ability to close tabs once state of matplotlib is handled #initialize the process table self.doUpdates=True #flag for updating the process tab table updateProcTable(self,config) - + #upon initialization completion, set System tab (first tab on left) as the visible tab self.ui.tabWidget.setCurrentIndex(config.SYST_TAB) @@ -151,6 +154,8 @@ def update1Sec(self): #clear persistent arrays when update rate changed self.ui.cpu=self.ui.cpu*0 self.ui.mem=self.ui.mem*0 + self.ui.cpuMe=self.ui.cpuMe*0 + self.ui.memMe=self.ui.memMe*0 self.ui.dt=[None]*self.ui.Nsamples def update2Sec(self): @@ -160,6 +165,8 @@ def update2Sec(self): #clear persistent arrays when update rate changed self.ui.cpu=self.ui.cpu*0 self.ui.mem=self.ui.mem*0 + self.ui.cpuMe=self.ui.cpuMe*0 + self.ui.memMe=self.ui.memMe*0 self.ui.dt=[None]*self.ui.Nsamples def update5Sec(self): @@ -169,6 +176,8 @@ def update5Sec(self): #clear persistent arrays when update rate changed self.ui.cpu=self.ui.cpu*0 self.ui.mem=self.ui.mem*0 + self.ui.cpuMe=self.ui.cpuMe*0 + self.ui.memMe=self.ui.memMe*0 self.ui.dt=[None]*self.ui.Nsamples def update10Sec(self): @@ -178,6 +187,8 @@ def update10Sec(self): #clear persistent arrays when update rate changed self.ui.cpu=self.ui.cpu*0 self.ui.mem=self.ui.mem*0 + self.ui.cpuMe=self.ui.cpuMe*0 + self.ui.memMe=self.ui.memMe*0 self.ui.dt=[None]*self.ui.Nsamples def update60Duration(self): @@ -203,11 +214,26 @@ def resizeEvent(self,resizeEvent): print "resizing" sz=self.ui.tableWidgetProcess.size() w=sz.width() - self.ui.tableWidgetProcess.setColumnWidth(0,3*w/20) - self.ui.tableWidgetProcess.setColumnWidth(1,5*w/20) - self.ui.tableWidgetProcess.setColumnWidth(2,3*w/20) - self.ui.tableWidgetProcess.setColumnWidth(3,3*w/20) - self.ui.tableWidgetProcess.setColumnWidth(4,6*w/20) + wmin=self.ui.parent.minimumSize().width() #establish minimum table size based upon parent widget minimum size + if w < wmin: + w=wmin + #now use widget width to determine process table column width + self.ui.tableWidgetProcess.setColumnWidth(0,3.5*w/20) #PID + self.ui.tableWidgetProcess.setColumnWidth(1,4*w/20) #User + self.ui.tableWidgetProcess.setColumnWidth(2,3.5*w/20) #CPU% + self.ui.tableWidgetProcess.setColumnWidth(3,3.5*w/20) #MEM% + self.ui.tableWidgetProcess.setColumnWidth(4,5.5*w/20) #Name + + #check size of GUI to determine the size of font to use. + minSz=self.ui.parent.minimumSize().width() #establish minimum table size based upon parent widget minimum size + curSz=self.ui.parent.size().width() + #print "current size: ",curSz," type: ",type(curSz)," min size: ",minSz," type: ",type(minSz) + fsize=max([int(config.basefontsize*float(curSz)/float(minSz)*config.fscl),config.basefontsize]) + #print "Font Size: ",fsize + config.pltFont=fsize + + #adapt plot line width to GUI size change + config.linewidth=min([max([int(float(curSz)/float(minSz)),1]),3]) def removeMPLTabs(self): #In case matplotlib not available, remove tabs requiring this diff --git a/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py b/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py index 2e8d9eabb004..0fe4e1f87ad7 100644 --- a/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py +++ b/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py @@ -3,6 +3,8 @@ import datetime import numpy as np import config +import math +import getpass #check if command line flag --nompl set to disable matplotlib if not(config.nompl): @@ -31,8 +33,24 @@ def constantUpdateActor(self,config): #update global variables #mode to show status in percentage + if self.update < 3: + #use averaging if using faster update rates + Navg=1 + else: + #Don't need averaging in longer acquisition cases + Navg=1 + busy_avg=0 cpu_stats = psutil.cpu_times_percent(interval=0,percpu=False) #syntax seems to be same for psutil versions 1 and 2 - percentcpubusy = 100.0 - cpu_stats.idle + + tmpsum=cpu_stats.system+cpu_stats.user + if sum(self.ui.cpu[0:Navg-2+1]) == 0: + #avoid initial zeros in the array pulling down the average - just use the value measured in this case. + busy_avg=tmpsum + else: + #case to average + busy_avg=(tmpsum+sum(self.ui.cpu[0:Navg-2+1]))/Navg + + percentcpubusy = busy_avg self.ui.progressBarStatusCPU.setValue(round(percentcpubusy)) percentmembusy=psutil.virtual_memory().percent self.ui.progressBarStatusMemory.setValue(round(percentmembusy)) @@ -40,24 +58,13 @@ def constantUpdateActor(self,config): self.ui.Ncpus=Ncpus totalcpustr='CPU Count: '+str(Ncpus) # print "Total CPU str: ",totalcpustr - self.ui.labelCPUCount.setText(totalcpustr) + self.ui.labelCPUCount.setText(totalcpustr+' - CPU Utilization:') totalmem=int(round(float(psutil.virtual_memory().total)/(1024*1024*1024))) #psutil syntax OK for both versions # print "Total Mem: ",totalmem - self.ui.labelMemUsage.setText('Memory Usage: '+str(totalmem*percentmembusy/100)+' GB') self.ui.totalmem=totalmem - totalmemstr='Max Mem: '+str(totalmem)+' GB' + totalmemstr=str(totalmem)+' GB' + self.ui.labelMemUsage.setText('Memory Usage: '+str(totalmem*percentmembusy/100)+' GB of '+totalmemstr) # print "Total Mem str: ",totalmemstr - self.ui.labelMaxMem.setText(totalmemstr) -# print "** config.mplLoaded: ",config.mplLoaded - - if config.mplLoaded: - #update first position with most recent value overwriting oldest value which has been shifted to first position - self.ui.cpu=np.roll(self.ui.cpu,1) - self.ui.cpu[0]=percentcpubusy - self.ui.mem=np.roll(self.ui.mem,1) - self.ui.mem[0]=percentmembusy - # self.ui.dt=np.roll(self.ui.dt,1) - # self.ui.dt[0]=datetime.datetime.now() # update system tab if self.ui.tabWidget.currentIndex() == config.SYST_TAB: @@ -78,13 +85,55 @@ def constantUpdateActor(self,config): uusers=set(lst) Nuusers=len(uusers) self.ui.labelNUsers.setText("Number of Users Logged On: "+str(Nuusers)) - + + #determine "Me" user CPU and memory statistics + Me=getpass.getuser() + cpupctMe=0 + memValMe=0 + cpupctTot=0 + memValTot=0 + for proc in psutil.process_iter(): + try: + #check if process still exists, if so, update dictionaries + cpupct=proc.get_cpu_percent(interval=0) if config.psutilVer == 1 else proc.cpu_percent(interval=0) + memVal=proc.get_memory_percent() if config.psutilVer == 1 else proc.memory_percent() + + try: + #some processes give permission denied when getting the name, if so, fail out gracefully using this try. + if config.psutilVer == 1: + uname=proc.username + else: + uname=proc.username() + #print "proc.username: ",uname," type: ",type(uname)," Me: ",Me," type: ",type(Me) + except: + uname='' + except: + pass #skip process - case where process no longer exists + cpupctTot+=cpupct + memValTot+=memVal + #print "uname: ",uname," Me: ",Me + #note that on Windows systems that getpass.getuser() does not return the same base username as proc.username, so check for the smaller + if Me in uname: + cpupctMe+=cpupct + memValMe+=memVal + #print "cpupctMe: ",cpupctMe," memValMe: ",memValMe + if config.mplLoaded: + #update first position with most recent value overwriting oldest value which has been shifted to first position + self.ui.cpu=np.roll(self.ui.cpu,1) + self.ui.cpu[0]=percentcpubusy #percentcpubusy seems to agree better with system System Monitor than cpupctTot/Ncpus + self.ui.mem=np.roll(self.ui.mem,1) + self.ui.mem[0]=percentmembusy + self.ui.cpuMe=np.roll(self.ui.cpuMe,1) + self.ui.cpuMe[0]=cpupctMe/(Ncpus) + self.ui.memMe=np.roll(self.ui.memMe,1) + self.ui.memMe[0]=memValMe + #update the history plot if self.ui.tabWidget.currentIndex() == config.HIST_TAB: #only update history plot if tab is active font = {'family' : 'sans-serif', 'weight' : 'bold', - 'size' : 10} + 'size' : config.pltFont+1} matplotlib.rc('font', **font) xtime=range(0,self.ui.Nsamples+1,self.update) @@ -93,10 +142,13 @@ def constantUpdateActor(self,config): plt.figure(self.ui.figure.number) #make plot figure active plt.clf() #clear figure each time for rolling updates to show - plt.plot(xtime[0:Npts+1],self.ui.cpu[0:Npts+1],color='Blue',label='CPU Busy') - plt.plot(xtime[0:Npts+1],self.ui.mem[0:Npts+1],color='Green',label='Mem Busy') - plt.title('Composite CPU and Memory Activity',fontsize=10,fontweight='bold') - plt.ylabel('% Busy',fontsize=9.5,fontweight='bold') + plt.plot(xtime[0:Npts+1],self.ui.cpu[0:Npts+1],color='Blue',label='CPU: All',linewidth=config.linewidth) + plt.plot(xtime[0:Npts+1],self.ui.mem[0:Npts+1],color='Green',label='Mem: All',linewidth=config.linewidth) + plt.plot(xtime[0:Npts+1],self.ui.cpuMe[0:Npts+1],color='red',label='CPU: '+Me,linewidth=config.linewidth) + plt.plot(xtime[0:Npts+1],self.ui.memMe[0:Npts+1],color='cyan',label='Mem: '+Me,linewidth=config.linewidth) + + plt.title('Composite CPU and Memory Activity',fontsize=config.pltFont+1,fontweight='bold') + plt.ylabel('% Used',fontsize=config.pltFont+0.5,fontweight='bold') if self.update == 1: xlab="Seconds with 1 Second Updates" @@ -106,8 +158,9 @@ def constantUpdateActor(self,config): xlab="Seconds with 5 Second Updates" elif self.update == 10: xlab="Seconds with 10 Second Updates" - plt.xlabel(xlab,fontsize=9.5,fontweight='bold') - plt.legend(loc="upper right",prop={'size':9}) + plt.xlabel(xlab,fontsize=config.pltFont+0.5,fontweight='bold') + plt.legend(loc="upper right",prop={'size':config.pltFont}) + plt.xlim([0,Ndur]) self.ui.canvas.draw() @@ -159,17 +212,21 @@ def updateProcTable(self,config): #fill the dictionaries - seems to need to be done faster than within loop which also fills the table...not sure why... for proc in psutil.process_iter(): - cpupct=proc.get_cpu_percent(interval=0) if config.psutilVer == 1 else proc.cpu_percent(interval=0) - memVal=float(int(float(proc.get_memory_percent())*100.0))/100.0 if config.psutilVer == 1 else float(int(float(proc.memory_percent())*100.0))/100.0 try: - #don't update dictionaries if name gives an access denied error when checking process name - pname=proc.name if config.psutilVer == 1 else proc.name() - d_user.update({proc.pid:proc.username}) if config.psutilVer == 1 else d_user.update({proc.pid:proc.username()}) - d_cpu.update({proc.pid:cpupct}) - d_mem.update({proc.pid:memVal}) - d_name.update({proc.pid:pname}) + #check if process still exists, if so, update dictionaries + cpupct=proc.get_cpu_percent(interval=0) if config.psutilVer == 1 else proc.cpu_percent(interval=0) + memVal=float(int(float(proc.get_memory_percent())*100.0))/100.0 if config.psutilVer == 1 else float(int(float(proc.memory_percent())*100.0))/100.0 + try: + #don't update dictionaries if name gives an access denied error when checking process name + pname=proc.name if config.psutilVer == 1 else proc.name() + d_user.update({proc.pid:proc.username}) if config.psutilVer == 1 else d_user.update({proc.pid:proc.username()}) + d_cpu.update({proc.pid:cpupct}) + d_mem.update({proc.pid:memVal}) + d_name.update({proc.pid:pname}) + except: + pass #place holder except: - pass #place holder + pass #skip this process - case where it no longer exists #now fill the table for display for proc in d_user.keys(): @@ -207,10 +264,10 @@ def updateProcTable(self,config): self.ui.labelLastUpdate.setText("Last Update: "+str(datetime.datetime.now())) def updateUserChart(self,config): - + font = {'family' : 'sans-serif', 'weight' : 'bold', - 'size' : 9} + 'size' : config.pltFont} matplotlib.rc('font', **font) @@ -220,7 +277,7 @@ def updateUserChart(self,config): plt.clf() plt.cla() # f.gca().cla() - + plt.subplot(121) #divide plot area into two: plot on left and legend on right #create empty dictionaries to be used by the process table d_user={} d_cpu={} @@ -228,18 +285,24 @@ def updateUserChart(self,config): d_name={} #fill the dictionaries - seems to need to be done faster than within loop which also fills the table...not sure why... for proc in psutil.process_iter(): - cpupct=proc.get_cpu_percent(interval=0) if config.psutilVer == 1 else proc.cpu_percent(interval=0) - memVal=float(int(float(proc.get_memory_percent())*100.0))/100.0 if config.psutilVer == 1 else float(int(float(proc.memory_percent())*100.0))/100.0 try: - #don't update dictionaries if name gives an access denied error when checking process name - pname=proc.name if config.psutilVer == 1 else proc.name() - d_user.update({proc.pid:proc.username}) if config.psutilVer == 1 else d_user.update({proc.pid:proc.username()}) - d_cpu.update({proc.pid:cpupct}) - d_mem.update({proc.pid:memVal}) - d_name.update({proc.pid:pname}) + #check if process still exists, if so, update dictionaries + cpupct=proc.get_cpu_percent(interval=0) if config.psutilVer == 1 else proc.cpu_percent(interval=0) + memVal=float(int(float(proc.get_memory_percent())*100.0))/100.0 if config.psutilVer == 1 else float(int(float(proc.memory_percent())*100.0))/100.0 + try: + #don't update dictionaries if name gives an access denied error when checking process name + pname=proc.name if config.psutilVer == 1 else proc.name() + d_user.update({proc.pid:proc.username}) if config.psutilVer == 1 else d_user.update({proc.pid:proc.username()}) + d_cpu.update({proc.pid:cpupct}) + d_mem.update({proc.pid:memVal}) + d_name.update({proc.pid:pname}) + except: + #print "access denied" + pass #place holder except: - pass #place holder - + #print "skipped process" + pass #skip this process as it no longer exists + #print "** Total Mem Used: ",sum(d_mem.values()) users=d_user.values() users_unique=list(set(users)) #use set() to find unique users then convert the resulting set to a list via list() Nusers=len(users_unique) @@ -274,6 +337,8 @@ def updateUserChart(self,config): sortBy='cpu' elif self.ui.radioButtonMem.isChecked(): sortBy='mem' + elif self.ui.radioButtonMax.isChecked(): + sortBy='max' else: print "invalid radio button selection - using CPU sort as default" sortBy='cpu' @@ -283,6 +348,14 @@ def updateUserChart(self,config): indx=sorted(range(len(cpu_by_users_lst)), key=cpu_by_users_lst.__getitem__,reverse=True) elif sortBy=='mem': indx=sorted(range(len(mem_by_users_lst)), key=mem_by_users_lst.__getitem__,reverse=True) + elif sortBy=='max': + #determine if cpu or mem is larger + if sum(cpu_by_users_lst) > sum(mem_by_users_lst): + #case where cpu usage is larger value + indx=sorted(range(len(cpu_by_users_lst)), key=cpu_by_users_lst.__getitem__,reverse=True) + else: + #case where mem usage is larger + indx=sorted(range(len(mem_by_users_lst)), key=mem_by_users_lst.__getitem__,reverse=True) else: print 'Incorrect sort parameter' #sort lists @@ -294,90 +367,120 @@ def updateUserChart(self,config): if Nusers > Nmax: #replace the Nmaxth - 1 element with the total of the values from index Nmax - 1 to the end of the list cpu_by_users_sorted[Nmax-1]=sum(cpu_by_users_sorted[Nmax-1:]) - mem_remaining=sum(mem_by_users_sorted[Nmax-1:]) + mem_by_users_sorted[Nmax-1]=sum(mem_by_users_sorted[Nmax-1:]) users_unique_sorted[Nmax-1]='Remaining' Nshow=Nmax else: Nshow=Nusers if min(cpu_by_users_sorted) < 0: - print " *** cp_by_users_sorted has values less than zero" + print " *** cpu_by_users_sorted has values less than zero - should not occur, please check" print cpu_by_users_sorted print " ***" if min(mem_by_users_sorted) < 0: - print " *** mem_by_users_sorted has values less than zero" + print " *** mem_by_users_sorted has values less than zero - should not occur, please check" print mem_by_users_sorted print " ***" #range check the values of the sorted lists - may not be necessary, just being cautious... tst=np.array(cpu_by_users_sorted)<0 #need an array for summing - indx=cpu_by_users_sorted<0 #need bool list for indexing + indx=list(np.array(cpu_by_users_sorted)<0) #need bool list for indexing + #check if any users have less than zero CPU usage and set usage to 0 for these users if sum(tst) > 0: print "cpu_by_users < 0: ",sum(indx) - cpu_by_users_sorted[indx]=0 - tst=np.array(cpu_by_users_sorted)>self.ui.Ncpus*100 - indx=cpu_by_users_sorted>self.ui.Ncpus*100 + cpu_by_users_sorted=[0 if x<0 else x for x in cpu_by_users_sorted] + tst=np.array(cpu_by_users_sorted)>(self.ui.Ncpus*100) + indx=list(np.array(cpu_by_users_sorted)>self.ui.Ncpus*100) + #check if any users have CPU usage greater than possible number of CPUs and set usage to max CPU usage for those users if sum(tst) > 0: print "cpu_by_users > Ncpus*100: ",sum(indx) - cpu_by_users_sorted[indx]=self.ui.Ncpus*100 + cpu_by_users_sorted=[self.ui.Ncpus*100 if x>self.ui.Ncpus*100 else x for x in cpu_by_users_sorted] tst=np.array(mem_by_users_sorted)<0 - indx=mem_by_users_sorted<0 + indx=list(np.array(mem_by_users_sorted)<0) + #check if any users have less than zero memory usage and set these users to zero usage if sum(tst) > 0: print "mem_by_users < 0: ",sum(indx) - mem_by_users_sorted[indx]=0 + mem_by_users_sorted=[0 if x<0 else x for x in mem_by_users_sorted] tst=np.array(mem_by_users_sorted)>self.ui.totalmem - indx=mem_by_users_sorted>self.ui.totalmem + indx=np.array(mem_by_users_sorted)>self.ui.totalmem + #check if any users have memory usage greater than the total system memory - should never happen... if sum(tst) > 0: - print "mem_by_users > totalmem: ",sum(indx) - mem_by_users_sorted[indx]=self.ui.totalmem + #if true, then need to adjust maximum usage for these users to the total memory possible + #print "mem_by_users > totalmem: ",sum(indx)," indx: ",indx," mem_by_users: ",mem_by_users_sorted + mem_by_users_sorted=[self.ui.totalmem if x>self.ui.totalmem else x for x in mem_by_users_sorted] p=[] #list to contain plot objects for use by the legend ind=np.arange(2) - - + #print "**************" + #print mem_by_users_sorted[0:Nshow] for u in range(Nshow): if u == 0: p.append(plt.bar(ind,(cpu_by_users_sorted[u],mem_by_users_sorted[u]),width,bottom=(0,0),color=colors[u])) else: p.append(plt.bar(ind,(cpu_by_users_sorted[u],mem_by_users_sorted[u]),width,bottom=(sum(cpu_by_users_sorted[0:u]),sum(mem_by_users_sorted[0:u])),color=colors[u])) - plt.title('CPU and Memory Usage by User',fontsize=10,fontweight='bold') + plt.title('Usage by User',fontsize=config.pltFont+1,fontweight='bold') #remove default yaxis ticks then redraw them via ax1 and ax2 below frame=plt.gca() frame.axes.get_yaxis().set_ticks([]) - plt.xticks(np.arange(2)+width/2.,('CPU','Mem'),fontsize=9,fontweight='bold') - ymaxCPU=round(int((sum(cpu_by_users_sorted[0:Nshow])+100)/100)*100) - ymaxMEM=round(int((sum(mem_by_users_sorted[0:Nshow])+100)/100)*100) - ymax=max([ymaxCPU,ymaxMEM,100]) -# plt.ylim([0,ymax]) + plt.xticks(np.arange(2)+width/2.,('CPU','Mem'),fontsize=config.pltFont,fontweight='bold') + ymaxCPU=int((sum(cpu_by_users_sorted)+100)/100)*100 #range ymaxCPU to nearest 100% + ymaxMEM=int(round(sum(mem_by_users_sorted)+10))/10*10 #range ymaxMEM to nearest 10% + + ymaxMAX=max([ymaxCPU,ymaxMEM,100]) + + if sortBy == 'cpu': + ymax=max([ymaxCPU,10]) + auto=False + elif sortBy == 'mem': + ymax=max([ymaxMEM,10]) + auto=False + elif sortBy == 'max': + ymax=max([ymaxMAX,10]) + auto=True +# print 'ymaxCPU: ',ymaxCPU,' ymaxMEM: ',ymaxMEM,' ymaxMAX: ',ymaxMAX,' ymax: ',ymax,' sum(mem_by_users_sorted): ',sum(mem_by_users_sorted) + plt.ylim(0,ymax,auto=auto) + + #compute composite % - ylab=np.arange(6)/5.0*float(ymax)/float(self.ui.Ncpus) - ylab=ylab*10 + sumCPU=sum(cpu_by_users_sorted) + ylab=np.arange(5)/4.0*float(sumCPU)/float(self.ui.Ncpus) + scl=float(ymax)/float(sumCPU) + ylab=ylab*100*scl tmp=ylab.astype('int') tmp1=tmp.astype('float') - tmp1=tmp1/10 + tmp1=tmp1/100 ylab1=tmp1 ax1=plt.twinx() - ax1.set_ylabel('Composite CPU Percent',fontsize=9,fontweight='bold') + ax1.set_ylabel('Composite CPU Percent',fontsize=config.pltFont,fontweight='bold') ax1.yaxis.set_ticks_position('left') ax1.yaxis.set_label_position('left') + ax1.set_ybound(lower=0,upper=max(ylab1)) ax1.set_yticks(ylab1) +# print 'ylab1: ',ylab1 + + #place warnings if MEM or CPU go out of range + if ymax < ymaxCPU: + plt.text(2.7,0.0,'CPU Above Axis',color='red') + if ymax < ymaxMEM: + plt.text(2.7,0.0,'MEM Above Axis',color='green') + usersLegend=users_unique_sorted[0:Nshow] #reverse legend print order to have legend correspond with the order data are placed in the bar chart usersLegend.reverse() p.reverse() - plt.legend(p,usersLegend) - - + #place legend outside of plot to the right + plt.legend(p,usersLegend,bbox_to_anchor=(1.45, 1.1), loc="upper left", borderaxespad=0.1,fontsize=config.pltFont-0.5,title='Users') + #place second y axis label on plot ylab2=np.arange(5)/4.0*float(ymax) ax2=plt.twinx() - ax2.set_ylabel('Percent',fontsize=9,fontweight='bold') + ax2.set_ylabel('Percent',fontsize=config.pltFont,fontweight='bold',position=(0.9,0.5)) ax2.set_yticks(ylab2) #ax2.set_yticks(ylab2) ax2.yaxis.set_ticks_position('right') diff --git a/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py index cb543a389d72..93cfffe0752b 100644 --- a/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py +++ b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- -# Form implementation generated from reading ui file '../../Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui' +# Form implementation generated from reading ui file 'ui_sysmon.ui' # -# Created: Fri Sep 19 12:44:16 2014 -# by: PyQt4 UI code generator 4.10.4 +# Created: Wed Sep 24 16:19:13 2014 +# by: PyQt4 UI code generator 4.8.3 # # WARNING! All changes made in this file will be lost! @@ -12,21 +12,13 @@ try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: - def _fromUtf8(s): - return s - -try: - _encoding = QtGui.QApplication.UnicodeUTF8 - def _translate(context, text, disambig): - return QtGui.QApplication.translate(context, text, disambig, _encoding) -except AttributeError: - def _translate(context, text, disambig): - return QtGui.QApplication.translate(context, text, disambig) + _fromUtf8 = lambda s: s class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(230, 331) + Form.setMinimumSize(QtCore.QSize(230, 331)) Form.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.horizontalLayout = QtGui.QHBoxLayout(Form) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) @@ -45,7 +37,7 @@ def setupUi(self, Form): self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(_fromUtf8("scrollArea")) self.scrollAreaWidgetContents = QtGui.QWidget() - self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 320, 293)) + self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 186, 267)) self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents")) self.verticalLayout_2 = QtGui.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) @@ -115,49 +107,44 @@ def setupUi(self, Form): self.groupBox_5.setSizePolicy(sizePolicy) self.groupBox_5.setMinimumSize(QtCore.QSize(0, 0)) font = QtGui.QFont() - font.setBold(False) - font.setUnderline(False) font.setWeight(50) + font.setUnderline(False) + font.setBold(False) self.groupBox_5.setFont(font) self.groupBox_5.setObjectName(_fromUtf8("groupBox_5")) - self.gridLayout_6 = QtGui.QGridLayout(self.groupBox_5) - self.gridLayout_6.setObjectName(_fromUtf8("gridLayout_6")) + self.verticalLayout_7 = QtGui.QVBoxLayout(self.groupBox_5) + self.verticalLayout_7.setObjectName(_fromUtf8("verticalLayout_7")) self.labelMemUsage = QtGui.QLabel(self.groupBox_5) font = QtGui.QFont() font.setUnderline(False) self.labelMemUsage.setFont(font) self.labelMemUsage.setObjectName(_fromUtf8("labelMemUsage")) - self.gridLayout_6.addWidget(self.labelMemUsage, 0, 0, 1, 1) + self.verticalLayout_7.addWidget(self.labelMemUsage) + self.progressBarStatusMemory = QtGui.QProgressBar(self.groupBox_5) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.progressBarStatusMemory.sizePolicy().hasHeightForWidth()) + self.progressBarStatusMemory.setSizePolicy(sizePolicy) + self.progressBarStatusMemory.setMaximumSize(QtCore.QSize(210, 16777215)) + self.progressBarStatusMemory.setToolTip(_fromUtf8("")) + self.progressBarStatusMemory.setObjectName(_fromUtf8("progressBarStatusMemory")) + self.verticalLayout_7.addWidget(self.progressBarStatusMemory) self.labelCPUCount = QtGui.QLabel(self.groupBox_5) self.labelCPUCount.setObjectName(_fromUtf8("labelCPUCount")) - self.gridLayout_6.addWidget(self.labelCPUCount, 3, 0, 1, 1) - self.labelMaxMem = QtGui.QLabel(self.groupBox_5) - self.labelMaxMem.setObjectName(_fromUtf8("labelMaxMem")) - self.gridLayout_6.addWidget(self.labelMaxMem, 1, 0, 1, 1) - self.label_102 = QtGui.QLabel(self.groupBox_5) - font = QtGui.QFont() - font.setUnderline(False) - self.label_102.setFont(font) - self.label_102.setObjectName(_fromUtf8("label_102")) - self.gridLayout_6.addWidget(self.label_102, 2, 0, 1, 1) + self.verticalLayout_7.addWidget(self.labelCPUCount) self.progressBarStatusCPU = QtGui.QProgressBar(self.groupBox_5) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) + sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBarStatusCPU.sizePolicy().hasHeightForWidth()) self.progressBarStatusCPU.setSizePolicy(sizePolicy) - self.progressBarStatusCPU.setProperty("value", 24) + self.progressBarStatusCPU.setMaximumSize(QtCore.QSize(210, 16777215)) + self.progressBarStatusCPU.setToolTip(_fromUtf8("")) + self.progressBarStatusCPU.setStatusTip(_fromUtf8("")) + self.progressBarStatusCPU.setProperty(_fromUtf8("value"), 24) self.progressBarStatusCPU.setObjectName(_fromUtf8("progressBarStatusCPU")) - self.gridLayout_6.addWidget(self.progressBarStatusCPU, 2, 1, 2, 1) - self.progressBarStatusMemory = QtGui.QProgressBar(self.groupBox_5) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.progressBarStatusMemory.sizePolicy().hasHeightForWidth()) - self.progressBarStatusMemory.setSizePolicy(sizePolicy) - self.progressBarStatusMemory.setProperty("value", 24) - self.progressBarStatusMemory.setObjectName(_fromUtf8("progressBarStatusMemory")) - self.gridLayout_6.addWidget(self.progressBarStatusMemory, 0, 1, 2, 1) + self.verticalLayout_7.addWidget(self.progressBarStatusCPU) self.gridLayout_4.addWidget(self.groupBox_5, 1, 0, 1, 1) self.verticalLayout_2.addWidget(self.groupBox_3) self.scrollArea.setWidget(self.scrollAreaWidgetContents) @@ -196,6 +183,8 @@ def setupUi(self, Form): self.tableWidgetProcess.setRowCount(10) self.tableWidgetProcess.setColumnCount(5) self.tableWidgetProcess.setObjectName(_fromUtf8("tableWidgetProcess")) + self.tableWidgetProcess.setColumnCount(5) + self.tableWidgetProcess.setRowCount(10) item = QtGui.QTableWidgetItem() self.tableWidgetProcess.setHorizontalHeaderItem(0, item) item = QtGui.QTableWidgetItem() @@ -252,9 +241,13 @@ def setupUi(self, Form): sizePolicy.setHeightForWidth(self.radioButtonMem.sizePolicy().hasHeightForWidth()) self.radioButtonMem.setSizePolicy(sizePolicy) self.radioButtonMem.setMinimumSize(QtCore.QSize(0, 0)) - self.radioButtonMem.setChecked(True) + self.radioButtonMem.setChecked(False) self.radioButtonMem.setObjectName(_fromUtf8("radioButtonMem")) self.horizontalLayout_6.addWidget(self.radioButtonMem) + self.radioButtonMax = QtGui.QRadioButton(self.groupBox) + self.radioButtonMax.setChecked(True) + self.radioButtonMax.setObjectName(_fromUtf8("radioButtonMax")) + self.horizontalLayout_6.addWidget(self.radioButtonMax) self.verticalLayout_6.addWidget(self.groupBox) self.frameBar = QtGui.QFrame(self.tab_5) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Expanding) @@ -275,7 +268,7 @@ def setupUi(self, Form): self.scrollArea_2.setWidgetResizable(True) self.scrollArea_2.setObjectName(_fromUtf8("scrollArea_2")) self.scrollAreaWidgetContents_2 = QtGui.QWidget() - self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 303, 244)) + self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 232, 250)) self.scrollAreaWidgetContents_2.setObjectName(_fromUtf8("scrollAreaWidgetContents_2")) self.horizontalLayout_5 = QtGui.QHBoxLayout(self.scrollAreaWidgetContents_2) self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5")) @@ -331,47 +324,41 @@ def setupUi(self, Form): QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): - Form.setWindowTitle(_translate("Form", "Form", None)) - self.groupBox_3.setTitle(_translate("Form", "System Info", None)) - self.labelComputerName.setText(_translate("Form", "Computer Name: ", None)) - self.labelOS.setText(_translate("Form", "Operating System:", None)) - self.labelProcFam.setText(_translate("Form", "Processor Family:", None)) - self.labelNUsers.setText(_translate("Form", "Number of Users Logged On:", None)) - self.labelUptime.setText(_translate("Form", "System Uptime: ", None)) - self.groupBox_5.setTitle(_translate("Form", "Composite System Status", None)) - self.labelMemUsage.setText(_translate("Form", "Memory Usage", None)) - self.labelCPUCount.setText(_translate("Form", "CPU count:", None)) - self.labelMaxMem.setText(_translate("Form", "Max Mem:", None)) - self.label_102.setText(_translate("Form", "Composite CPU Usage", None)) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("Form", "System", None)) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("Form", "History", None)) - self.labelLastUpdate.setText(_translate("Form", "Last Update: ", None)) + Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8)) + self.groupBox_3.setTitle(QtGui.QApplication.translate("Form", "System Info", None, QtGui.QApplication.UnicodeUTF8)) + self.labelComputerName.setText(QtGui.QApplication.translate("Form", "Computer Name: ", None, QtGui.QApplication.UnicodeUTF8)) + self.labelOS.setText(QtGui.QApplication.translate("Form", "Operating System:", None, QtGui.QApplication.UnicodeUTF8)) + self.labelProcFam.setText(QtGui.QApplication.translate("Form", "Processor Family:", None, QtGui.QApplication.UnicodeUTF8)) + self.labelNUsers.setText(QtGui.QApplication.translate("Form", "Number of Users Logged On:", None, QtGui.QApplication.UnicodeUTF8)) + self.labelUptime.setText(QtGui.QApplication.translate("Form", "System Uptime: ", None, QtGui.QApplication.UnicodeUTF8)) + self.groupBox_5.setTitle(QtGui.QApplication.translate("Form", "Composite System Status", None, QtGui.QApplication.UnicodeUTF8)) + self.labelMemUsage.setText(QtGui.QApplication.translate("Form", "Memory Usage", None, QtGui.QApplication.UnicodeUTF8)) + self.labelCPUCount.setText(QtGui.QApplication.translate("Form", "CPU count:", None, QtGui.QApplication.UnicodeUTF8)) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtGui.QApplication.translate("Form", "System", None, QtGui.QApplication.UnicodeUTF8)) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), QtGui.QApplication.translate("Form", "History", None, QtGui.QApplication.UnicodeUTF8)) + self.labelLastUpdate.setText(QtGui.QApplication.translate("Form", "Last Update: ", None, QtGui.QApplication.UnicodeUTF8)) self.tableWidgetProcess.setSortingEnabled(True) - item = self.tableWidgetProcess.horizontalHeaderItem(0) - item.setText(_translate("Form", "PID", None)) - item = self.tableWidgetProcess.horizontalHeaderItem(1) - item.setText(_translate("Form", "USER", None)) - item = self.tableWidgetProcess.horizontalHeaderItem(2) - item.setText(_translate("Form", "CPU%", None)) - item = self.tableWidgetProcess.horizontalHeaderItem(3) - item.setText(_translate("Form", "MEM%", None)) - item = self.tableWidgetProcess.horizontalHeaderItem(4) - item.setText(_translate("Form", "NAME", None)) - self.pushButtonUpdate.setText(_translate("Form", "Hold Updates", None)) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("Form", "Processes", None)) - self.groupBox.setTitle(_translate("Form", "Sort", None)) - self.radioButtonCPU.setText(_translate("Form", "CPU", None)) - self.radioButtonMem.setText(_translate("Form", "Memory", None)) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_5), _translate("Form", "Users", None)) - self.groupBox_6.setTitle(_translate("Form", "Display Period", None)) - self.radioButton60Secs.setText(_translate("Form", "60 Seconds", None)) - self.radioButton300Secs.setText(_translate("Form", "300 Seconds", None)) - self.radioButton600Secs.setText(_translate("Form", "600 Seconds", None)) - self.radioButton3600Secs.setText(_translate("Form", "3600 Seconds", None)) - self.groupBox_4.setTitle(_translate("Form", "Update Rate", None)) - self.radioButton1Sec.setText(_translate("Form", "1 Second", None)) - self.radioButton2Secs.setText(_translate("Form", "2 Seconds", None)) - self.radioButton5Secs.setText(_translate("Form", "5 Seconds", None)) - self.radioButton10Secs.setText(_translate("Form", "10 Seconds", None)) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), _translate("Form", "Options", None)) + self.tableWidgetProcess.horizontalHeaderItem(0).setText(QtGui.QApplication.translate("Form", "PID", None, QtGui.QApplication.UnicodeUTF8)) + self.tableWidgetProcess.horizontalHeaderItem(1).setText(QtGui.QApplication.translate("Form", "USER", None, QtGui.QApplication.UnicodeUTF8)) + self.tableWidgetProcess.horizontalHeaderItem(2).setText(QtGui.QApplication.translate("Form", "CPU%", None, QtGui.QApplication.UnicodeUTF8)) + self.tableWidgetProcess.horizontalHeaderItem(3).setText(QtGui.QApplication.translate("Form", "MEM%", None, QtGui.QApplication.UnicodeUTF8)) + self.tableWidgetProcess.horizontalHeaderItem(4).setText(QtGui.QApplication.translate("Form", "NAME", None, QtGui.QApplication.UnicodeUTF8)) + self.pushButtonUpdate.setText(QtGui.QApplication.translate("Form", "Hold Updates", None, QtGui.QApplication.UnicodeUTF8)) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), QtGui.QApplication.translate("Form", "Processes", None, QtGui.QApplication.UnicodeUTF8)) + self.groupBox.setTitle(QtGui.QApplication.translate("Form", "Sort", None, QtGui.QApplication.UnicodeUTF8)) + self.radioButtonCPU.setText(QtGui.QApplication.translate("Form", "CPU", None, QtGui.QApplication.UnicodeUTF8)) + self.radioButtonMem.setText(QtGui.QApplication.translate("Form", "Memory", None, QtGui.QApplication.UnicodeUTF8)) + self.radioButtonMax.setText(QtGui.QApplication.translate("Form", "Max", None, QtGui.QApplication.UnicodeUTF8)) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_5), QtGui.QApplication.translate("Form", "Users", None, QtGui.QApplication.UnicodeUTF8)) + self.groupBox_6.setTitle(QtGui.QApplication.translate("Form", "Display Period", None, QtGui.QApplication.UnicodeUTF8)) + self.radioButton60Secs.setText(QtGui.QApplication.translate("Form", "60 Seconds", None, QtGui.QApplication.UnicodeUTF8)) + self.radioButton300Secs.setText(QtGui.QApplication.translate("Form", "300 Seconds", None, QtGui.QApplication.UnicodeUTF8)) + self.radioButton600Secs.setText(QtGui.QApplication.translate("Form", "600 Seconds", None, QtGui.QApplication.UnicodeUTF8)) + self.radioButton3600Secs.setText(QtGui.QApplication.translate("Form", "3600 Seconds", None, QtGui.QApplication.UnicodeUTF8)) + self.groupBox_4.setTitle(QtGui.QApplication.translate("Form", "Update Rate", None, QtGui.QApplication.UnicodeUTF8)) + self.radioButton1Sec.setText(QtGui.QApplication.translate("Form", "1 Second", None, QtGui.QApplication.UnicodeUTF8)) + self.radioButton2Secs.setText(QtGui.QApplication.translate("Form", "2 Seconds", None, QtGui.QApplication.UnicodeUTF8)) + self.radioButton5Secs.setText(QtGui.QApplication.translate("Form", "5 Seconds", None, QtGui.QApplication.UnicodeUTF8)) + self.radioButton10Secs.setText(QtGui.QApplication.translate("Form", "10 Seconds", None, QtGui.QApplication.UnicodeUTF8)) + self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), QtGui.QApplication.translate("Form", "Options", None, QtGui.QApplication.UnicodeUTF8)) diff --git a/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui index 2dfbc897f680..a793bcc76f91 100644 --- a/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui +++ b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui @@ -10,6 +10,12 @@ 331 + + + 230 + 331 + + 16777215 @@ -36,7 +42,7 @@ System - + true @@ -46,8 +52,8 @@ 0 0 - 320 - 293 + 186 + 267 @@ -168,7 +174,7 @@ - + @@ -192,8 +198,8 @@ Composite System Status - - + + @@ -205,52 +211,51 @@ - - - - CPU count: + + + + + 0 + 0 + - - - - - - Max Mem: + + + 210 + 16777215 + + + + - - - - - false - - + + - Composite CPU Usage + CPU count: - + - + 0 0 - - 24 + + + 210 + 16777215 + - - - - - - - 0 - 0 - + + + + + 24 @@ -491,6 +496,16 @@ Memory + + false + + + + + + + Max + true @@ -532,8 +547,8 @@ 0 0 - 303 - 244 + 232 + 250 From 5742e0719639d0f473b6092c39e00a6137162f5d Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Thu, 4 Dec 2014 20:14:09 +0000 Subject: [PATCH 007/414] Fix bad merge conflict resolution Refs #9843 --- Code/Mantid/MantidPlot/CMakeLists.txt | 6 ------ 1 file changed, 6 deletions(-) diff --git a/Code/Mantid/MantidPlot/CMakeLists.txt b/Code/Mantid/MantidPlot/CMakeLists.txt index 652202eec165..6313cc0253a8 100644 --- a/Code/Mantid/MantidPlot/CMakeLists.txt +++ b/Code/Mantid/MantidPlot/CMakeLists.txt @@ -960,16 +960,10 @@ set ( MANTIDPLOT_TEST_PY_FILES MantidPlot2DPlotTest.py MantidPlotProxiesTest.py MantidPlotPythonImportTest.py -<<<<<<< HEAD - MantidPlotFoldersTest.py - MantidPlotMdiSubWindowTest.py - MantidPlotTiledWindowTest.py -======= MantidPlotFoldersTest.py MantidPlotMdiSubWindowTest.py MantidPlotTiledWindowTest.py MantidPlotInputArgsCheck.py ->>>>>>> master ) if ( 0 ) From bc3246d52b2f4e81210c02b73652d420aef061a9 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Wed, 10 Dec 2014 17:31:59 +0000 Subject: [PATCH 008/414] Update SysMon to v0.26 Refs #9843 --- Code/Mantid/MantidPlot/CMakeLists.txt | 1 + Code/Mantid/MantidPlot/SysMon/SysMon.pyw | 10 ++- Code/Mantid/MantidPlot/SysMon/_version.py | 4 + Code/Mantid/MantidPlot/SysMon/sysmon.py | 24 +++++- Code/Mantid/MantidPlot/SysMon/sysmon_tools.py | 82 +++++++++++-------- Code/Mantid/MantidPlot/SysMon/ui_sysmon.py | 32 +++++++- Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui | 54 +++++++++++- 7 files changed, 166 insertions(+), 41 deletions(-) create mode 100644 Code/Mantid/MantidPlot/SysMon/_version.py diff --git a/Code/Mantid/MantidPlot/CMakeLists.txt b/Code/Mantid/MantidPlot/CMakeLists.txt index 620a008c2a18..b10593f4c885 100644 --- a/Code/Mantid/MantidPlot/CMakeLists.txt +++ b/Code/Mantid/MantidPlot/CMakeLists.txt @@ -882,6 +882,7 @@ copy_files_to_dir ( "${IPY_FILES}" # SysMon scripts set( SYSMON_FILES __init__.py + _version.py config.py sysmon.py sysmon_tools.py diff --git a/Code/Mantid/MantidPlot/SysMon/SysMon.pyw b/Code/Mantid/MantidPlot/SysMon/SysMon.pyw index 4fd044de0cbe..638813a2990d 100755 --- a/Code/Mantid/MantidPlot/SysMon/SysMon.pyw +++ b/Code/Mantid/MantidPlot/SysMon/SysMon.pyw @@ -11,6 +11,14 @@ provided to the application. import config import sys +__version__="unknown" +try: + from _version import __version__ +except ImportError: + #_version.py file not found - version not known in this case so use + #the default previously given. + pass + #parse args - doing it here as config structure needs to be filled prior to importing sysmon if ['--nompl'] == [s for s in sys.argv if '--nompl' in s]: #case to not use matplotlib @@ -72,7 +80,7 @@ class SysMonMainWindow(QtGui.QMainWindow): def About(self): dialog=QtGui.QMessageBox(self) - dialog.setText("PyQt4 System Monitoring Application V0.02") + dialog.setText("PyQt4 System Monitoring Application "+__version__) info='Application Info: \n\r * Changing the Update Rate Clears plots \n\r * It may take one full new update cycle for changes to take effect \n\r * Update rate shown in History plot xaxis label \n\r * Process tab CPU percentage can be greater than 100 when more than a single core is involved' dialog.setDetailedText(info) #give full info in detailed text dialog.exec_() diff --git a/Code/Mantid/MantidPlot/SysMon/_version.py b/Code/Mantid/MantidPlot/SysMon/_version.py new file mode 100644 index 000000000000..bad294c0f517 --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/_version.py @@ -0,0 +1,4 @@ +#File to identify the current version of the software +#Note that this file must be manually updated to contain the same +#version number as the git tag for the check-in. +__version__="v0.26" \ No newline at end of file diff --git a/Code/Mantid/MantidPlot/SysMon/sysmon.py b/Code/Mantid/MantidPlot/SysMon/sysmon.py index d62254f7cff0..967442b50c65 100644 --- a/Code/Mantid/MantidPlot/SysMon/sysmon.py +++ b/Code/Mantid/MantidPlot/SysMon/sysmon.py @@ -3,7 +3,14 @@ import sys, os, time import re import config #application constants and variables +#suppress deprecation warnings that can occur when importing psutil version 2 +#note - all deprecation warnings will probably be suppressed using this filterwarnings +#as specifying the psutil module specifically in filterwarnings did not suppress +#these warnings +import warnings +warnings.filterwarnings('ignore',category=DeprecationWarning) import psutil + #check psutil version as command syntax changes between version 1 and version 2 ver=psutil.__version__ verChk1=re.match('1.[0-9].[0-9]',ver) #latest psutil version 1 is 1.2.1 - using positional numeric wildcards to check sub versions @@ -26,6 +33,15 @@ except AttributeError: _fromUtf8 = lambda s: s +#import application version information +__version__="unknown" +try: + from _version import __version__ +except ImportError: + #_version.py file not found - version not known in this case so use + #the default previously given. + pass + class SysMon(QtGui.QWidget): def __init__(self, parent=None): @@ -102,7 +118,9 @@ def __init__(self, parent=None): #create drawing canvas # a figure instance to plot on - matplotlib.rc_context({'toolbar':False}) + if not re.match('1.[0-1]',matplotlib.__version__): + #if not an old version of matplotlib, then use the following command + matplotlib.rc_context({'toolbar':False}) #initialize figure 1 and its canvas for cpu and memory history plots self.ui.figure = plt.figure(1) # the Canvas Widget displays the `figure` @@ -142,6 +160,9 @@ def __init__(self, parent=None): #upon initialization completion, set System tab (first tab on left) as the visible tab self.ui.tabWidget.setCurrentIndex(config.SYST_TAB) + + #initialize version label + self.ui.labelVersion.setText("Version: "+__version__) def constantUpdate(self): #redirct to global function @@ -211,7 +232,6 @@ def updateProcesses(self): self.ui.pushButtonUpdate.setText('Hold Updates') def resizeEvent(self,resizeEvent): - print "resizing" sz=self.ui.tableWidgetProcess.size() w=sz.width() wmin=self.ui.parent.minimumSize().width() #establish minimum table size based upon parent widget minimum size diff --git a/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py b/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py index 0fe4e1f87ad7..6c2e0f6dfaca 100644 --- a/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py +++ b/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py @@ -1,10 +1,18 @@ +#suppress deprecation warnings that can occur when importing psutil version 2 +#note - all deprecation warnings will probably be suppressed using this filterwarnings +#as specifying the psutil module specifically in filterwarnings did not suppress +#these warnings +import warnings +warnings.filterwarnings('ignore',category=DeprecationWarning) import psutil + from PyQt4 import Qt, QtCore, QtGui import datetime import numpy as np import config import math import getpass +import re #check if command line flag --nompl set to disable matplotlib if not(config.nompl): @@ -27,31 +35,14 @@ def constantUpdateActor(self,config): - #check duration + #set duration number Ndur=self.duration - #update global variables - - #mode to show status in percentage - if self.update < 3: - #use averaging if using faster update rates - Navg=1 - else: - #Don't need averaging in longer acquisition cases - Navg=1 - busy_avg=0 + #get current CPU stats cpu_stats = psutil.cpu_times_percent(interval=0,percpu=False) #syntax seems to be same for psutil versions 1 and 2 - - tmpsum=cpu_stats.system+cpu_stats.user - if sum(self.ui.cpu[0:Navg-2+1]) == 0: - #avoid initial zeros in the array pulling down the average - just use the value measured in this case. - busy_avg=tmpsum - else: - #case to average - busy_avg=(tmpsum+sum(self.ui.cpu[0:Navg-2+1]))/Navg - - percentcpubusy = busy_avg - self.ui.progressBarStatusCPU.setValue(round(percentcpubusy)) + #determine total busy percentage based upon system and users + percentcpubusy=cpu_stats.system+cpu_stats.user + percentmembusy=psutil.virtual_memory().percent self.ui.progressBarStatusMemory.setValue(round(percentmembusy)) Ncpus=len(psutil.cpu_percent(percpu=True)) @@ -108,7 +99,10 @@ def constantUpdateActor(self,config): except: uname='' except: - pass #skip process - case where process no longer exists + #skip process - case where process no longer exists + cpupct=0 + memVal=0 + uname='' cpupctTot+=cpupct memValTot+=memVal #print "uname: ",uname," Me: ",Me @@ -117,16 +111,34 @@ def constantUpdateActor(self,config): cpupctMe+=cpupct memValMe+=memVal #print "cpupctMe: ",cpupctMe," memValMe: ",memValMe - if config.mplLoaded: - #update first position with most recent value overwriting oldest value which has been shifted to first position - self.ui.cpu=np.roll(self.ui.cpu,1) - self.ui.cpu[0]=percentcpubusy #percentcpubusy seems to agree better with system System Monitor than cpupctTot/Ncpus - self.ui.mem=np.roll(self.ui.mem,1) - self.ui.mem[0]=percentmembusy - self.ui.cpuMe=np.roll(self.ui.cpuMe,1) + + #update first position with most recent value overwriting oldest value which has been shifted to first position + self.ui.cpu=np.roll(self.ui.cpu,1) + #check if CPU smoothing to be applied + sm=int(str(self.ui.comboBoxCPUHistSmooth.currentText())) + if sm == 1: + self.ui.cpu[0]=percentcpubusy + elif sm >1: + self.ui.cpu[0]=(percentcpubusy+np.sum(self.ui.cpu[1:sm]))/sm + else: + #unknown case - default to no smoothing + self.ui.cpu[0]=percentcpubusy + #update progress bar with (potentially) smoothed cpu percentage + self.ui.progressBarStatusCPU.setValue(round(self.ui.cpu[0])) + self.ui.mem=np.roll(self.ui.mem,1) + self.ui.mem[0]=percentmembusy + self.ui.cpuMe=np.roll(self.ui.cpuMe,1) + #check if CPU smoothing to be applied + if sm == 1: + self.ui.cpuMe[0]=cpupctMe/(Ncpus) + elif sm>1: + self.ui.cpuMe[0]=(cpupctMe/(Ncpus)+np.sum(self.ui.cpuMe[1:sm]))/sm + else: + #use no filtering in case sm is unknown (should never happen...) self.ui.cpuMe[0]=cpupctMe/(Ncpus) - self.ui.memMe=np.roll(self.ui.memMe,1) - self.ui.memMe[0]=memValMe + self.ui.memMe=np.roll(self.ui.memMe,1) + self.ui.memMe[0]=memValMe + #update the history plot if self.ui.tabWidget.currentIndex() == config.HIST_TAB: @@ -475,7 +487,11 @@ def updateUserChart(self,config): usersLegend.reverse() p.reverse() #place legend outside of plot to the right - plt.legend(p,usersLegend,bbox_to_anchor=(1.45, 1.1), loc="upper left", borderaxespad=0.1,fontsize=config.pltFont-0.5,title='Users') + if not re.match('1.[0-1]',matplotlib.__version__): + #if not an old version of matplotlib, then use the following command + plt.legend(p,usersLegend,bbox_to_anchor=(1.45, 1.1), loc="upper left", borderaxespad=0.1,fontsize=config.pltFont-0.5,title='Users') + else: + plt.legend(p,usersLegend,bbox_to_anchor=(1.45, 1.1), loc="upper left", borderaxespad=0.1,title='Users') #place second y axis label on plot ylab2=np.arange(5)/4.0*float(ymax) diff --git a/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py index 93cfffe0752b..351c80dd4287 100644 --- a/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py +++ b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py @@ -2,7 +2,7 @@ # Form implementation generated from reading ui file 'ui_sysmon.ui' # -# Created: Wed Sep 24 16:19:13 2014 +# Created: Fri Dec 05 09:55:29 2014 # by: PyQt4 UI code generator 4.8.3 # # WARNING! All changes made in this file will be lost! @@ -37,7 +37,7 @@ def setupUi(self, Form): self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(_fromUtf8("scrollArea")) self.scrollAreaWidgetContents = QtGui.QWidget() - self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 186, 267)) + self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 179, 267)) self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents")) self.verticalLayout_2 = QtGui.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) @@ -268,7 +268,7 @@ def setupUi(self, Form): self.scrollArea_2.setWidgetResizable(True) self.scrollArea_2.setObjectName(_fromUtf8("scrollArea_2")) self.scrollAreaWidgetContents_2 = QtGui.QWidget() - self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 232, 250)) + self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 238, 250)) self.scrollAreaWidgetContents_2.setObjectName(_fromUtf8("scrollAreaWidgetContents_2")) self.horizontalLayout_5 = QtGui.QHBoxLayout(self.scrollAreaWidgetContents_2) self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5")) @@ -290,8 +290,27 @@ def setupUi(self, Form): self.radioButton3600Secs = QtGui.QRadioButton(self.groupBox_6) self.radioButton3600Secs.setObjectName(_fromUtf8("radioButton3600Secs")) self.verticalLayout_5.addWidget(self.radioButton3600Secs) + self.line = QtGui.QFrame(self.groupBox_6) + self.line.setFrameShape(QtGui.QFrame.HLine) + self.line.setFrameShadow(QtGui.QFrame.Sunken) + self.line.setObjectName(_fromUtf8("line")) + self.verticalLayout_5.addWidget(self.line) + self.label = QtGui.QLabel(self.groupBox_6) + self.label.setObjectName(_fromUtf8("label")) + self.verticalLayout_5.addWidget(self.label) + self.comboBoxCPUHistSmooth = QtGui.QComboBox(self.groupBox_6) + self.comboBoxCPUHistSmooth.setObjectName(_fromUtf8("comboBoxCPUHistSmooth")) + self.comboBoxCPUHistSmooth.addItem(_fromUtf8("")) + self.comboBoxCPUHistSmooth.addItem(_fromUtf8("")) + self.comboBoxCPUHistSmooth.addItem(_fromUtf8("")) + self.comboBoxCPUHistSmooth.addItem(_fromUtf8("")) + self.comboBoxCPUHistSmooth.addItem(_fromUtf8("")) + self.verticalLayout_5.addWidget(self.comboBoxCPUHistSmooth) spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout_5.addItem(spacerItem1) + self.labelVersion = QtGui.QLabel(self.groupBox_6) + self.labelVersion.setObjectName(_fromUtf8("labelVersion")) + self.verticalLayout_5.addWidget(self.labelVersion) self.horizontalLayout_5.addWidget(self.groupBox_6) self.groupBox_4 = QtGui.QGroupBox(self.scrollAreaWidgetContents_2) self.groupBox_4.setMinimumSize(QtCore.QSize(0, 0)) @@ -355,6 +374,13 @@ def retranslateUi(self, Form): self.radioButton300Secs.setText(QtGui.QApplication.translate("Form", "300 Seconds", None, QtGui.QApplication.UnicodeUTF8)) self.radioButton600Secs.setText(QtGui.QApplication.translate("Form", "600 Seconds", None, QtGui.QApplication.UnicodeUTF8)) self.radioButton3600Secs.setText(QtGui.QApplication.translate("Form", "3600 Seconds", None, QtGui.QApplication.UnicodeUTF8)) + self.label.setText(QtGui.QApplication.translate("Form", "CPU History Smooth", None, QtGui.QApplication.UnicodeUTF8)) + self.comboBoxCPUHistSmooth.setItemText(0, QtGui.QApplication.translate("Form", "1", None, QtGui.QApplication.UnicodeUTF8)) + self.comboBoxCPUHistSmooth.setItemText(1, QtGui.QApplication.translate("Form", "2", None, QtGui.QApplication.UnicodeUTF8)) + self.comboBoxCPUHistSmooth.setItemText(2, QtGui.QApplication.translate("Form", "5", None, QtGui.QApplication.UnicodeUTF8)) + self.comboBoxCPUHistSmooth.setItemText(3, QtGui.QApplication.translate("Form", "10", None, QtGui.QApplication.UnicodeUTF8)) + self.comboBoxCPUHistSmooth.setItemText(4, QtGui.QApplication.translate("Form", "15", None, QtGui.QApplication.UnicodeUTF8)) + self.labelVersion.setText(QtGui.QApplication.translate("Form", "Version: ", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_4.setTitle(QtGui.QApplication.translate("Form", "Update Rate", None, QtGui.QApplication.UnicodeUTF8)) self.radioButton1Sec.setText(QtGui.QApplication.translate("Form", "1 Second", None, QtGui.QApplication.UnicodeUTF8)) self.radioButton2Secs.setText(QtGui.QApplication.translate("Form", "2 Seconds", None, QtGui.QApplication.UnicodeUTF8)) diff --git a/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui index a793bcc76f91..265c066807af 100644 --- a/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui +++ b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui @@ -52,7 +52,7 @@ 0 0 - 186 + 179 267 @@ -547,7 +547,7 @@ 0 0 - 232 + 238 250 @@ -595,6 +595,49 @@ + + + + Qt::Horizontal + + + + + + + CPU History Smooth + + + + + + + + 1 + + + + + 2 + + + + + 5 + + + + + 10 + + + + + 15 + + + + @@ -608,6 +651,13 @@ + + + + Version: + + + From 9ef4c184dab259455877c208c878fcac04c1f101 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Thu, 11 Dec 2014 10:15:02 +0000 Subject: [PATCH 009/414] Add psutil as package dependency for Linux packages. Refs #9843 --- Code/Mantid/CMakeLists.txt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Code/Mantid/CMakeLists.txt b/Code/Mantid/CMakeLists.txt index 6b42d63df1a0..b70b46f929b1 100644 --- a/Code/Mantid/CMakeLists.txt +++ b/Code/Mantid/CMakeLists.txt @@ -197,8 +197,8 @@ if ( ENABLE_CPACK ) set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},poco-crypto,poco-data,poco-mysql,poco-sqlite,poco-odbc,poco-util,poco-xml,poco-zip,poco-net,poco-netssl,poco-foundation,PyQt4,sip" ) set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},python-ipython >= 1.1.0" ) - # scipy & matplotlib - set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},scipy,python-matplotlib" ) + # scipy, matplotlib, psutil + set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},scipy,python-matplotlib,python-psutil" ) set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},mxml,hdf,hdf5" ) if( "${UNIX_CODENAME}" MATCHES "Santiago" ) @@ -226,19 +226,19 @@ if ( ENABLE_CPACK ) set ( PERFTOOLS_DEB_PACKAGE "libgoogle-perftools0 (>= 1.7)" ) if( "${UNIX_CODENAME}" MATCHES "lucid" ) list ( APPEND DEPENDS_LIST ",libqscintilla2-5," - "libopencascade-foundation-6.3.0 (>= 6.3.0),libopencascade-modeling-6.3.0 (>= 6.3.0)," + "libopencascade-foundation-6.3.0 (>= 6.3.0),libopencascade-modeling-6.3.0 (>= 6.3.0),python-psutil," "libmuparser0,libpocofoundation9,libpocoutil9,libpoconet9,libpoconetssl9,libpococrypto9,libpocoxml9" ) elseif( "${UNIX_CODENAME}" MATCHES "precise" ) list ( APPEND DEPENDS_LIST ",libqscintilla2-8," "libopencascade-foundation-6.5.0 (>= 6.5.0),libopencascade-modeling-6.5.0 (>= 6.5.0)," "libmuparser0debian1," - "ipython-qtconsole (>= 1.1),python-matplotlib,python-scipy," + "ipython-qtconsole (>= 1.1),python-matplotlib,python-scipy,python-psutil," "libpocofoundation9,libpocoutil9,libpoconet9,libpoconetssl9,libpococrypto9,libpocoxml9") elseif( "${UNIX_CODENAME}" STREQUAL "trusty" ) list ( APPEND DEPENDS_LIST ",libqscintilla2-11," "liboce-foundation8,liboce-modeling8," "libmuparser2," - "ipython-qtconsole (>= 1.1),python-matplotlib,python-scipy," + "ipython-qtconsole (>= 1.1),python-matplotlib,python-scipy,python-psutil," "libpocofoundation11,libpocoutil11,libpoconet11,libpoconetssl11,libpococrypto11,libpocoxml11") set ( PERFTOOLS_DEB_PACKAGE "libgoogle-perftools4 (>= 1.7)" ) else() From 4f9e81639e8219fbf3ee5384c513571ae2f0112c Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Mon, 22 Dec 2014 09:26:27 +0000 Subject: [PATCH 010/414] Updated to SysMon v0.27 Refs #9843 --- Code/Mantid/MantidPlot/SysMon/_version.py | 2 +- Code/Mantid/MantidPlot/SysMon/sysmon_tools.py | 216 +++++++++++++++--- README.md | 32 ++- 3 files changed, 205 insertions(+), 45 deletions(-) diff --git a/Code/Mantid/MantidPlot/SysMon/_version.py b/Code/Mantid/MantidPlot/SysMon/_version.py index bad294c0f517..649c677e799e 100644 --- a/Code/Mantid/MantidPlot/SysMon/_version.py +++ b/Code/Mantid/MantidPlot/SysMon/_version.py @@ -1,4 +1,4 @@ #File to identify the current version of the software #Note that this file must be manually updated to contain the same #version number as the git tag for the check-in. -__version__="v0.26" \ No newline at end of file +__version__="v0.27" \ No newline at end of file diff --git a/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py b/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py index 6c2e0f6dfaca..108f6e58c456 100644 --- a/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py +++ b/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py @@ -13,6 +13,8 @@ import math import getpass import re +import sys +import time #check if command line flag --nompl set to disable matplotlib if not(config.nompl): @@ -190,6 +192,9 @@ def constantUpdateActor(self,config): def updateProcTable(self,config): if self.doUpdates==True: + + Ncpus=len(psutil.cpu_percent(percpu=True)) + table=self.ui.tableWidgetProcess #first remove all rows Nrows=table.rowCount() @@ -221,25 +226,93 @@ def updateProcTable(self,config): d_cpu={} d_mem={} d_name={} + d_cpuTimes={} + d_procTimes={} #fill the dictionaries - seems to need to be done faster than within loop which also fills the table...not sure why... + + try: + #check if this dictionary exists or not + self.ui.d_procTimes + self.ui.d_cpuTimes + #if so, move on + pass + except: + #case to initialize the dictionary + for proc in psutil.process_iter(): + try: + #check if acess denied + pname=proc.name + proctime=proc.get_cpu_times() #get + cputime=psutil.cpu_times() + d_procTimes.update({proc.pid:proctime}) + d_cpuTimes.update({proc.pid:cputime}) + except: + #case we skip a process + pass + self.ui.d_cpuTimes=d_cpuTimes + self.ui.d_procTimes=d_procTimes + d_cpuTimes={} + d_procTimes={} + + updateInterval=float(self.update) #timer interval in seconds for proc in psutil.process_iter(): - try: + #try: + if psutil.Process(proc.pid).is_running(): + #if proc.pid == 37196: #check if process still exists, if so, update dictionaries - cpupct=proc.get_cpu_percent(interval=0) if config.psutilVer == 1 else proc.cpu_percent(interval=0) - memVal=float(int(float(proc.get_memory_percent())*100.0))/100.0 if config.psutilVer == 1 else float(int(float(proc.memory_percent())*100.0))/100.0 try: - #don't update dictionaries if name gives an access denied error when checking process name - pname=proc.name if config.psutilVer == 1 else proc.name() - d_user.update({proc.pid:proc.username}) if config.psutilVer == 1 else d_user.update({proc.pid:proc.username()}) - d_cpu.update({proc.pid:cpupct}) - d_mem.update({proc.pid:memVal}) - d_name.update({proc.pid:pname}) + #check if process previously existed - if so we can calculate a cpupct + proctimeHold=self.ui.d_procTimes[proc.pid] + proctime=proc.get_cpu_times() #get + deltaProcTime=(proctime.user+proctime.system) - (proctimeHold.user+proctimeHold.system) + + cputimeHold=self.ui.d_cpuTimes[proc.pid] + cputime=psutil.cpu_times() + deltaCPUTime=(cputime.user+cputime.system+cputime.idle) - (cputimeHold.user+cputimeHold.system+cputimeHold.idle) + + if deltaProcTime > 0: + if deltaCPUTime < updateInterval: + deltaCPUTime=updateInterval + else: + pass + cpupct=float(deltaProcTime)/float(deltaCPUTime)*100.0 + + else: + cpupct=0 + + if cpupct < 0: + cpupct=0 + + cpupct=float(int(float(cpupct)*100))/100 #only keep two decimal places + memVal=float(int(float(proc.get_memory_percent())*100.0))/100.0 if config.psutilVer == 1 else float(int(float(proc.memory_percent())*100.0))/100.0 + + try: + #don't update dictionaries if name gives an access denied error when checking process name + #print "Updating" + pname=proc.name if config.psutilVer == 1 else proc.name() + d_user.update({proc.pid:proc.username}) if config.psutilVer == 1 else d_user.update({proc.pid:proc.username()}) + d_cpu.update({proc.pid:cpupct}) + d_mem.update({proc.pid:memVal}) + d_name.update({proc.pid:pname}) + d_cpuTimes.update({proc.pid:cputime}) + d_procTimes.update({proc.pid:proctime}) + + except: + #print "psutil General Error: ",sys.exc_info()[0] + pass + except: - pass #place holder - except: - pass #skip this process - case where it no longer exists + #else process did not previously exist and we cannot give an update this iteration + #print "except - pid: ",proc.pid + pass + + + #once the dictionarys are updated, update cpu times for next loop + self.ui.d_cpuTimes=d_cpuTimes + self.ui.d_procTimes=d_procTimes + #now fill the table for display for proc in d_user.keys(): #print "proc: ",proc," type: ",type(proc) @@ -295,25 +368,98 @@ def updateUserChart(self,config): d_cpu={} d_mem={} d_name={} - #fill the dictionaries - seems to need to be done faster than within loop which also fills the table...not sure why... + d_cpuTimes={} + d_procTimes={} + + try: + #check if this dictionary exists or not + self.ui.d_procTimes + self.ui.d_cpuTimes + #if so, move on + pass + except: + #case to initialize the dictionary + for proc in psutil.process_iter(): + try: + #check if acess denied + pname=proc.name + proctime=proc.get_cpu_times() #get + cputime=psutil.cpu_times() + d_procTimes.update({proc.pid:proctime}) + d_cpuTimes.update({proc.pid:cputime}) + except: + #case we skip a process + pass + self.ui.d_cpuTimes=d_cpuTimes + self.ui.d_procTimes=d_procTimes + d_cpuTimes={} + d_procTimes={} + + updateInterval=float(self.update) #timer interval in seconds + totcpupct=0 for proc in psutil.process_iter(): try: + psutil.Process(proc.pid).is_running() + #if proc.pid == 37196: #check if process still exists, if so, update dictionaries - cpupct=proc.get_cpu_percent(interval=0) if config.psutilVer == 1 else proc.cpu_percent(interval=0) - memVal=float(int(float(proc.get_memory_percent())*100.0))/100.0 if config.psutilVer == 1 else float(int(float(proc.memory_percent())*100.0))/100.0 try: - #don't update dictionaries if name gives an access denied error when checking process name - pname=proc.name if config.psutilVer == 1 else proc.name() - d_user.update({proc.pid:proc.username}) if config.psutilVer == 1 else d_user.update({proc.pid:proc.username()}) - d_cpu.update({proc.pid:cpupct}) - d_mem.update({proc.pid:memVal}) - d_name.update({proc.pid:pname}) + #check if process previously existed - if so we can calculate a cpupct + proctimeHold=self.ui.d_procTimes[proc.pid] + proctime=proc.get_cpu_times() #get + deltaProcTime=(proctime.user+proctime.system) - (proctimeHold.user+proctimeHold.system) + + cputimeHold=self.ui.d_cpuTimes[proc.pid] + cputime=psutil.cpu_times() + deltaCPUTime=(cputime.user+cputime.system+cputime.idle) - (cputimeHold.user+cputimeHold.system+cputimeHold.idle) + + if deltaProcTime > 0: + if deltaCPUTime < updateInterval: + deltaCPUTime=updateInterval + else: + pass + cpupct=float(deltaProcTime)/float(deltaCPUTime)*100.0 + + else: + cpupct=0 + + if cpupct < 0: + cpupct=0 + + cpupct=float(int(float(cpupct)*100))/100 #only keep two decimal places + totcpupct+=cpupct + memVal=float(int(float(proc.get_memory_percent())*100.0))/100.0 if config.psutilVer == 1 else float(int(float(proc.memory_percent())*100.0))/100.0 + + try: + #don't update dictionaries if name gives an access denied error when checking process name + #print "Updating" + pname=proc.name if config.psutilVer == 1 else proc.name() + d_user.update({proc.pid:proc.username}) if config.psutilVer == 1 else d_user.update({proc.pid:proc.username()}) + #System Idle process should not be listed in users cpu totals so set it to zero + if pname =="System Idle Process": + cpupct=0 + d_cpu.update({proc.pid:cpupct}) + d_mem.update({proc.pid:memVal}) + d_name.update({proc.pid:pname}) + d_cpuTimes.update({proc.pid:cputime}) + d_procTimes.update({proc.pid:proctime}) + + except: + #print "psutil General Error: ",sys.exc_info()[0] + pass + except: - #print "access denied" - pass #place holder + #else process did not previously exist and we cannot give an update this iteration + #print "except - pid: ",proc.pid + + pass except: - #print "skipped process" - pass #skip this process as it no longer exists + #process no longer exists - do nothing + pass + + + self.ui.d_cpuTimes=d_cpuTimes + self.ui.d_procTimes=d_procTimes + #print "** Total Mem Used: ",sum(d_mem.values()) users=d_user.values() users_unique=list(set(users)) #use set() to find unique users then convert the resulting set to a list via list() @@ -335,7 +481,7 @@ def updateUserChart(self,config): user=d_user[pid] cpu_by_users[user]=cpu_by_users[user] + d_cpu[pid] mem_by_users[user]=mem_by_users[user] + d_mem[pid] - + #print d_cpu[35296],d_cpu[37196],d_cpu[35296]+d_cpu[37196] #now convert to a list which we can index cpu_by_users_lst=cpu_by_users.values() mem_by_users_lst=mem_by_users.values() @@ -370,6 +516,7 @@ def updateUserChart(self,config): indx=sorted(range(len(mem_by_users_lst)), key=mem_by_users_lst.__getitem__,reverse=True) else: print 'Incorrect sort parameter' + #sort lists cpu_by_users_sorted=[cpu_by_users_lst[x] for x in indx] mem_by_users_sorted=[mem_by_users_lst[x] for x in indx] @@ -438,10 +585,10 @@ def updateUserChart(self,config): frame=plt.gca() frame.axes.get_yaxis().set_ticks([]) plt.xticks(np.arange(2)+width/2.,('CPU','Mem'),fontsize=config.pltFont,fontweight='bold') - ymaxCPU=int((sum(cpu_by_users_sorted)+100)/100)*100 #range ymaxCPU to nearest 100% + ymaxCPU=int(round(sum(cpu_by_users_sorted)+10))/10*10 #range ymaxCPU to nearest 10% ymaxMEM=int(round(sum(mem_by_users_sorted)+10))/10*10 #range ymaxMEM to nearest 10% - ymaxMAX=max([ymaxCPU,ymaxMEM,100]) + ymaxMAX=max([ymaxCPU,ymaxMEM]) if sortBy == 'cpu': ymax=max([ymaxCPU,10]) @@ -452,20 +599,23 @@ def updateUserChart(self,config): elif sortBy == 'max': ymax=max([ymaxMAX,10]) auto=True -# print 'ymaxCPU: ',ymaxCPU,' ymaxMEM: ',ymaxMEM,' ymaxMAX: ',ymaxMAX,' ymax: ',ymax,' sum(mem_by_users_sorted): ',sum(mem_by_users_sorted) - plt.ylim(0,ymax,auto=auto) + #print 'ymaxCPU: ',ymaxCPU,' ymaxMEM: ',ymaxMEM,' ymaxMAX: ',ymaxMAX,' ymax: ',ymax + #print 'sum(cpu_by_users_sorted): ',sum(cpu_by_users_sorted),'sum(mem_by_users_sorted): ',sum(mem_by_users_sorted) + #print cpu_by_users + plt.ylim(0,ymax,auto=True) #compute composite % sumCPU=sum(cpu_by_users_sorted) - ylab=np.arange(5)/4.0*float(sumCPU)/float(self.ui.Ncpus) + sumCPU=float(int(sumCPU*100))/100 #use two digits + ylab=np.arange(5)/4.0*float(sumCPU)#/float(self.ui.Ncpus) scl=float(ymax)/float(sumCPU) ylab=ylab*100*scl tmp=ylab.astype('int') tmp1=tmp.astype('float') tmp1=tmp1/100 - ylab1=tmp1 + ylab1=np.round(tmp1) ax1=plt.twinx() ax1.set_ylabel('Composite CPU Percent',fontsize=config.pltFont,fontweight='bold') @@ -496,7 +646,7 @@ def updateUserChart(self,config): #place second y axis label on plot ylab2=np.arange(5)/4.0*float(ymax) ax2=plt.twinx() - ax2.set_ylabel('Percent',fontsize=config.pltFont,fontweight='bold',position=(0.9,0.5)) + ax2.set_ylabel('Memory Percent',fontsize=config.pltFont,fontweight='bold',position=(0.9,0.5)) ax2.set_yticks(ylab2) #ax2.set_yticks(ylab2) ax2.yaxis.set_ticks_position('right') diff --git a/README.md b/README.md index 71a05dea8d76..8ef2ab770d04 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,25 @@ -Mantid +SysMon ====== -The Mantid project provides a framework that supports high-performance computing and visualisation of scientific data. Mantid has been created to manipulate and analyse Neutron and Muon scattering data, but could be applied to many other techniques. The framework is open source and supported on multiple target platforms (Windows, Linux, Mac OS X). +Python qt system monitor which utilizes the Python psutil and platform modules to provide system information for display. -Useful links ------------- - * Homepage: http://www.mantidproject.org - * Download: http://download.mantidproject.org - * Asking for help: http://download.mantidproject.org/webmailer/index.php - * Issue tracking: http://trac.mantidproject.org/mantid/ - * Build server: http://builds.mantidproject.org - * Developer site: http://developer.mantidproject.org +This application has been adapted to work with psutil version 1 and version 2 modules as there are some command syntax changes between these two versions. + +The SysMon user interface has been divided into a main window which imports the tabs to make a standalone application, or the tabs can be imported into other applications as a QWidget. Thus there are separate .ui files corresponding to each. + +The code which imports the tabs into the main program resides in SysMon.pyw. This is where to look to see how to include the tabs into your own application. All files except SysMon.pyw and ui_sysmonMainWindow.* will be required when tabs are incorporated in other applications. + +The following command line arguments have been added: + --help to print out the help message. + --nompl to run the application minus matplotlib in support of the current MantidPlot (removes those tabs requiring matplotlib). + --custom to enable the custom menubar item in the standalone application (currently supports checking Matlab license status on SNS analysis computers). + +To run as a standalone application via the corresponding command lines: + *Change to the folder containing the Sysmon software, then: + *DOS: python SysMon.pyw + *Linux: ./SysMon.pyw + +The standalone application been tested on Windows and RHEL Linux, but not on Mac yet. + +Note that configuration and global constants and variables now reside in config.py. -[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/mantidproject/mantid/trend.png)](https://bitdeli.com/free "Bitdeli Badge") From 5fa5b77c5c91ab8e29de62bc92836db7a4b89bc6 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Mon, 5 Jan 2015 10:07:26 +0000 Subject: [PATCH 011/414] Update SysMon to version 0.28 Refs #9843 --- Code/Mantid/MantidPlot/SysMon/_version.py | 2 +- Code/Mantid/MantidPlot/SysMon/sysmon.py | 11 ++++++----- Code/Mantid/MantidPlot/SysMon/sysmon_tools.py | 6 ++---- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/Code/Mantid/MantidPlot/SysMon/_version.py b/Code/Mantid/MantidPlot/SysMon/_version.py index 649c677e799e..83dec484891b 100644 --- a/Code/Mantid/MantidPlot/SysMon/_version.py +++ b/Code/Mantid/MantidPlot/SysMon/_version.py @@ -1,4 +1,4 @@ #File to identify the current version of the software #Note that this file must be manually updated to contain the same #version number as the git tag for the check-in. -__version__="v0.27" \ No newline at end of file +__version__="v0.28" \ No newline at end of file diff --git a/Code/Mantid/MantidPlot/SysMon/sysmon.py b/Code/Mantid/MantidPlot/SysMon/sysmon.py index 967442b50c65..6e9336ee8c49 100644 --- a/Code/Mantid/MantidPlot/SysMon/sysmon.py +++ b/Code/Mantid/MantidPlot/SysMon/sysmon.py @@ -13,12 +13,13 @@ #check psutil version as command syntax changes between version 1 and version 2 ver=psutil.__version__ -verChk1=re.match('1.[0-9].[0-9]',ver) #latest psutil version 1 is 1.2.1 - using positional numeric wildcards to check sub versions -#thus the check is for version 1 as version 2 and following versions are still evolving -#match returns a string if a match is found else returns NoneType -if verChk1 != None: +#using positional numeric wildcards for re.match() to check sub versions +#match returns a match object if a match is found else returns NoneType +if re.match('0.[0-9].[0-9]',ver) or re.match('1.[0-9].[0-9]',ver) != None: + #set flag to version 1 if either version 0 or version 1 psutil imported config.psutilVer=1 else: + #set flat to version 2 for any versions higher than version 1 config.psutilVer=2 from ui_sysmon import * @@ -162,7 +163,7 @@ def __init__(self, parent=None): self.ui.tabWidget.setCurrentIndex(config.SYST_TAB) #initialize version label - self.ui.labelVersion.setText("Version: "+__version__) + self.ui.labelVersion.setText("Version: "+__version__+"_"+psutil.__version__) def constantUpdate(self): #redirct to global function diff --git a/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py b/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py index 108f6e58c456..e0dc66da4615 100644 --- a/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py +++ b/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py @@ -40,10 +40,8 @@ def constantUpdateActor(self,config): #set duration number Ndur=self.duration - #get current CPU stats - cpu_stats = psutil.cpu_times_percent(interval=0,percpu=False) #syntax seems to be same for psutil versions 1 and 2 - #determine total busy percentage based upon system and users - percentcpubusy=cpu_stats.system+cpu_stats.user + #get current CPU percent busy + percentcpubusy = psutil.cpu_percent() percentmembusy=psutil.virtual_memory().percent self.ui.progressBarStatusMemory.setValue(round(percentmembusy)) From c15e56ff853c09ee3976a04e7a1fcb6addeda54e Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Thu, 8 Jan 2015 09:29:07 +0000 Subject: [PATCH 012/414] Update SysMon to version 0.29 Refs #9843 --- Code/Mantid/MantidPlot/SysMon/_version.py | 2 +- Code/Mantid/MantidPlot/SysMon/sysmon.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/MantidPlot/SysMon/_version.py b/Code/Mantid/MantidPlot/SysMon/_version.py index 83dec484891b..b88b26dd7c4b 100644 --- a/Code/Mantid/MantidPlot/SysMon/_version.py +++ b/Code/Mantid/MantidPlot/SysMon/_version.py @@ -1,4 +1,4 @@ #File to identify the current version of the software #Note that this file must be manually updated to contain the same #version number as the git tag for the check-in. -__version__="v0.28" \ No newline at end of file +__version__="v0.29" \ No newline at end of file diff --git a/Code/Mantid/MantidPlot/SysMon/sysmon.py b/Code/Mantid/MantidPlot/SysMon/sysmon.py index 6e9336ee8c49..33249856c52c 100644 --- a/Code/Mantid/MantidPlot/SysMon/sysmon.py +++ b/Code/Mantid/MantidPlot/SysMon/sysmon.py @@ -119,7 +119,8 @@ def __init__(self, parent=None): #create drawing canvas # a figure instance to plot on - if not re.match('1.[0-1]',matplotlib.__version__): + #rc_context in matplotlib requires version 1.2.0 or later, so check we don't have an older version of matplotlib + if not re.match('1.[0-1]',matplotlib.__version__) and not re.match('0.',matplotlib.__version__): #if not an old version of matplotlib, then use the following command matplotlib.rc_context({'toolbar':False}) #initialize figure 1 and its canvas for cpu and memory history plots @@ -163,7 +164,7 @@ def __init__(self, parent=None): self.ui.tabWidget.setCurrentIndex(config.SYST_TAB) #initialize version label - self.ui.labelVersion.setText("Version: "+__version__+"_"+psutil.__version__) + self.ui.labelVersion.setText("Version: "+__version__+"_"+matplotlib.__version__+"_"+psutil.__version__) def constantUpdate(self): #redirct to global function From ad2c3d421a4fdae7857db665509f6e4da395331e Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Mon, 12 Jan 2015 09:43:26 +0000 Subject: [PATCH 013/414] refs #10875. Better docs. Changed algorithm documentation as well as documentation in the source code. --- Code/Mantid/Framework/MDEvents/src/Integrate3DEvents.cpp | 8 +++++++- .../docs/source/algorithms/IntegrateEllipsoids-v1.rst | 4 +++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/MDEvents/src/Integrate3DEvents.cpp b/Code/Mantid/Framework/MDEvents/src/Integrate3DEvents.cpp index 43069e08714c..826834330a38 100644 --- a/Code/Mantid/Framework/MDEvents/src/Integrate3DEvents.cpp +++ b/Code/Mantid/Framework/MDEvents/src/Integrate3DEvents.cpp @@ -185,11 +185,17 @@ int Integrate3DEvents::numInEllipsoid(std::vector const &events, /** * Given a list of events, associated with a particular peak - * and SHIFTED to be centered at (0,0,0), calculate the 3x3 + * and already SHIFTED to be centered at (0,0,0), calculate the 3x3 * covariance matrix for finding the principal axes of that * local event data. Only events within the specified radius * of (0,0,0) will be used. * + * The covariance matrix can be easily constructed. X, Y, Z of each peak position are the variables we wish to determine + * the covariance. The mean position in each dimension has already been calculated on subtracted, since this corresponds to the centre position of each + * peak, which we knew aprori. The expected values of each correlation test X,X X,Y X,Z e.t.c form the elements of this 3 by 3 matrix, but since the + * probabilities are equal, we can remove them from the sums of the expected values, and simply divide by the number of events for each matrix element. + * Note that the diagonal elements form the variance X,X, Y,Y, Z,Z + * * @param events Vector of V3D objects containing the * Q vectors for a peak, with mean at (0,0,0). * @param matrix A 3x3 matrix that will be filled out with diff --git a/Code/Mantid/docs/source/algorithms/IntegrateEllipsoids-v1.rst b/Code/Mantid/docs/source/algorithms/IntegrateEllipsoids-v1.rst index ef8e0f5483f0..c64b003e7668 100644 --- a/Code/Mantid/docs/source/algorithms/IntegrateEllipsoids-v1.rst +++ b/Code/Mantid/docs/source/algorithms/IntegrateEllipsoids-v1.rst @@ -110,7 +110,7 @@ added to the list of events for a peak provided that the fractional :math:`Q` -vector) is closer to the :math:`h,k,l` of that peak, than to the :math:`h,k,l` of any other peak AND the :math:`Q` -vector for that event is within the specified -radius of the :math:`Q` -vector for that peak. +radius of the :math:`Q` -vector for that peak. This technique makes the algorithm suitable for nuclear peaks, but may not be suitable for magnetic peaks. When the lists of events near the peaks have been built, the three principal axes of the set of events near each peak are found, and the @@ -155,6 +155,8 @@ ellipsoid. The outer surface of the background ellipsoidal shell is an ellipsoidal surface with the same relative axis lengths as the inner surface. +This algorithm uses principle component analysis to determine the principle axis for each peak. For the event list (QLab) associated with each peak, the algorithm determines a covariance matrix, and uses that to establish eigenvectors corresponding to the principle axis (all orthogonal). The sizes of each principle axis are used define the region of which events will be counted/integrated from those already associated with each peak. + Usage ------ From fe3e9486183dc96ae2afc5a8befa5c1219d664dd Mon Sep 17 00:00:00 2001 From: Nick Draper Date: Wed, 14 Jan 2015 18:04:37 +0000 Subject: [PATCH 014/414] re #10899 Fixing a casing error in FindOpenCasade.cmake --- Code/Mantid/Build/CMake/FindOpenCascade.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Build/CMake/FindOpenCascade.cmake b/Code/Mantid/Build/CMake/FindOpenCascade.cmake index aefa011416e1..ed88d20d029c 100644 --- a/Code/Mantid/Build/CMake/FindOpenCascade.cmake +++ b/Code/Mantid/Build/CMake/FindOpenCascade.cmake @@ -60,7 +60,7 @@ find_library ( OPENCASCADE_LIB_TKGEOMBASE NAMES TKGeomBase ) -find_library ( OPENCASCADE_LIB_TKGEOMAlgo +find_library ( OPENCASCADE_LIB_TKGEOMALGO NAMES TKGeomAlgo ) From 1385fe4e66146c540c96976f5374bb94a06cdfd0 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Thu, 15 Jan 2015 15:14:02 +0000 Subject: [PATCH 015/414] Fixing patch number for release 3.3.0 --- Code/Mantid/Build/CMake/VersionNumber.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Build/CMake/VersionNumber.cmake b/Code/Mantid/Build/CMake/VersionNumber.cmake index 8d616616e39d..2c8f948b88ab 100644 --- a/Code/Mantid/Build/CMake/VersionNumber.cmake +++ b/Code/Mantid/Build/CMake/VersionNumber.cmake @@ -6,5 +6,5 @@ set ( VERSION_MINOR 3 ) # UNCOMMENT the next 'set' line to 'force' the patch version number to # a value (instead of using the count coming out of 'git describe') # DO NOT COMMIT THIS TO MASTER UNCOMMENTED, ONLY TO A RELEASE BRANCH -#set ( VERSION_PATCH 0 ) +set ( VERSION_PATCH 0 ) From bb4d57df3ec166c880a07b0b97fb2971c183a9ab Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Fri, 16 Jan 2015 13:18:54 +0000 Subject: [PATCH 016/414] Fix rpm for Fedora >= 18 and RHEL >= 7 The rpm command is now more strict on these systems and requires the package not to own system directories Refs #10911 --- Code/Mantid/Build/CMake/LinuxPackageScripts.cmake | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake b/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake index d3ddda676e5d..cf5728be28ba 100644 --- a/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake +++ b/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake @@ -22,6 +22,10 @@ endif() set ( CMAKE_INSTALL_RPATH ${CMAKE_INSTALL_PREFIX}/${LIB_DIR};${CMAKE_INSTALL_PREFIX}/${PLUGINS_DIR};${CMAKE_INSTALL_PREFIX}/${PVPLUGINS_DIR} ) +# Tell rpm that this package does not own /opt /usr/share/{applications,pixmaps} +# Required for Fedora >= 18 and RHEL >= 7 +set ( CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION /opt /usr/share/applications /usr/share/pixmaps ) + ########################################################################### # LD_PRELOAD libraries ########################################################################### From 00e3c71cdc1c7587b642e5c5e56d4d7240023927 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Fri, 16 Jan 2015 14:46:44 +0000 Subject: [PATCH 017/414] Re #10894 updating PlotAsymmetryByLogValue algorithm --- .../PlotAsymmetryByLogValue.h | 33 +- .../src/PlotAsymmetryByLogValue.cpp | 406 +++++++++++------- 2 files changed, 273 insertions(+), 166 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h index e1dd2d90a01b..26508de9191b 100644 --- a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h +++ b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h @@ -69,7 +69,6 @@ class DLLExport PlotAsymmetryByLogValue : public API::Algorithm { virtual const std::string summary() const { return "Calculates asymmetry for a series of log values"; } - /// Algorithm's version for identification overriding a virtual method virtual int version() const { return 1; } /// Algorithm's category for identification overriding a virtual method @@ -79,19 +78,24 @@ class DLLExport PlotAsymmetryByLogValue : public API::Algorithm { // Overridden Algorithm methods void init(); void exec(); - + // Parse run names + void parseRunNames (std::string& firstFN, std::string& lastFN, std::string& fnBase, std::string& fnExt); + // Load dead-time corrections from specified file + void loadCorrectionsFromFile (API::Workspace_sptr &customDeadTimes, std::string deadTimeFile ); + // Apply dead-time corrections + void applyDeadtimeCorr (API::Workspace_sptr &loadedWs, API::Workspace_sptr deadTimes); + /// Group detectors from run file + void groupDetectors (API::Workspace_sptr &loadedWs, API::Workspace_sptr loadedDetGrouping); /// Calculate the integral asymmetry for a workspace (single period) void calcIntAsymmetry(API::MatrixWorkspace_sptr ws, double &Y, double &E); - /// Calculate the integral asymmetry for a workspace (red & green) - void calcIntAsymmetry(API::MatrixWorkspace_sptr ws_red, - API::MatrixWorkspace_sptr ws_geen, double &Y, - double &E); + void calcIntAsymmetry(API::MatrixWorkspace_sptr ws_red, API::MatrixWorkspace_sptr ws_geen, double &Y, double &E); /// Group detectors - void groupDetectors(API::MatrixWorkspace_sptr &ws, - const std::vector &spectraList); + void groupDetectors (API::MatrixWorkspace_sptr &ws, const std::vector &spectraList); /// Get log value - double getLogValue(API::MatrixWorkspace &ws, const std::string &logName); + double getLogValue(API::MatrixWorkspace &ws); + /// Populate output workspace with results + void populateOutputWorkspace (API::MatrixWorkspace_sptr &outWS, int nplots); /// Stores property "Int" bool m_int; @@ -101,6 +105,17 @@ class DLLExport PlotAsymmetryByLogValue : public API::Algorithm { std::vector m_backward_list; /// If true call LoadMuonNexus with Autogroup on bool m_autogroup; + // Mantid vectors to store results + // Red mantid vectors + MantidVec m_redX, m_redY, m_redE; + // Green mantid vectors + MantidVec m_greenX, m_greenY, m_greenE; + // Mantid vectors to store Red + Green + MantidVec m_sumX, m_sumY, m_sumE; + // Mantid vectors to store Red - Green + MantidVec m_diffX, m_diffY, m_diffE; + // LogValue name + std::string m_logName; }; } // namespace Algorithm diff --git a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp index c9dfec93a203..aac17d5f3771 100644 --- a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp +++ b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp @@ -15,6 +15,7 @@ #include "MantidAPI/AlgorithmManager.h" #include "MantidAlgorithms/PlotAsymmetryByLogValue.h" #include "MantidDataObjects/Workspace2D.h" +#include "MantidDataObjects/TableWorkspace.h" #include "MantidKernel/ArrayProperty.h" #include "MantidKernel/ListValidator.h" #include "MantidKernel/MandatoryValidator.h" @@ -130,232 +131,322 @@ void PlotAsymmetryByLogValue::init() { * Executes the algorithm */ void PlotAsymmetryByLogValue::exec() { + + // Get properties + // Get grouping property m_forward_list = getProperty("ForwardSpectra"); m_backward_list = getProperty("BackwardSpectra"); m_autogroup = (m_forward_list.size() == 0 && m_backward_list.size() == 0); - - std::string logName = getProperty("LogValue"); - + // Get log value + m_logName = getProperty("LogValue"); + // Get green and red periods int red = getProperty("Red"); int green = getProperty("Green"); - + // Get type of computation std::string stype = getProperty("Type"); m_int = stype == "Integral"; - + // Get type of dead-time corrections + const std::string dtcType = getPropertyValue("DeadTimeCorrType"); + // Get runs std::string firstFN = getProperty("FirstRun"); std::string lastFN = getProperty("LastRun"); - std::string ext = firstFN.substr(firstFN.find_last_of(".")); - - firstFN.erase(firstFN.size() - 4); - lastFN.erase(lastFN.size() - 4); - - std::string fnBase = firstFN; - size_t i = fnBase.size() - 1; - while (isdigit(fnBase[i])) - i--; - if (i == fnBase.size() - 1) { - g_log.error("File name must end with a number."); - throw Exception::FileError("File name must end with a number.", firstFN); - } - fnBase.erase(i + 1); - - firstFN.erase(0, fnBase.size()); - lastFN.erase(0, fnBase.size()); - + // Parse run names and get the number of runs + std::string fnBase, fnExt; + parseRunNames( firstFN, lastFN, fnBase, fnExt); size_t is = atoi(firstFN.c_str()); // starting run number size_t ie = atoi(lastFN.c_str()); // last run number int w = static_cast(firstFN.size()); - // The number of runs - size_t npoints = ie - is + 1; - - // Create the 2D workspace for the output - int nplots = green != EMPTY_INT() ? 4 : 1; - MatrixWorkspace_sptr outWS = WorkspaceFactory::Instance().create( - "Workspace2D", - nplots, // the number of plots - npoints, // the number of data points on a plot - npoints // it's not a histogram - ); - TextAxis *tAxis = new TextAxis(nplots); - if (nplots == 1) { - tAxis->setLabel(0, "Asymmetry"); - } else { - tAxis->setLabel(0, "Red-Green"); - tAxis->setLabel(1, "Red"); - tAxis->setLabel(2, "Green"); - tAxis->setLabel(3, "Red+Green"); - } - outWS->replaceAxis(1, tAxis); - - const std::string dtcType = getPropertyValue("DeadTimeCorrType"); + // Dead-time corrections: if user specifies a file, load corrections now Workspace_sptr customDeadTimes; - if (dtcType == "FromSpecifiedFile") { - IAlgorithm_sptr loadDeadTimes = createChildAlgorithm("LoadNexusProcessed"); - loadDeadTimes->initialize(); - loadDeadTimes->setPropertyValue("Filename", - getPropertyValue("DeadTimeCorrFile")); - loadDeadTimes->execute(); - - customDeadTimes = loadDeadTimes->getProperty("OutputWorkspace"); + loadCorrectionsFromFile (customDeadTimes, getPropertyValue("DeadTimeCorrFile")); } Progress progress(this, 0, 1, ie - is + 2); + + // Loop through runs for (size_t i = is; i <= ie; i++) { + + // Get complete run name std::ostringstream fn, fnn; fnn << std::setw(w) << std::setfill('0') << i; - fn << fnBase << fnn.str() << ext; + fn << fnBase << fnn.str() << fnExt; + // Load run IAlgorithm_sptr load = createChildAlgorithm("LoadMuonNexus"); - load->initialize(); load->setPropertyValue("Filename", fn.str()); load->execute(); - Workspace_sptr loadedWs = load->getProperty("OutputWorkspace"); + // Check if dead-time corrections have to be applied if (dtcType != "None") { - IAlgorithm_sptr applyCorr = - AlgorithmManager::Instance().create("ApplyDeadTimeCorr"); - applyCorr->setLogging(false); - applyCorr->setRethrows(true); - - ScopedWorkspace ws(loadedWs); - applyCorr->setPropertyValue("InputWorkspace", ws.name()); - applyCorr->setPropertyValue("OutputWorkspace", ws.name()); - - ScopedWorkspace deadTimes; - if (dtcType == "FromSpecifiedFile") { - deadTimes.set(customDeadTimes); + applyDeadtimeCorr (loadedWs, customDeadTimes); } else { - deadTimes.set(load->getProperty("DeadTimeTable")); + Workspace_sptr deadTimes = load->getProperty("DeadTimeTable"); + applyDeadtimeCorr (loadedWs, deadTimes); } - - applyCorr->setPropertyValue("DeadTimeTable", deadTimes.name()); - applyCorr->execute(); - - // Workspace should've been replaced in the ADS by ApplyDeadTimeCorr, so - // need to - // re-assign it - loadedWs = ws.retrieve(); } + // If m_autogroup, group detectors if (m_autogroup) { - Workspace_sptr loadedDetGrouping = - load->getProperty("DetectorGroupingTable"); - + Workspace_sptr loadedDetGrouping = load->getProperty("DetectorGroupingTable"); if (!loadedDetGrouping) throw std::runtime_error("No grouping info in the file.\n\nPlease " "specify grouping manually"); - - // Could be groups of workspaces, so need to work with ADS - ScopedWorkspace inWS(loadedWs); - ScopedWorkspace grouping(loadedDetGrouping); - ScopedWorkspace outWS; - - try { - IAlgorithm_sptr applyGrouping = - AlgorithmManager::Instance().create("MuonGroupDetectors"); - applyGrouping->setLogging(false); - applyGrouping->setRethrows(true); - - applyGrouping->setPropertyValue("InputWorkspace", inWS.name()); - applyGrouping->setPropertyValue("DetectorGroupingTable", - grouping.name()); - applyGrouping->setPropertyValue("OutputWorkspace", outWS.name()); - applyGrouping->execute(); - - loadedWs = outWS.retrieve(); - } catch (...) { - throw std::runtime_error( - "Unable to group detectors.\n\nPlease specify grouping manually."); - } + groupDetectors(loadedWs,loadedDetGrouping); } + // Check if workspace is a workspace group WorkspaceGroup_sptr loadedGroup = boost::dynamic_pointer_cast(loadedWs); + // If it is not, we only have 'red' data if (!loadedGroup) { Workspace2D_sptr loadedWs2D = boost::dynamic_pointer_cast(loadedWs); double Y, E; calcIntAsymmetry(loadedWs2D, Y, E); - outWS->dataY(0)[i - is] = Y; - outWS->dataX(0)[i - is] = getLogValue(*loadedWs2D, logName); - outWS->dataE(0)[i - is] = E; + m_redX.push_back(getLogValue(*loadedWs2D)); + m_redY.push_back(Y); + m_redE.push_back(E); + } else { + DataObjects::Workspace2D_sptr ws_red; DataObjects::Workspace2D_sptr ws_green; - - // Run through the periods of the loaded file and do calculations on the + // Run through the periods of the loaded file and save the // selected ones for (int mi = 0; mi < loadedGroup->getNumberOfEntries(); mi++) { + Workspace2D_sptr memberWs = boost::dynamic_pointer_cast(loadedGroup->getItem(mi)); - int period = mi + 1; - - // Do only one period - if (green == EMPTY_INT() && period == red) { + if ( period == red ){ ws_red = memberWs; - double Y, E; - calcIntAsymmetry(ws_red, Y, E); - outWS->dataY(0)[i - is] = Y; - outWS->dataX(0)[i - is] = getLogValue(*ws_red, logName); - outWS->dataE(0)[i - is] = E; - } else // red & green - { - if (period == red) - ws_red = memberWs; - if (period == green) + } + if ( green!= EMPTY_INT() ){ + if ( period == green ){ ws_green = memberWs; + } } } - // red & green claculation - if (green != EMPTY_INT()) { - if (!ws_red || !ws_green) - throw std::invalid_argument("Red or green period is out of range"); + // Check ws_red + if (!ws_red){ + throw std::invalid_argument("Red period is out of range"); + } + // Check ws_green + if ( (green!=EMPTY_INT()) && (!ws_green) ){ + throw std::invalid_argument("Green period is out of range"); + } + + if ( green==EMPTY_INT() ){ double Y, E; - double Y1, E1; - double logValue = getLogValue(*ws_red, logName); calcIntAsymmetry(ws_red, Y, E); - calcIntAsymmetry(ws_green, Y1, E1); - outWS->dataY(1)[i - is] = Y; - outWS->dataX(1)[i - is] = logValue; - outWS->dataE(1)[i - is] = E; - - outWS->dataY(2)[i - is] = Y1; - outWS->dataX(2)[i - is] = logValue; - outWS->dataE(2)[i - is] = E1; - - outWS->dataY(3)[i - is] = Y + Y1; - outWS->dataX(3)[i - is] = logValue; - outWS->dataE(3)[i - is] = sqrt(E * E + E1 * E1); - + m_redX.push_back(getLogValue(*ws_red)); + m_redY.push_back(Y); + m_redE.push_back(E); + + } else{ + + double YR, ER; + double YG, EG; + double logValue = getLogValue(*ws_red); + calcIntAsymmetry(ws_red, YR, ER); + calcIntAsymmetry(ws_green, YG, EG); + // Red data + m_redX.push_back(logValue); + m_redY.push_back(YR); + m_redE.push_back(ER); + // Green data + m_greenX.push_back(logValue); + m_greenY.push_back(YG); + m_greenE.push_back(EG); + // Sum + m_sumX.push_back(logValue); + m_sumY.push_back(YR+YG); + m_sumE.push_back(sqrt(ER * ER + EG * EG)); // move to last for safety since some grouping takes place in the // calcIntAsymmetry call below - calcIntAsymmetry(ws_red, ws_green, Y, E); - outWS->dataY(0)[i - is] = Y; - outWS->dataX(0)[i - is] = logValue; - outWS->dataE(0)[i - is] = E; - } else if (!ws_red) - throw std::invalid_argument("Red period is out of range"); - } + calcIntAsymmetry(ws_red, ws_green, YR, ER); + m_diffX.push_back(logValue); + m_diffY.push_back(YR); + m_diffE.push_back(ER); + } + } // else loadedGroup progress.report(); } - outWS->getAxis(0)->title() = logName; - outWS->setYUnitLabel("Asymmetry"); + // Create the 2D workspace for the output + int nplots = m_greenX.size() ? 4 : 1; + size_t npoints = ie - is + 1; + MatrixWorkspace_sptr outWS = WorkspaceFactory::Instance().create( + "Workspace2D", + nplots, // the number of plots + npoints, // the number of data points on a plot + npoints // it's not a histogram + ); + // Populate output workspace with data + populateOutputWorkspace(outWS,nplots); // Assign the result to the output workspace property setProperty("OutputWorkspace", outWS); } +/** Load dead-time corrections from specified file +* @param customDeadTimes :: [input/output] Output workspace to store corrections +* @param deadTimeFile :: [input] File to read corrections from +*/ +void PlotAsymmetryByLogValue::loadCorrectionsFromFile (Workspace_sptr &customDeadTimes, std::string deadTimeFile ) +{ + try{ + IAlgorithm_sptr loadDeadTimes = createChildAlgorithm("LoadNexusProcessed"); + loadDeadTimes->setPropertyValue("Filename", deadTimeFile); + loadDeadTimes->setProperty("OutputWorkspace", customDeadTimes); + loadDeadTimes->executeAsChildAlg(); + customDeadTimes = loadDeadTimes->getProperty("OutputWorkspace"); + } + catch (...){ + throw std::runtime_error("Unable to load corrections from specified file\n"); + } +} +/** Populate output workspace with results +* @param outWS :: [input/output] Output workspace to populate +* @param nplots :: [input] Number of histograms +*/ +void PlotAsymmetryByLogValue::populateOutputWorkspace (MatrixWorkspace_sptr &outWS, int nplots) +{ + TextAxis *tAxis = new TextAxis(nplots); + if (nplots == 1) { + tAxis->setLabel(0, "Asymmetry"); + outWS->dataX(0) = m_redX; + outWS->dataY(0) = m_redY; + outWS->dataE(0) = m_redE; + } else { + tAxis->setLabel(0, "Red-Green"); + tAxis->setLabel(1, "Red"); + tAxis->setLabel(2, "Green"); + tAxis->setLabel(3, "Red+Green"); + outWS->dataX(0) = m_diffX; + outWS->dataY(0) = m_diffY; + outWS->dataE(0) = m_diffE; + outWS->dataX(1) = m_redX; + outWS->dataY(1) = m_redY; + outWS->dataE(1) = m_redE; + outWS->dataX(2) = m_greenX; + outWS->dataY(2) = m_greenY; + outWS->dataE(2) = m_greenE; + outWS->dataX(3) = m_sumX; + outWS->dataY(3) = m_sumY; + outWS->dataE(3) = m_sumE; + } + outWS->replaceAxis(1, tAxis); + outWS->getAxis(0)->title() = m_logName; + outWS->setYUnitLabel("Asymmetry"); +} +/** Parse run names +* @param firstFN :: [input/output] First run's name +* @param lastFN :: [input/output] Last run's name +* @param fnBase :: [output] Runs base name +* @param fnExt :: [output] Runs extension +*/ +void PlotAsymmetryByLogValue::parseRunNames (std::string& firstFN, std::string& lastFN, std::string& fnBase, std::string& fnExt) +{ + + if ( firstFN.size() != lastFN.size() ) + { + throw std::runtime_error("First and last runs are not in the same directory\n"); + } + + fnExt = firstFN.substr(firstFN.find_last_of(".")); + + firstFN.erase(firstFN.size() - 4); + lastFN.erase(lastFN.size() - 4); + + fnBase = firstFN; + size_t i = fnBase.size() - 1; + while (isdigit(fnBase[i])) + i--; + if (i == fnBase.size() - 1) { + throw Exception::FileError("File name must end with a number.", firstFN); + } + fnBase.erase(i + 1); + + std::string fnBase2 = lastFN; + fnBase2.erase(i + 1); + if ( fnBase != fnBase2 ) + { + throw std::runtime_error("First and last runs are not in the same directory\n"); + } + + firstFN.erase(0, fnBase.size()); + lastFN.erase(0, fnBase.size()); +} + +/** Apply dead-time corrections. The calculation is done by ApplyDeadTimeCorr algorithm +* @param loadedWs :: [input/output] Workspace to apply corrections to +* @param deadTimes :: [input] Corrections to apply +*/ +void PlotAsymmetryByLogValue::applyDeadtimeCorr (Workspace_sptr &loadedWs, Workspace_sptr deadTimes) +{ + ScopedWorkspace ws(loadedWs); + ScopedWorkspace dt(deadTimes); + + try + { + IAlgorithm_sptr applyCorr = AlgorithmManager::Instance().create("ApplyDeadTimeCorr"); + applyCorr->setLogging(false); + applyCorr->setRethrows(true); + applyCorr->setPropertyValue("InputWorkspace", ws.name()); + applyCorr->setPropertyValue("OutputWorkspace", ws.name()); + applyCorr->setProperty("DeadTimeTable", dt.name()); + applyCorr->execute(); + // Workspace should've been replaced in the ADS by ApplyDeadTimeCorr, so + // need to + // re-assign it + loadedWs = ws.retrieve(); + } + catch (...) + { + throw std::runtime_error("Unable to apply corrections\n"); + } +} + +/** Group detectors from specified file +* @param loadedWs :: [input/output] Workspace to apply grouping to +* @param loadedDetGrouping :: [input] Workspace storing detectors grouping +*/ +void PlotAsymmetryByLogValue::groupDetectors (Workspace_sptr &loadedWs, Workspace_sptr loadedDetGrouping) +{ + + // Could be groups of workspaces, so need to work with ADS + ScopedWorkspace inWS(loadedWs); + ScopedWorkspace grouping(loadedDetGrouping); + ScopedWorkspace outWS; + + try + { + IAlgorithm_sptr applyGrouping = AlgorithmManager::Instance().create("MuonGroupDetectors"); + applyGrouping->setLogging(false); + applyGrouping->setRethrows(true); + + applyGrouping->setPropertyValue("InputWorkspace", inWS.name()); + applyGrouping->setPropertyValue("DetectorGroupingTable", grouping.name()); + applyGrouping->setPropertyValue("OutputWorkspace", outWS.name()); + applyGrouping->execute(); + + loadedWs = outWS.retrieve(); + } + catch (...) + { + throw std::runtime_error("Unable to group detectors.\n\nPlease specify grouping manually."); + } +} /** Calculate the integral asymmetry for a workspace. * The calculation is done by MuonAsymmetryCalc and SimpleIntegration * algorithms. @@ -539,16 +630,14 @@ PlotAsymmetryByLogValue::groupDetectors(API::MatrixWorkspace_sptr &ws, * Get log value from a workspace. Convert to double if possible. * * @param ws :: The input workspace. - * @param logName :: Name of the log file. * @return :: Log value. * @throw :: std::invalid_argument if the log cannot be converted to a double or *doesn't exist. */ -double PlotAsymmetryByLogValue::getLogValue(MatrixWorkspace &ws, - const std::string &logName) { - auto *property = ws.run().getLogData(logName); +double PlotAsymmetryByLogValue::getLogValue(MatrixWorkspace &ws) { + auto *property = ws.run().getLogData(m_logName); if (!property) { - throw std::invalid_argument("Log " + logName + " does not exist."); + throw std::invalid_argument("Log " + m_logName + " does not exist."); } double value = 0; @@ -582,8 +671,11 @@ double PlotAsymmetryByLogValue::getLogValue(MatrixWorkspace &ws, } } - throw std::invalid_argument("Log " + logName + + throw std::invalid_argument("Log " + m_logName + " cannot be converted to a double type."); } + + + } // namespace Algorithm } // namespace Mantid From 689f3e6a9895fe1544351d00341d12e884145acd Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Mon, 19 Jan 2015 13:39:51 +0000 Subject: [PATCH 018/414] Unfix patch number for possible future patches --- Code/Mantid/Build/CMake/VersionNumber.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Build/CMake/VersionNumber.cmake b/Code/Mantid/Build/CMake/VersionNumber.cmake index 2c8f948b88ab..8d616616e39d 100644 --- a/Code/Mantid/Build/CMake/VersionNumber.cmake +++ b/Code/Mantid/Build/CMake/VersionNumber.cmake @@ -6,5 +6,5 @@ set ( VERSION_MINOR 3 ) # UNCOMMENT the next 'set' line to 'force' the patch version number to # a value (instead of using the count coming out of 'git describe') # DO NOT COMMIT THIS TO MASTER UNCOMMENTED, ONLY TO A RELEASE BRANCH -set ( VERSION_PATCH 0 ) +#set ( VERSION_PATCH 0 ) From d8a5f963b27dd4b34d33e806ca2137507ee5de84 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Fri, 23 Jan 2015 09:24:36 +0000 Subject: [PATCH 019/414] Re #10894 Fixing build plot asymmetry by log value --- .../Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp index aac17d5f3771..20afdb2e61f9 100644 --- a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp +++ b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp @@ -138,7 +138,7 @@ void PlotAsymmetryByLogValue::exec() { m_backward_list = getProperty("BackwardSpectra"); m_autogroup = (m_forward_list.size() == 0 && m_backward_list.size() == 0); // Get log value - m_logName = getProperty("LogValue"); + m_logName = getPropertyValue("LogValue"); // Get green and red periods int red = getProperty("Red"); int green = getProperty("Green"); From e7765fb7ffec4b6cd5e59a122e97812b6d05d8b9 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Wed, 28 Jan 2015 09:06:19 +0000 Subject: [PATCH 020/414] Re #9556 DKT base implementation --- .../Framework/CurveFitting/CMakeLists.txt | 2 + .../MantidCurveFitting/DynamicKuboToyabe.h | 72 +++++ .../CurveFitting/src/DynamicKuboToyabe.cpp | 245 ++++++++++++++++++ 3 files changed, 319 insertions(+) create mode 100644 Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h create mode 100644 Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp diff --git a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt index d48a4ac4a661..93d8e42f046a 100644 --- a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt +++ b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt @@ -29,6 +29,7 @@ set ( SRC_FILES src/DerivMinimizer.cpp src/DiffRotDiscreteCircle.cpp src/DiffSphere.cpp + src/DynamicKuboToyabe.cpp src/EndErfc.cpp src/ExpDecay.cpp src/ExpDecayMuon.cpp @@ -135,6 +136,7 @@ set ( INC_FILES inc/MantidCurveFitting/DiffRotDiscreteCircle.h inc/MantidCurveFitting/DiffSphere.h inc/MantidCurveFitting/DllConfig.h + inc/MantidCurveFitting/DynamicKuboToyabe.h inc/MantidCurveFitting/EndErfc.h inc/MantidCurveFitting/ExpDecay.h inc/MantidCurveFitting/ExpDecayMuon.h diff --git a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h new file mode 100644 index 000000000000..261905dc46ce --- /dev/null +++ b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h @@ -0,0 +1,72 @@ +#ifndef MANTID_CURVEFITTING_DYNAMICKUBOTOYABE_H_ +#define MANTID_CURVEFITTING_DYNAMICKUBOTOYABE_H_ + +//---------------------------------------------------------------------- +// Includes +//---------------------------------------------------------------------- +#include "MantidAPI/IPeakFunction.h" +#include "MantidAPI/IFunctionMW.h" +#include "MantidAPI/IFunctionWithLocation.h" +#include + +//#include "MantidAPI/ParamFunction.h" +//#include "MantidAPI/IPeakFunction.h" + +//#include "MantidAPI/IFunctionMW.h" +//#include "MantidAPI/IFunction1D.h" + +namespace Mantid +{ + namespace CurveFitting + { + /** + Provide Dynamic Kubo Toyabe function interface to IPeakFunction for muon scientists. + + @author Karl Palmen, ISIS, RAL + @date 21/03/2012 + + Copyright © 2007-2012 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory + + This file is part of Mantid. + + Mantid is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + Mantid is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + File change history is stored at: + Code Documentation is available at: + */ + + class DLLExport DynamicKuboToyabe : public API::ParamFunction, public API::IFunction1D + { + public: + + /// Destructor + virtual ~DynamicKuboToyabe() {} + + /// overwrite base class methods + std::string name()const{return "DynamicKuboToyabe";} + virtual const std::string category() const { return "Muon";} + + protected: + virtual void function1D(double* out, const double* xValues, const size_t nData)const; + virtual void functionDeriv1D(API::Jacobian* out, const double* xValues, const size_t nData); + virtual void functionDeriv(const API::FunctionDomain& domain, API::Jacobian& jacobian); + virtual void init(); + virtual void setActiveParameter(size_t i, double value); + + }; + + } // namespace CurveFitting +} // namespace Mantid + +#endif /*MANTID_CURVEFITTING_DYNAMICKUBOTOYABE_H_*/ \ No newline at end of file diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp new file mode 100644 index 000000000000..c3c00ca34cc1 --- /dev/null +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -0,0 +1,245 @@ +//---------------------------------------------------------------------- +// Includes +//---------------------------------------------------------------------- +#include "MantidCurveFitting/DynamicKuboToyabe.h" +#include "MantidAPI/Jacobian.h" +#include "MantidAPI/FunctionFactory.h" +#include +#include // TODO Remove + +#define EPS 1e-6 +#define JMAX 14 +#define JMAXP (JMAX+1) +#define K 5 +#define NR_END 1 +#define FREE_ARG char* + +namespace Mantid +{ +namespace CurveFitting +{ + +using namespace Kernel; +using namespace API; +using namespace boost::math; + +DECLARE_FUNCTION(DynamicKuboToyabe) + +// ** MODIFY THIS ** +// Here specify/declare the parameters of your Fit Function +// +// declareParameter takes three arguments: +// +// 1st: The name of the parameter +// 2nd: The default (initial) value of the parameter +// 3rd: A description of the parameter (optional) +// +void DynamicKuboToyabe::init() +{ + declareParameter("Asym", 0.2); + declareParameter("Delta", 0.2); + declareParameter("Field",0.0); + declareParameter("Nu",0.0); + //declareParameter("EndX",15); +} + + +//------------------------------------------------------------------------------------------------ +double *vector(long nl, long nh) +/* allocate a double vector with subscript range v[nl..nh] */ +{ + double *v; + + v=(double *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(double))); + if (!v) throw std::runtime_error("allocation failure in dvector()"); + return v-nl+NR_END; +} +void free_vector(double *v, long nl, long nh) +/* free a double vector allocated with dvector() */ +{ + free((FREE_ARG) (v+nl-NR_END)); +} +double midpnt(double func(const double, const double, const double), + const double a, const double b, const int n, const double g, const double w0) { +// quote & modified from numerical recipe 2nd edtion (page147) + + static double s; + + if (n==1) { + double s1 = 0.5*(b-a)*func(a,g,w0)+func(b,g,w0); + double s2 = (b-a)*func(0.5*(a+b),g,w0); + return (s2); + } else { + double x, tnm, sum, del, ddel; + int it, j; + for (it=1,j=1;j= K) { + polint(&h[j-K],&s[j-K],K,0.0,ss,dss); + if (fabs(dss) <= fabs(ss)) return ss; + } + h[j+1]=h[j]/9.0; + } + throw std::runtime_error("integrate(): Too many steps in routine integrate\n"); + return 0.0; +} + +//-------------------------------------------------------------------------------------------------------------------------------------- + + +double f1(const double x, const double G, const double w0) { + return( exp(-G*G*x*x/2)*sin(w0*x)); +} + +double ZFKT (double q){ + // In zero field: + // g(t) = 1/3 + 2/3 exp( -q/2 ) ( 1 - q ) + // q = t *sigma + return (0.3333333333 + 0.6666666667*exp(-0.5*q)*(1-q)); +} +double gz (const double x, const double G, const double F) +{ + double w0 = 2.0*3.1415926536*0.01355342*F; + const double q = G*G*x*x; + + if (w0 == 0.0) { + return (ZFKT(q)); + } + else { + + if (F>2.0*G) { w0 = 2*3.1415926*0.01355342*F ;} else { w0 =2*3.1415926*0.01355342*2.0*G; } + + double p = G*G/(w0*w0); + double HKT = 1.0-2.0*p*(1-exp(-q/2.0)*cos(w0*x))+2.0*p*p*w0*integrate(f1,0.0,x,G,w0); + if (F>2.0*G) {return (HKT);} + else {return (ZFKT(q)+ (F/2.0/G)*(HKT-ZFKT(q)));} + + } +} + +// Original function by mark telling +void DynamicKuboToyabe::function1D(double* out, const double* xValues, const size_t nData)const +{ + const double& A = getParameter("Asym"); + const double& G = fabs(getParameter("Delta")); + const double& F = fabs(getParameter("Field")); + const double& v = fabs(getParameter("Nu")); + + + // Zero hopping rate + if (v == 0.0) { + for (size_t i = 0; i < nData; i++) { + out[i] = A*gz(xValues[i],G,F); + } + } + + // Non-zero hopping rate + else { + + const int n = 1000; + const double stepsize = fabs(xValues[nData-1]/n); + // do{stepsizeTemp=stepsizeTemp/10;nTemp=nTemp*10; }while (xValues[0] funcG(n); + + for (int i = 0; i < n; i++) { + + double Integral=0.0; + for (int c = 1; c <= i; c++) { + Integral= gz(c*stepsize,G,F)*exp(-v*c*stepsize)*funcG[i-c]*(stepsize) + Integral; + } + funcG[i] = (gz(i*stepsize,G,F)*exp(-v*i*stepsize) + v*Integral); + } + + + for (size_t i = 0; i < nData; i++) { + double a =xValues[i]/stepsize; + out[i] = A*(funcG.at(int(a)-1)); + } + + } // else hopping rate != 0 + +} + + + +void DynamicKuboToyabe::functionDeriv(const API::FunctionDomain& domain, API::Jacobian& jacobian) +{ + calNumericalDeriv(domain, jacobian); +} + +void DynamicKuboToyabe::functionDeriv1D(API::Jacobian* , const double* , const size_t ) +{ + throw Mantid::Kernel::Exception::NotImplementedError("functionDerivLocal is not implemented for DynamicKuboToyabe."); +} + +void DynamicKuboToyabe::setActiveParameter(size_t i, double value) { + + setParameter( i, fabs(value), false); + +} + +} // namespace CurveFitting +} // namespace Mantid From fb9f1dce6329b9a624232841821980e6e350c7b7 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Wed, 28 Jan 2015 11:11:34 +0000 Subject: [PATCH 021/414] Re #9556 DKT updating parameter description --- .../CurveFitting/src/DynamicKuboToyabe.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index c3c00ca34cc1..bb8564563d19 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -36,10 +36,10 @@ DECLARE_FUNCTION(DynamicKuboToyabe) // void DynamicKuboToyabe::init() { - declareParameter("Asym", 0.2); - declareParameter("Delta", 0.2); - declareParameter("Field",0.0); - declareParameter("Nu",0.0); + declareParameter("Asym", 0.2, "Amplitude at time 0"); + declareParameter("Delta", 0.2, "Local field"); + declareParameter("Field", 0.0, "External field"); + declareParameter("Nu", 0.0, "Hopping rate"); //declareParameter("EndX",15); } @@ -197,13 +197,11 @@ void DynamicKuboToyabe::function1D(double* out, const double* xValues, const siz // Non-zero hopping rate else { - const int n = 1000; const double stepsize = fabs(xValues[nData-1]/n); // do{stepsizeTemp=stepsizeTemp/10;nTemp=nTemp*10; }while (xValues[0] funcG(n); - for (int i = 0; i < n; i++) { double Integral=0.0; @@ -216,7 +214,8 @@ void DynamicKuboToyabe::function1D(double* out, const double* xValues, const siz for (size_t i = 0; i < nData; i++) { double a =xValues[i]/stepsize; - out[i] = A*(funcG.at(int(a)-1)); + a = a Date: Wed, 28 Jan 2015 11:15:14 +0000 Subject: [PATCH 022/414] Re #9556 DKT documentation --- .../source/fitfunctions/DynamicKuboToyabe.rst | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst diff --git a/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst b/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst new file mode 100644 index 000000000000..206be446c5e1 --- /dev/null +++ b/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst @@ -0,0 +1,31 @@ +.. _func-DynamicKuboToyabe: + +================ +DynamicKuboToyabe +================ + +.. index:: DynamicKuboToyabe + +Description +----------- + +Dynamic Kubo Toyabe fitting function for use by Muon scientists defined +by + +.. math:: G_z \left(t\right) = g_z\left(t\right) e^{-\nu t} + \nu \int_0^t g_z\left(\tau\right) e^{-\nu\tau} G_z\left(t-\tau\right) d\tau + +where :math:`g_z\left(t\right)` is the static KT function. + +| In zero field, :math:`B_0=0`: + +.. math:: g_z\left(t\right) = \mbox{A} \Bigg[ \frac{1}{3} + \frac{2}{3} \left( 1 - {\Delta}^2 {t}^2 \right) e^{-\frac{1}{2}\Delta^2 t^2} \Bigg] + +| In the presence of a longitudinal field, :math:`B_0=\omega_0 /\gamma_{\mu}>0`: + +.. math:: g_z\left(t\right) = \mbox{A} \Bigg[ 1 - 2\frac{\Delta^2}{\omega_0^2}\Big(1-cos(\omega_0 t)e^{-\frac{1}{2}\Delta^2 t^2}\Big) + 2\frac{\Delta^4}{\omega_0^4}\omega_0\int_0^\tau \sin(\omega_0\tau)e^{-\frac{1}{2}\Delta^2\tau^2}d\tau \Bigg] + +.. attributes:: + +.. properties:: + +.. categories:: From 5868103f80f76603b289d0de43d54bc64db68e81 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Wed, 28 Jan 2015 11:21:24 +0000 Subject: [PATCH 023/414] Re #9556 DKT updating setActiveParameter --- .../Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index bb8564563d19..2729c173d96c 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -238,6 +238,12 @@ void DynamicKuboToyabe::setActiveParameter(size_t i, double value) { setParameter( i, fabs(value), false); + if (parameterName(i)=="Nu"){ + if (value<1e-10){ + setParameter(i,0,false); + } + } + } } // namespace CurveFitting From 5079fc94404a4323c0ff72bdc1849475707e862e Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Wed, 28 Jan 2015 11:48:55 +0000 Subject: [PATCH 024/414] Re #9556 DKT unit test --- .../Framework/CurveFitting/CMakeLists.txt | 1 + .../CurveFitting/test/DynamicKuboToyabeTest.h | 108 ++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h diff --git a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt index 93d8e42f046a..f493cf94d865 100644 --- a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt +++ b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt @@ -239,6 +239,7 @@ set ( TEST_FILES DeltaFunctionTest.h DiffRotDiscreteCircleTest.h DiffSphereTest.h + DynamicKuboToyabeTest.h EndErfcTest.h ExpDecayMuonTest.h ExpDecayOscTest.h diff --git a/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h new file mode 100644 index 000000000000..9331529860ca --- /dev/null +++ b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h @@ -0,0 +1,108 @@ +#ifndef DYNAMICKUBOTOYABETEST_H_ +#define DYNAMICKUBOTOYABETEST_H_ + +#include + +#include "MantidCurveFitting/DynamicKuboToyabe.h" +#include "MantidAPI/CompositeFunction.h" +#include "MantidCurveFitting/LinearBackground.h" +#include "MantidCurveFitting/BoundaryConstraint.h" +#include "MantidCurveFitting/Fit.h" +#include "MantidKernel/UnitFactory.h" +#include "MantidAPI/AnalysisDataService.h" +#include "MantidAPI/WorkspaceFactory.h" +#include "MantidAPI/Algorithm.h" +#include "MantidDataObjects/Workspace2D.h" +#include "MantidKernel/Exception.h" +#include "MantidAPI/FunctionFactory.h" + +using namespace Mantid::Kernel; +using namespace Mantid::API; +using namespace Mantid::CurveFitting; +using namespace Mantid::DataObjects; + + +class DynamicKuboToyabeTest : public CxxTest::TestSuite +{ +public: + + void getMockData(Mantid::MantidVec& y, Mantid::MantidVec& e) + { + // Calculated with A = 0.24 and Delta = 0.16 on an Excel spreadsheet + y[0] = 0.24; + y[1] = 0.233921146; + y[2] = 0.216447929; + y[3] = 0.189737312; + y[4] = 0.156970237; + y[5] = 0.121826185; + y[6] = 0.08791249; + y[7] = 0.058260598; + y[8] = 0.034976545; + y[9] = 0.019090369; + + for (int i = 0; i <10; i++) + { + e[i] = 0.01; + } + + } + + void testAgainstMockData() + { + Fit alg2; + TS_ASSERT_THROWS_NOTHING(alg2.initialize()); + TS_ASSERT( alg2.isInitialized() ); + + // create mock data to test against + std::string wsName = "DynamicKuboToyabeData"; + int histogramNumber = 1; + int timechannels = 10; + Workspace_sptr ws = WorkspaceFactory::Instance().create("Workspace2D",histogramNumber,timechannels,timechannels); + Workspace2D_sptr ws2D = boost::dynamic_pointer_cast(ws); + for (int i = 0; i < 10; i++) ws2D->dataX(0)[i] = i; + Mantid::MantidVec& y = ws2D->dataY(0); // y-values (counts) + Mantid::MantidVec& e = ws2D->dataE(0); // error values of counts + getMockData(y, e); + + //put this workspace in the data service + TS_ASSERT_THROWS_NOTHING(AnalysisDataService::Instance().addOrReplace(wsName, ws2D)); + + // set up fitting function +// DynamicKuboToyabe fn; + std::string fnString = "name=DynamicKuboToyabe,ties=(Field=0,Nu=0);"; + IFunction_sptr fn = FunctionFactory::Instance().createInitialized(fnString); + + //alg2.setFunction(fn); + TS_ASSERT_THROWS_NOTHING(alg2.setProperty("Function",fnString)); + + // Set which spectrum to fit against and initial starting values + TS_ASSERT_THROWS_NOTHING(alg2.setPropertyValue("InputWorkspace", wsName)); + TS_ASSERT_THROWS_NOTHING(alg2.setPropertyValue("WorkspaceIndex","0")); + TS_ASSERT_THROWS_NOTHING(alg2.setPropertyValue("StartX","0")); + TS_ASSERT_THROWS_NOTHING(alg2.setPropertyValue("EndX","17")); + + fn->applyTies(); + // execute fit + TS_ASSERT_THROWS_NOTHING( + TS_ASSERT( alg2.execute() ) + ) + + TS_ASSERT( alg2.isExecuted() ); + + auto out = FunctionFactory::Instance().createInitialized(alg2.getPropertyValue("Function")); + TS_ASSERT_DELTA( out->getParameter("Asym"), 0.238 ,0.001); + TS_ASSERT_DELTA( out->getParameter("Delta"), 0.157 ,0.001); + + // check its categories + const std::vector categories = out->categories(); + TS_ASSERT( categories.size() == 1 ); + TS_ASSERT( categories[0] == "Muon" ); + + AnalysisDataService::Instance().remove(wsName); + + } + + +}; + +#endif /*DYNAMICKUBOTOYABETEST_H_*/ From 605309210a73e32affc300ee4fcc88ea1e52e2c3 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Wed, 28 Jan 2015 16:26:52 +0000 Subject: [PATCH 025/414] Re #10886 Recover lost change in dead time type --- .../CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp b/Code/Mantid/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp index 4e14e4a4bca5..3d6fe444ee56 100644 --- a/Code/Mantid/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp +++ b/Code/Mantid/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp @@ -215,5 +215,5 @@ void PlotAsymmetryByLogValueDialog::fillLogBox(const QString&) void PlotAsymmetryByLogValueDialog::showHideDeadTimeFileWidget(int deadTimeTypeIndex) { // Show only if "Using specified file" selected - m_uiForm.dtcFileContainer->setVisible(deadTimeTypeIndex == 1); + m_uiForm.dtcFileContainer->setVisible(deadTimeTypeIndex == 2); } From b977abd27292f4937e4ec55d0a124740158e80c1 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Thu, 29 Jan 2015 15:35:42 +0000 Subject: [PATCH 026/414] Re #9556 Unit test testing function not fitting --- .../CurveFitting/test/DynamicKuboToyabeTest.h | 176 ++++++++++-------- 1 file changed, 97 insertions(+), 79 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h index 9331529860ca..490f07fd4d67 100644 --- a/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h @@ -4,102 +4,120 @@ #include #include "MantidCurveFitting/DynamicKuboToyabe.h" -#include "MantidAPI/CompositeFunction.h" -#include "MantidCurveFitting/LinearBackground.h" -#include "MantidCurveFitting/BoundaryConstraint.h" -#include "MantidCurveFitting/Fit.h" -#include "MantidKernel/UnitFactory.h" -#include "MantidAPI/AnalysisDataService.h" -#include "MantidAPI/WorkspaceFactory.h" -#include "MantidAPI/Algorithm.h" -#include "MantidDataObjects/Workspace2D.h" -#include "MantidKernel/Exception.h" -#include "MantidAPI/FunctionFactory.h" +#include "MantidCurveFitting/StaticKuboToyabe.h" +#include "MantidAPI/FunctionDomain1D.h" +#include "MantidAPI/FunctionValues.h" +//#include "MantidAPI/CompositeFunction.h" +//#include "MantidCurveFitting/LinearBackground.h" +//#include "MantidCurveFitting/BoundaryConstraint.h" +//#include "MantidCurveFitting/Fit.h" +//#include "MantidKernel/UnitFactory.h" +//#include "MantidAPI/AnalysisDataService.h" +//#include "MantidAPI/WorkspaceFactory.h" +//#include "MantidAPI/Algorithm.h" +//#include "MantidDataObjects/Workspace2D.h" +//#include "MantidKernel/Exception.h" +//#include "MantidAPI/FunctionFactory.h" using namespace Mantid::Kernel; using namespace Mantid::API; using namespace Mantid::CurveFitting; -using namespace Mantid::DataObjects; +//using namespace Mantid::DataObjects; class DynamicKuboToyabeTest : public CxxTest::TestSuite { public: - void getMockData(Mantid::MantidVec& y, Mantid::MantidVec& e) + void testZFZNDKTFunction() { - // Calculated with A = 0.24 and Delta = 0.16 on an Excel spreadsheet - y[0] = 0.24; - y[1] = 0.233921146; - y[2] = 0.216447929; - y[3] = 0.189737312; - y[4] = 0.156970237; - y[5] = 0.121826185; - y[6] = 0.08791249; - y[7] = 0.058260598; - y[8] = 0.034976545; - y[9] = 0.019090369; - - for (int i = 0; i <10; i++) + // Test Dynamic Kubo Toyabe (DKT) for Zero Field (ZF) and Zero Nu (ZN) + // Function values must match exactly values from the Static Kubo Toyabe + const double asym = 1.0; + const double delta = 0.39; + const double field = 0; + const double nu = 0.0; + + DynamicKuboToyabe dkt; + dkt.initialize(); + dkt.setParameter("Asym", asym); + dkt.setParameter("Delta",delta ); + dkt.setParameter("Field",field); + dkt.setParameter("Nu", nu); + + StaticKuboToyabe skt; + skt.initialize(); + skt.setParameter("A", asym); + skt.setParameter("Delta", delta); + + // define 1d domain of 10 points in interval [0,10] + Mantid::API::FunctionDomain1DVector x(0,10,10); + Mantid::API::FunctionValues y1(x); + Mantid::API::FunctionValues y2(x); + + dkt.function(x,y1); + skt.function(x,y2); + + for(size_t i = 0; i < x.size(); ++i) { - e[i] = 0.01; + TS_ASSERT_DELTA( y1[i], y2[i], 1e-6 ); } - } - void testAgainstMockData() + void testZFDKTFunction() { - Fit alg2; - TS_ASSERT_THROWS_NOTHING(alg2.initialize()); - TS_ASSERT( alg2.isInitialized() ); - - // create mock data to test against - std::string wsName = "DynamicKuboToyabeData"; - int histogramNumber = 1; - int timechannels = 10; - Workspace_sptr ws = WorkspaceFactory::Instance().create("Workspace2D",histogramNumber,timechannels,timechannels); - Workspace2D_sptr ws2D = boost::dynamic_pointer_cast(ws); - for (int i = 0; i < 10; i++) ws2D->dataX(0)[i] = i; - Mantid::MantidVec& y = ws2D->dataY(0); // y-values (counts) - Mantid::MantidVec& e = ws2D->dataE(0); // error values of counts - getMockData(y, e); - - //put this workspace in the data service - TS_ASSERT_THROWS_NOTHING(AnalysisDataService::Instance().addOrReplace(wsName, ws2D)); - - // set up fitting function -// DynamicKuboToyabe fn; - std::string fnString = "name=DynamicKuboToyabe,ties=(Field=0,Nu=0);"; - IFunction_sptr fn = FunctionFactory::Instance().createInitialized(fnString); - - //alg2.setFunction(fn); - TS_ASSERT_THROWS_NOTHING(alg2.setProperty("Function",fnString)); - - // Set which spectrum to fit against and initial starting values - TS_ASSERT_THROWS_NOTHING(alg2.setPropertyValue("InputWorkspace", wsName)); - TS_ASSERT_THROWS_NOTHING(alg2.setPropertyValue("WorkspaceIndex","0")); - TS_ASSERT_THROWS_NOTHING(alg2.setPropertyValue("StartX","0")); - TS_ASSERT_THROWS_NOTHING(alg2.setPropertyValue("EndX","17")); - - fn->applyTies(); - // execute fit - TS_ASSERT_THROWS_NOTHING( - TS_ASSERT( alg2.execute() ) - ) - - TS_ASSERT( alg2.isExecuted() ); - - auto out = FunctionFactory::Instance().createInitialized(alg2.getPropertyValue("Function")); - TS_ASSERT_DELTA( out->getParameter("Asym"), 0.238 ,0.001); - TS_ASSERT_DELTA( out->getParameter("Delta"), 0.157 ,0.001); - - // check its categories - const std::vector categories = out->categories(); - TS_ASSERT( categories.size() == 1 ); - TS_ASSERT( categories[0] == "Muon" ); - - AnalysisDataService::Instance().remove(wsName); + // Test Dynamic Kubo Toyabe (DKT) for Zero Field (ZF) (non-zero Nu) + const double asym = 1.0; + const double delta = 0.39; + const double field = 0; + const double nu = 1.0; + + DynamicKuboToyabe dkt; + dkt.initialize(); + dkt.setParameter("Asym", asym); + dkt.setParameter("Delta",delta ); + dkt.setParameter("Field",field); + dkt.setParameter("Nu", nu); + + // define 1d domain of 5 points in interval [0,5] + Mantid::API::FunctionDomain1DVector x(0,5,5); + Mantid::API::FunctionValues y(x); + + dkt.function(x,y); + + TS_ASSERT_DELTA( y[0], 1.000000, 0.000001); + TS_ASSERT_DELTA( y[1], 0.849898, 0.000001); + TS_ASSERT_DELTA( y[2], 0.621963, 0.000001); + TS_ASSERT_DELTA( y[3], 0.443612, 0.000001); + TS_ASSERT_DELTA( y[4], 0.317374, 0.000001); + } + void testDKTFunction() + { + // Test Dynamic Kubo Toyabe (DKT) (non-zero Field, non-zero Nu) + const double asym = 1.0; + const double delta = 0.39; + const double field = 0.1; + const double nu = 0.5; + + DynamicKuboToyabe dkt; + dkt.initialize(); + dkt.setParameter("Asym", asym); + dkt.setParameter("Delta",delta ); + dkt.setParameter("Field",field); + dkt.setParameter("Nu", nu); + + // define 1d domain of 5 points in interval [0,5] + Mantid::API::FunctionDomain1DVector x(0,5,5); + Mantid::API::FunctionValues y(x); + + dkt.function(x,y); + + TS_ASSERT_DELTA( y[0], 1.000000, 0.000001); + TS_ASSERT_DELTA( y[1], 0.816422, 0.000001); + TS_ASSERT_DELTA( y[2], 0.503185, 0.000001); + TS_ASSERT_DELTA( y[3], 0.274738, 0.000001); + TS_ASSERT_DELTA( y[4], 0.152792, 0.000001); } From 06a5cb2fc14eb76dc3f9fdf0100eab2ca4f9d35c Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Thu, 29 Jan 2015 16:40:10 +0000 Subject: [PATCH 027/414] Re #9556 Fitting function improvements --- .../CurveFitting/src/DynamicKuboToyabe.cpp | 94 ++++++++++--------- 1 file changed, 50 insertions(+), 44 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index 2729c173d96c..5a42e851af01 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -5,7 +5,8 @@ #include "MantidAPI/Jacobian.h" #include "MantidAPI/FunctionFactory.h" #include -#include // TODO Remove +#include +//#include // TODO Remove #define EPS 1e-6 #define JMAX 14 @@ -40,35 +41,21 @@ void DynamicKuboToyabe::init() declareParameter("Delta", 0.2, "Local field"); declareParameter("Field", 0.0, "External field"); declareParameter("Nu", 0.0, "Hopping rate"); - //declareParameter("EndX",15); } //------------------------------------------------------------------------------------------------ -double *vector(long nl, long nh) -/* allocate a double vector with subscript range v[nl..nh] */ -{ - double *v; +// Routines from Numerical Recipes - v=(double *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(double))); - if (!v) throw std::runtime_error("allocation failure in dvector()"); - return v-nl+NR_END; -} -void free_vector(double *v, long nl, long nh) -/* free a double vector allocated with dvector() */ -{ - free((FREE_ARG) (v+nl-NR_END)); -} double midpnt(double func(const double, const double, const double), const double a, const double b, const int n, const double g, const double w0) { // quote & modified from numerical recipe 2nd edtion (page147) static double s; - if (n==1) { - double s1 = 0.5*(b-a)*func(a,g,w0)+func(b,g,w0); - double s2 = (b-a)*func(0.5*(a+b),g,w0); - return (s2); + if (n==1) { + double s1 = (b-a)*func(0.5*(a+b),g,w0); + return (s1); } else { double x, tnm, sum, del, ddel; int it, j; @@ -93,11 +80,9 @@ void polint (double xa[], double ya[], int n, double x, double& y, double& dy) { int i, m, ns = 1; double den, dif, dift, ho, hp, w; - double *c,*d; - dif = fabs(x-xa[1]); - c = vector(1,n); - d = vector(1,n); + std::vector c(n+1); + std::vector d(n+1); for (i=1;i<=n;i++){ if((dift=fabs(x-xa[i]))2.0*G) { w0 = 2*3.1415926*0.01355342*F ;} else { w0 =2*3.1415926*0.01355342*2.0*G; } + // Non-zero field + + if (F>2.0*G) { + w0 = 2*3.1415926*0.01355342*F ; + } else { + w0 =2*3.1415926*0.01355342*2.0*G; + } double p = G*G/(w0*w0); double HKT = 1.0-2.0*p*(1-exp(-q/2.0)*cos(w0*x))+2.0*p*p*w0*integrate(f1,0.0,x,G,w0); @@ -179,7 +170,7 @@ double gz (const double x, const double G, const double F) } } -// Original function by mark telling +// Dynamic Kubo Toyabe function void DynamicKuboToyabe::function1D(double* out, const double* xValues, const size_t nData)const { const double& A = getParameter("Asym"); @@ -197,20 +188,41 @@ void DynamicKuboToyabe::function1D(double* out, const double* xValues, const siz // Non-zero hopping rate else { - const int n = 1000; + + // Make sure stepsize is smaller than spacing between xValues + int n = 1000; + //while (n funcG(n); + + // Mark's implementation for (int i = 0; i < n; i++) { - double Integral=0.0; - for (int c = 1; c <= i; c++) { - Integral= gz(c*stepsize,G,F)*exp(-v*c*stepsize)*funcG[i-c]*(stepsize) + Integral; + double efac1=exp(-v*stepsize); // survival prob for step + double efac2=(1.0-efac1); // hop prob ~ hoprate*step + + funcG[0]=gz(0,G,F); + funcG[1]=gz(stepsize,G,F); + + for(i=1; i Date: Fri, 30 Jan 2015 08:34:39 +0000 Subject: [PATCH 028/414] Re #9556 Removing unnecessary includes --- .../CurveFitting/test/DynamicKuboToyabeTest.h | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h index 490f07fd4d67..52cc405feda5 100644 --- a/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h @@ -7,22 +7,10 @@ #include "MantidCurveFitting/StaticKuboToyabe.h" #include "MantidAPI/FunctionDomain1D.h" #include "MantidAPI/FunctionValues.h" -//#include "MantidAPI/CompositeFunction.h" -//#include "MantidCurveFitting/LinearBackground.h" -//#include "MantidCurveFitting/BoundaryConstraint.h" -//#include "MantidCurveFitting/Fit.h" -//#include "MantidKernel/UnitFactory.h" -//#include "MantidAPI/AnalysisDataService.h" -//#include "MantidAPI/WorkspaceFactory.h" -//#include "MantidAPI/Algorithm.h" -//#include "MantidDataObjects/Workspace2D.h" -//#include "MantidKernel/Exception.h" -//#include "MantidAPI/FunctionFactory.h" using namespace Mantid::Kernel; using namespace Mantid::API; using namespace Mantid::CurveFitting; -//using namespace Mantid::DataObjects; class DynamicKuboToyabeTest : public CxxTest::TestSuite From fb46f0e48eaee8628548678550c1f08a98b4538d Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Fri, 30 Jan 2015 08:42:08 +0000 Subject: [PATCH 029/414] Re #9556 removing math --- Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index 5a42e851af01..54811c7ea9a1 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -4,9 +4,7 @@ #include "MantidCurveFitting/DynamicKuboToyabe.h" #include "MantidAPI/Jacobian.h" #include "MantidAPI/FunctionFactory.h" -#include #include -//#include // TODO Remove #define EPS 1e-6 #define JMAX 14 @@ -22,7 +20,6 @@ namespace CurveFitting using namespace Kernel; using namespace API; -using namespace boost::math; DECLARE_FUNCTION(DynamicKuboToyabe) From 257ba6d75666e1106da7968b90949c9930bf70be Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Fri, 30 Jan 2015 08:48:55 +0000 Subject: [PATCH 030/414] Re #9556 fixing cpp checks --- .../Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index 54811c7ea9a1..e3005d9c51c0 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -48,7 +48,6 @@ double midpnt(double func(const double, const double, const double), const double a, const double b, const int n, const double g, const double w0) { // quote & modified from numerical recipe 2nd edtion (page147) - static double s; if (n==1) { double s1 = (b-a)*func(0.5*(a+b),g,w0); @@ -68,6 +67,7 @@ double midpnt(double func(const double, const double, const double), sum += func(x,g,w0); x += del; } + static double s; s=(s+(b-a)*sum/tnm)/3.0; return s; } @@ -75,12 +75,13 @@ double midpnt(double func(const double, const double, const double), void polint (double xa[], double ya[], int n, double x, double& y, double& dy) { int i, m, ns = 1; - double den, dif, dift, ho, hp, w; + double dif; dif = fabs(x-xa[1]); std::vector c(n+1); std::vector d(n+1); for (i=1;i<=n;i++){ + double dift; if((dift=fabs(x-xa[i])) Date: Fri, 30 Jan 2015 09:10:21 +0000 Subject: [PATCH 031/414] Re #9556 remove unit test temporarily --- Code/Mantid/Framework/CurveFitting/CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt index f493cf94d865..93d8e42f046a 100644 --- a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt +++ b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt @@ -239,7 +239,6 @@ set ( TEST_FILES DeltaFunctionTest.h DiffRotDiscreteCircleTest.h DiffSphereTest.h - DynamicKuboToyabeTest.h EndErfcTest.h ExpDecayMuonTest.h ExpDecayOscTest.h From f4d713c85eb1b344541189658a9416fb5a8807ab Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Fri, 30 Jan 2015 10:35:11 +0000 Subject: [PATCH 032/414] Re #9556 Enabling some unit tests --- Code/Mantid/Framework/CurveFitting/CMakeLists.txt | 1 + .../CurveFitting/test/DynamicKuboToyabeTest.h | 10 +++++----- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt index 93d8e42f046a..f493cf94d865 100644 --- a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt +++ b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt @@ -239,6 +239,7 @@ set ( TEST_FILES DeltaFunctionTest.h DiffRotDiscreteCircleTest.h DiffSphereTest.h + DynamicKuboToyabeTest.h EndErfcTest.h ExpDecayMuonTest.h ExpDecayOscTest.h diff --git a/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h index 52cc405feda5..efddce67e31f 100644 --- a/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h @@ -43,8 +43,8 @@ class DynamicKuboToyabeTest : public CxxTest::TestSuite Mantid::API::FunctionValues y1(x); Mantid::API::FunctionValues y2(x); - dkt.function(x,y1); - skt.function(x,y2); + TS_ASSERT_THROWS_NOTHING(dkt.function(x,y1)); + TS_ASSERT_THROWS_NOTHING(skt.function(x,y2)); for(size_t i = 0; i < x.size(); ++i) { @@ -71,7 +71,7 @@ class DynamicKuboToyabeTest : public CxxTest::TestSuite Mantid::API::FunctionDomain1DVector x(0,5,5); Mantid::API::FunctionValues y(x); - dkt.function(x,y); + TS_ASSERT_THROWS_NOTHING(dkt.function(x,y)); TS_ASSERT_DELTA( y[0], 1.000000, 0.000001); TS_ASSERT_DELTA( y[1], 0.849898, 0.000001); @@ -80,7 +80,7 @@ class DynamicKuboToyabeTest : public CxxTest::TestSuite TS_ASSERT_DELTA( y[4], 0.317374, 0.000001); } - void testDKTFunction() + void xtestDKTFunction() { // Test Dynamic Kubo Toyabe (DKT) (non-zero Field, non-zero Nu) const double asym = 1.0; @@ -99,7 +99,7 @@ class DynamicKuboToyabeTest : public CxxTest::TestSuite Mantid::API::FunctionDomain1DVector x(0,5,5); Mantid::API::FunctionValues y(x); - dkt.function(x,y); + TS_ASSERT_THROWS_NOTHING(dkt.function(x,y)); TS_ASSERT_DELTA( y[0], 1.000000, 0.000001); TS_ASSERT_DELTA( y[1], 0.816422, 0.000001); From 1fa60d864765d9efdc6f090bfb02a78bc24869bd Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Fri, 30 Jan 2015 12:46:14 +0000 Subject: [PATCH 033/414] Re #9556 Some bugs fixed and unit test updated --- .../CurveFitting/src/DynamicKuboToyabe.cpp | 10 ++--- .../CurveFitting/test/DynamicKuboToyabeTest.h | 38 ++++++++++++++++--- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index e3005d9c51c0..f28e0f075a8e 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -48,10 +48,11 @@ double midpnt(double func(const double, const double, const double), const double a, const double b, const int n, const double g, const double w0) { // quote & modified from numerical recipe 2nd edtion (page147) + static double s; if (n==1) { - double s1 = (b-a)*func(0.5*(a+b),g,w0); - return (s1); + s = (b-a)*func(0.5*(a+b),g,w0); + return (s); } else { double x, tnm, sum, del, ddel; int it, j; @@ -67,7 +68,6 @@ double midpnt(double func(const double, const double, const double), sum += func(x,g,w0); x += del; } - static double s; s=(s+(b-a)*sum/tnm)/3.0; return s; } @@ -114,8 +114,8 @@ double integrate (double func(const double, const double, const double), int j; double ss,dss; double h[JMAXP+1], s[JMAXP]; - - h[0] = 1.0; + + h[1] = 1.0; for (j=1; j<= JMAX; j++) { s[j]=midpnt(func,a,b,j,g,w0); if (j >= K) { diff --git a/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h index efddce67e31f..0eaef5a0d20d 100644 --- a/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h @@ -80,7 +80,35 @@ class DynamicKuboToyabeTest : public CxxTest::TestSuite TS_ASSERT_DELTA( y[4], 0.317374, 0.000001); } - void xtestDKTFunction() + void testZNDKTFunction() + { + // Test Dynamic Kubo Toyabe (DKT) for non-zero Field and Zero Nu (ZN) + const double asym = 1.0; + const double delta = 0.39; + const double field = 0.1; + const double nu = 0.0; + + DynamicKuboToyabe dkt; + dkt.initialize(); + dkt.setParameter("Asym", asym); + dkt.setParameter("Delta",delta ); + dkt.setParameter("Field",field); + dkt.setParameter("Nu", nu); + + // define 1d domain of 5 points in interval [0,5] + Mantid::API::FunctionDomain1DVector x(0,5,5); + Mantid::API::FunctionValues y(x); + + TS_ASSERT_THROWS_NOTHING(dkt.function(x,y)); + + TS_ASSERT_DELTA( y[0], 1.000000, 0.000001); + TS_ASSERT_DELTA( y[1], 0.784636, 0.000001); + TS_ASSERT_DELTA( y[2], 0.353978, 0.000001); + TS_ASSERT_DELTA( y[3], 0.073286, 0.000001); + TS_ASSERT_DELTA( y[4], 0.055052, 0.000001); + } + + void testDKTFunction() { // Test Dynamic Kubo Toyabe (DKT) (non-zero Field, non-zero Nu) const double asym = 1.0; @@ -102,10 +130,10 @@ class DynamicKuboToyabeTest : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING(dkt.function(x,y)); TS_ASSERT_DELTA( y[0], 1.000000, 0.000001); - TS_ASSERT_DELTA( y[1], 0.816422, 0.000001); - TS_ASSERT_DELTA( y[2], 0.503185, 0.000001); - TS_ASSERT_DELTA( y[3], 0.274738, 0.000001); - TS_ASSERT_DELTA( y[4], 0.152792, 0.000001); + TS_ASSERT_DELTA( y[1], 0.822498, 0.000001); + TS_ASSERT_DELTA( y[2], 0.518536, 0.000001); + TS_ASSERT_DELTA( y[3], 0.295988, 0.000001); + TS_ASSERT_DELTA( y[4], 0.175489, 0.000001); } From 2326ed9831fc68d98c30115c7d4dd5563b494ed9 Mon Sep 17 00:00:00 2001 From: Andrei Savici Date: Fri, 30 Jan 2015 16:51:34 -0500 Subject: [PATCH 034/414] New CNCS geometry. Refs #11001 --- Code/Mantid/instrument/CNCS_Definition.xml | 102 +-- .../CNCS_Definition_20140808-20150129.xml | 729 ++++++++++++++++++ 2 files changed, 780 insertions(+), 51 deletions(-) create mode 100644 Code/Mantid/instrument/CNCS_Definition_20140808-20150129.xml diff --git a/Code/Mantid/instrument/CNCS_Definition.xml b/Code/Mantid/instrument/CNCS_Definition.xml index 9ba469baa2b1..aeb052269537 100644 --- a/Code/Mantid/instrument/CNCS_Definition.xml +++ b/Code/Mantid/instrument/CNCS_Definition.xml @@ -1,5 +1,5 @@ - + @@ -187,350 +187,350 @@ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + diff --git a/Code/Mantid/instrument/CNCS_Definition_20140808-20150129.xml b/Code/Mantid/instrument/CNCS_Definition_20140808-20150129.xml new file mode 100644 index 000000000000..cb3e5151f3d8 --- /dev/null +++ b/Code/Mantid/instrument/CNCS_Definition_20140808-20150129.xml @@ -0,0 +1,729 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 96e3a4c2482ff2d39a10084b4a61d716ce7aeaad Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Mon, 2 Feb 2015 08:16:21 +0000 Subject: [PATCH 035/414] Re #9556 Fixing title overline in rst --- Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst b/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst index 206be446c5e1..85aeb26ddd97 100644 --- a/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst +++ b/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst @@ -1,8 +1,8 @@ .. _func-DynamicKuboToyabe: -================ +================= DynamicKuboToyabe -================ +================= .. index:: DynamicKuboToyabe From f21317e6df5442a2c8cd0fc8bd9760627a59b934 Mon Sep 17 00:00:00 2001 From: Tobias Richter Date: Mon, 2 Feb 2015 15:48:19 +0100 Subject: [PATCH 036/414] add python-sphinx-bootstrap-theme That would require a version bump, but I've yet to understand this versioned directory hierarchy. --- .../deb/mantid-developer/mantid-developer-1.2.3/DEBIAN/control | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.3/DEBIAN/control b/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.3/DEBIAN/control index b8a48ac71c23..5d0abce474b7 100644 --- a/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.3/DEBIAN/control +++ b/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.3/DEBIAN/control @@ -3,7 +3,7 @@ Version: 1.2.3 Section: main Priority: optional Architecture: all -Depends: git, clang, cmake-qt-gui(>=2.8.12), qt4-qmake, qt4-dev-tools, libqt4-dbg, libpoco-dev(>=1.4.2), libboost-all-dev, libboost-dbg, libnexus0-dev, libgoogle-perftools-dev, libqwt5-qt4-dev, libqwtplot3d-qt4-dev, python-qt4-dev, libgsl0-dev, liboce-visualization-dev, libmuparser-dev, python-numpy, libssl-dev, libqscintilla2-dev, texlive,texlive-latex-extra, dvipng, libhdf4-dev, doxygen, python-sphinx, python-scipy, ipython-qtconsole (>=1.2.0), libhdf5-dev, libhdf4-dev, libpococrypto11-dbg, libpocodata11-dbg, libpocofoundation11-dbg, libpocomysql11-dbg, libpoconet11-dbg, libpoconetssl11-dbg, libpocoodbc11-dbg, libpocosqlite11-dbg, libpocoutil11-dbg, libpocoxml11-dbg, libpocozip11-dbg, python-qt4-dbg, qt4-default, ninja-build, libjsoncpp-dev, python-dateutil +Depends: git, clang, cmake-qt-gui(>=2.8.12), qt4-qmake, qt4-dev-tools, libqt4-dbg, libpoco-dev(>=1.4.2), libboost-all-dev, libboost-dbg, libnexus0-dev, libgoogle-perftools-dev, libqwt5-qt4-dev, libqwtplot3d-qt4-dev, python-qt4-dev, libgsl0-dev, liboce-visualization-dev, libmuparser-dev, python-numpy, libssl-dev, libqscintilla2-dev, texlive, texlive-latex-extra, dvipng, libhdf4-dev, doxygen, python-sphinx, python-scipy, ipython-qtconsole (>=1.2.0), libhdf5-dev, libhdf4-dev, libpococrypto11-dbg, libpocodata11-dbg, libpocofoundation11-dbg, libpocomysql11-dbg, libpoconet11-dbg, libpoconetssl11-dbg, libpocoodbc11-dbg, libpocosqlite11-dbg, libpocoutil11-dbg, libpocoxml11-dbg, libpocozip11-dbg, python-qt4-dbg, qt4-default, ninja-build, libjsoncpp-dev, python-dateutil, python-sphinx-bootstrap-theme Installed-Size: 0 Maintainer: Mantid Project Description: Installs all packages required for a Mantid developer From 6ae76a4695198ea69d5f24fb53d028e17d5af271 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Thu, 5 Feb 2015 12:04:45 +0000 Subject: [PATCH 037/414] Fix UI issues in calibration tab Refs #10513 --- .../Indirect/IndirectCalibration.h | 1 - .../Indirect/IndirectCalibration.ui | 6 +++++ .../src/Indirect/IndirectCalibration.cpp | 25 +++---------------- 3 files changed, 9 insertions(+), 23 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.h index c01b42bbd5d2..a878370e0f69 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.h @@ -48,7 +48,6 @@ namespace CustomInterfaces virtual bool validate(); private slots: - void algorithmsComplete(bool error); void calPlotRaw(); void calPlotEnergy(); void calMinChanged(double); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.ui index adbfa401df8b..01698de191a2 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.ui @@ -75,6 +75,9 @@ 999.990000000000009 + + 1.0 + @@ -161,6 +164,9 @@ 999.990000000000009 + + 1.0 + diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp index cedeaa92d211..f49891b9a7b3 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp @@ -165,8 +165,6 @@ namespace CustomInterfaces void IndirectCalibration::run() { - connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(algorithmsComplete(bool))); - // Get properties QString firstFile = m_uiForm.leRunNo->getFirstFilename(); QString filenames = m_uiForm.leRunNo->getFilenames().join(","); @@ -224,10 +222,6 @@ namespace CustomInterfaces { QString resolutionWsName = outputWorkspaceNameStem + "_res"; - QString scaleFactor("1.0"); - if(m_uiForm.ckResolutionScale->isChecked() && !m_uiForm.spResolutionScale->text().isEmpty()) - scaleFactor = m_uiForm.spResolutionScale->text(); - QString resDetectorRange = QString::number(m_dblManager->value(m_properties["ResSpecMin"])) + "," + QString::number(m_dblManager->value(m_properties["ResSpecMax"])); @@ -249,12 +243,14 @@ namespace CustomInterfaces resAlg->setProperty("RebinParam", rebinString.toStdString()); resAlg->setProperty("DetectorRange", resDetectorRange.toStdString()); resAlg->setProperty("BackgroundRange", background.toStdString()); - resAlg->setProperty("ScaleFactor", m_uiForm.spScale->value()); resAlg->setProperty("Smooth", m_uiForm.ckSmoothResolution->isChecked()); resAlg->setProperty("Verbose", m_uiForm.ckVerbose->isChecked()); resAlg->setProperty("Plot", m_uiForm.ckPlot->isChecked()); resAlg->setProperty("Save", m_uiForm.ckSave->isChecked()); + if(m_uiForm.ckResolutionScale->isChecked()) + resAlg->setProperty("ScaleFactor", m_uiForm.spScale->value()); + m_batchAlgoRunner->addAlgorithm(resAlg); // When creating resolution file take the resolution workspace as the result @@ -264,21 +260,6 @@ namespace CustomInterfaces m_batchAlgoRunner->executeBatchAsync(); } - void IndirectCalibration::algorithmsComplete(bool error) - { - if(error) - return; - - QString firstFile = m_uiForm.leRunNo->getFirstFilename(); - QFileInfo firstFileInfo(firstFile); - /* QString calFileName = firstFileInfo.baseName() + "_" + m_uiForm.iicInstrumentConfiguration->getAnalyserName() + m_uiForm.iicInstrumentConfiguration->getReflectionName() + "_calib.nxs"; */ - - /* m_uiForm.ind_calibFile->setFileTextWithSearch(calFileName); */ - /* m_uiForm.ckUseCalib->setChecked(true); */ - - disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(algorithmsComplete(bool))); - } - bool IndirectCalibration::validate() { MantidQt::CustomInterfaces::UserInputValidator uiv; From 995ce4a0b2b40dbbbf13d977f60447ef636e0546 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Thu, 5 Feb 2015 12:29:16 +0000 Subject: [PATCH 038/414] Support plotting both pre and post scale on res Refs #10513 --- .../WorkflowAlgorithms/IndirectResolution.py | 9 ---- .../Indirect/IndirectCalibration.h | 1 + .../src/Indirect/IndirectCalibration.cpp | 42 +++++++++++++++++-- .../algorithms/IndirectResolution-v1.rst | 2 - 4 files changed, 40 insertions(+), 14 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py index 38fb54891c2e..ba5a95326fba 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py @@ -38,7 +38,6 @@ def PyInit(self): self.declareProperty(name='RebinParam', defaultValue='', doc='Rebinning parameters (min,width,max)') self.declareProperty(name='ScaleFactor', defaultValue=1.0, doc='Factor to scale resolution curve by') - self.declareProperty(name='Smooth', defaultValue=False, doc='Apply WienerSmooth to resolution') self.declareProperty(name='Verbose', defaultValue=False, doc='Print more information to results log') self.declareProperty(name='Plot', defaultValue=False, doc='Plot resolution curve') @@ -75,11 +74,6 @@ def PyExec(self): Rebin(InputWorkspace=self._out_ws, OutputWorkspace=self._out_ws, Params=self._rebin_string) - if self._smooth: - WienerSmooth(InputWorkspace=self._out_ws, OutputWorkspace='__smooth_temp') - CopyLogs(InputWorkspace=self._out_ws, OutputWorkspace='__smooth_temp') - RenameWorkspace(InputWorkspace='__smooth_temp', OutputWorkspace=self._out_ws) - self._post_process() self.setProperty('OutputWorkspace', self._out_ws) @@ -102,7 +96,6 @@ def _setup(self): self._background = self.getProperty('BackgroundRange').value self._rebin_string = self.getProperty('RebinParam').value self._scale_factor = self.getProperty('ScaleFactor').value - self._smooth = self.getProperty('Smooth').value self._verbose = self.getProperty('Verbose').value self._plot = self.getProperty('Plot').value @@ -119,8 +112,6 @@ def _post_process(self): if use_scale_factor: AddSampleLog(Workspace=self._out_ws, LogName='scale_factor', LogType='Number', LogText=str(self._scale_factor)) - AddSampleLog(Workspace=self._out_ws, LogName='res_smoothing_applied', LogType='String', LogText=str(self._smooth)) - AddSampleLog(Workspace=self._out_ws, LogName='back_start', LogType='Number', LogText=str(self._background[0])) AddSampleLog(Workspace=self._out_ws, LogName='back_end', LogType='Number', LogText=str(self._background[1])) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.h index a878370e0f69..295f3e5229b3 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.h @@ -48,6 +48,7 @@ namespace CustomInterfaces virtual bool validate(); private slots: + void algorithmComplete(bool error); void calPlotRaw(); void calPlotEnergy(); void calMinChanged(double); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp index f49891b9a7b3..da7ccae4204c 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp @@ -150,6 +150,8 @@ namespace CustomInterfaces // Nudge resCheck to ensure res range selectors are only shown when Create RES file is checked resCheck(m_uiForm.ckCreateResolution->isChecked()); + + connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(algorithmComplete(bool))); } //---------------------------------------------------------------------------------------------- @@ -232,27 +234,48 @@ namespace CustomInterfaces QString background = QString::number(m_dblManager->value(m_properties["ResStart"])) + "," + QString::number(m_dblManager->value(m_properties["ResEnd"])); + bool smooth = m_uiForm.ckSmoothResolution->isChecked(); + Mantid::API::IAlgorithm_sptr resAlg = Mantid::API::AlgorithmManager::Instance().create("IndirectResolution", -1); resAlg->initialize(); resAlg->setProperty("InputFiles", filenames.toStdString()); - resAlg->setProperty("OutputWorkspace", resolutionWsName.toStdString()); resAlg->setProperty("Instrument", getInstrumentConfiguration()->getInstrumentName().toStdString()); resAlg->setProperty("Analyser", getInstrumentConfiguration()->getAnalyserName().toStdString()); resAlg->setProperty("Reflection", getInstrumentConfiguration()->getReflectionName().toStdString()); resAlg->setProperty("RebinParam", rebinString.toStdString()); resAlg->setProperty("DetectorRange", resDetectorRange.toStdString()); resAlg->setProperty("BackgroundRange", background.toStdString()); - resAlg->setProperty("Smooth", m_uiForm.ckSmoothResolution->isChecked()); resAlg->setProperty("Verbose", m_uiForm.ckVerbose->isChecked()); - resAlg->setProperty("Plot", m_uiForm.ckPlot->isChecked()); resAlg->setProperty("Save", m_uiForm.ckSave->isChecked()); if(m_uiForm.ckResolutionScale->isChecked()) resAlg->setProperty("ScaleFactor", m_uiForm.spScale->value()); + if(smooth) + { + resAlg->setProperty("OutputWorkspace", resolutionWsName.toStdString() + "_pre_smooth"); + } + else + { + resAlg->setProperty("OutputWorkspace", resolutionWsName.toStdString()); + resAlg->setProperty("Plot", m_uiForm.ckPlot->isChecked()); + } + m_batchAlgoRunner->addAlgorithm(resAlg); + if(smooth) + { + Mantid::API::IAlgorithm_sptr smoothAlg = Mantid::API::AlgorithmManager::Instance().create("WienerSmooth"); + smoothAlg->initialize(); + smoothAlg->setProperty("OutputWorkspace", resolutionWsName.toStdString()); + + BatchAlgorithmRunner::AlgorithmRuntimeProps smoothAlgInputProps; + smoothAlgInputProps["InputWorkspace"] = resolutionWsName.toStdString() + "_pre_smooth"; + + m_batchAlgoRunner->addAlgorithm(smoothAlg, smoothAlgInputProps); + } + // When creating resolution file take the resolution workspace as the result m_pythonExportWsName = resolutionWsName.toStdString(); } @@ -260,6 +283,19 @@ namespace CustomInterfaces m_batchAlgoRunner->executeBatchAsync(); } + void IndirectCalibration::algorithmComplete(bool error) + { + if(error) + return; + + // Plot the smoothed workspace if required + if(m_uiForm.ckSmoothResolution->isChecked() && m_uiForm.ckPlot->isChecked()) + { + std::string pyInput = "from mantidplot import plotSpectrum\nplotSpectrum(['" + m_pythonExportWsName + "', '" + m_pythonExportWsName + "_pre_smooth'], 0)\n"; + m_pythonRunner.runPythonCode(QString::fromStdString(pyInput)); + } + } + bool IndirectCalibration::validate() { MantidQt::CustomInterfaces::UserInputValidator uiv; diff --git a/Code/Mantid/docs/source/algorithms/IndirectResolution-v1.rst b/Code/Mantid/docs/source/algorithms/IndirectResolution-v1.rst index 27efd1d06062..6bb35679ff6e 100644 --- a/Code/Mantid/docs/source/algorithms/IndirectResolution-v1.rst +++ b/Code/Mantid/docs/source/algorithms/IndirectResolution-v1.rst @@ -11,8 +11,6 @@ Description Creates a resolution workspace for an inelastic indirect sample run. -See `Indirect:Calibration `_. - Usage ----- From fe24fcdb29cbb90d1cf945246d4ce7364879b0b9 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Thu, 5 Feb 2015 13:13:02 +0000 Subject: [PATCH 039/414] Re #10894 Removing try blocks that hide actual error messages --- .../src/PlotAsymmetryByLogValue.cpp | 71 +++++++------------ 1 file changed, 26 insertions(+), 45 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp index 20afdb2e61f9..bc9cb6bda5c6 100644 --- a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp +++ b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp @@ -304,16 +304,11 @@ void PlotAsymmetryByLogValue::exec() { */ void PlotAsymmetryByLogValue::loadCorrectionsFromFile (Workspace_sptr &customDeadTimes, std::string deadTimeFile ) { - try{ - IAlgorithm_sptr loadDeadTimes = createChildAlgorithm("LoadNexusProcessed"); - loadDeadTimes->setPropertyValue("Filename", deadTimeFile); - loadDeadTimes->setProperty("OutputWorkspace", customDeadTimes); - loadDeadTimes->executeAsChildAlg(); - customDeadTimes = loadDeadTimes->getProperty("OutputWorkspace"); - } - catch (...){ - throw std::runtime_error("Unable to load corrections from specified file\n"); - } + IAlgorithm_sptr loadDeadTimes = createChildAlgorithm("LoadNexusProcessed"); + loadDeadTimes->setPropertyValue("Filename", deadTimeFile); + loadDeadTimes->setProperty("OutputWorkspace", customDeadTimes); + loadDeadTimes->executeAsChildAlg(); + customDeadTimes = loadDeadTimes->getProperty("OutputWorkspace"); } /** Populate output workspace with results * @param outWS :: [input/output] Output workspace to populate @@ -397,24 +392,17 @@ void PlotAsymmetryByLogValue::applyDeadtimeCorr (Workspace_sptr &loadedWs, Works ScopedWorkspace ws(loadedWs); ScopedWorkspace dt(deadTimes); - try - { - IAlgorithm_sptr applyCorr = AlgorithmManager::Instance().create("ApplyDeadTimeCorr"); - applyCorr->setLogging(false); - applyCorr->setRethrows(true); - applyCorr->setPropertyValue("InputWorkspace", ws.name()); - applyCorr->setPropertyValue("OutputWorkspace", ws.name()); - applyCorr->setProperty("DeadTimeTable", dt.name()); - applyCorr->execute(); - // Workspace should've been replaced in the ADS by ApplyDeadTimeCorr, so - // need to - // re-assign it - loadedWs = ws.retrieve(); - } - catch (...) - { - throw std::runtime_error("Unable to apply corrections\n"); - } + IAlgorithm_sptr applyCorr = AlgorithmManager::Instance().create("ApplyDeadTimeCorr"); + applyCorr->setLogging(false); + applyCorr->setRethrows(true); + applyCorr->setPropertyValue("InputWorkspace", ws.name()); + applyCorr->setPropertyValue("OutputWorkspace", ws.name()); + applyCorr->setProperty("DeadTimeTable", dt.name()); + applyCorr->execute(); + // Workspace should've been replaced in the ADS by ApplyDeadTimeCorr, so + // need to + // re-assign it + loadedWs = ws.retrieve(); } /** Group detectors from specified file @@ -429,23 +417,16 @@ void PlotAsymmetryByLogValue::groupDetectors (Workspace_sptr &loadedWs, Workspac ScopedWorkspace grouping(loadedDetGrouping); ScopedWorkspace outWS; - try - { - IAlgorithm_sptr applyGrouping = AlgorithmManager::Instance().create("MuonGroupDetectors"); - applyGrouping->setLogging(false); - applyGrouping->setRethrows(true); - - applyGrouping->setPropertyValue("InputWorkspace", inWS.name()); - applyGrouping->setPropertyValue("DetectorGroupingTable", grouping.name()); - applyGrouping->setPropertyValue("OutputWorkspace", outWS.name()); - applyGrouping->execute(); - - loadedWs = outWS.retrieve(); - } - catch (...) - { - throw std::runtime_error("Unable to group detectors.\n\nPlease specify grouping manually."); - } + IAlgorithm_sptr applyGrouping = AlgorithmManager::Instance().create("MuonGroupDetectors"); + applyGrouping->setLogging(false); + applyGrouping->setRethrows(true); + + applyGrouping->setPropertyValue("InputWorkspace", inWS.name()); + applyGrouping->setPropertyValue("DetectorGroupingTable", grouping.name()); + applyGrouping->setPropertyValue("OutputWorkspace", outWS.name()); + applyGrouping->execute(); + + loadedWs = outWS.retrieve(); } /** Calculate the integral asymmetry for a workspace. * The calculation is done by MuonAsymmetryCalc and SimpleIntegration From ffa2bbf490fc0d66d997252348285cf975acca4b Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Mon, 9 Feb 2015 09:47:49 +0000 Subject: [PATCH 040/414] Move performance test code to Testing directory. The system tests will be added here so it makes sense to have all of this in one place. Refs #10870 --- {Test => Code/Mantid/Testing}/PerformanceTests/.gitignore | 0 .../PerformanceTests/Mantid.systemtests.properties.template | 0 {Test => Code/Mantid/Testing}/PerformanceTests/README.txt | 0 {Test => Code/Mantid/Testing}/PerformanceTests/analysis.py | 0 .../Mantid/Testing}/PerformanceTests/check_performance.py | 0 {Test => Code/Mantid/Testing}/PerformanceTests/make_report.py | 0 {Test => Code/Mantid/Testing}/PerformanceTests/reporters.py | 0 {Test => Code/Mantid/Testing}/PerformanceTests/setup.py | 0 {Test => Code/Mantid/Testing}/PerformanceTests/sqlresults.py | 0 {Test => Code/Mantid/Testing}/PerformanceTests/testresult.py | 0 {Test => Code/Mantid/Testing}/PerformanceTests/xunit_to_sql.py | 0 11 files changed, 0 insertions(+), 0 deletions(-) rename {Test => Code/Mantid/Testing}/PerformanceTests/.gitignore (100%) rename {Test => Code/Mantid/Testing}/PerformanceTests/Mantid.systemtests.properties.template (100%) rename {Test => Code/Mantid/Testing}/PerformanceTests/README.txt (100%) rename {Test => Code/Mantid/Testing}/PerformanceTests/analysis.py (100%) rename {Test => Code/Mantid/Testing}/PerformanceTests/check_performance.py (100%) rename {Test => Code/Mantid/Testing}/PerformanceTests/make_report.py (100%) rename {Test => Code/Mantid/Testing}/PerformanceTests/reporters.py (100%) rename {Test => Code/Mantid/Testing}/PerformanceTests/setup.py (100%) rename {Test => Code/Mantid/Testing}/PerformanceTests/sqlresults.py (100%) rename {Test => Code/Mantid/Testing}/PerformanceTests/testresult.py (100%) rename {Test => Code/Mantid/Testing}/PerformanceTests/xunit_to_sql.py (100%) diff --git a/Test/PerformanceTests/.gitignore b/Code/Mantid/Testing/PerformanceTests/.gitignore similarity index 100% rename from Test/PerformanceTests/.gitignore rename to Code/Mantid/Testing/PerformanceTests/.gitignore diff --git a/Test/PerformanceTests/Mantid.systemtests.properties.template b/Code/Mantid/Testing/PerformanceTests/Mantid.systemtests.properties.template similarity index 100% rename from Test/PerformanceTests/Mantid.systemtests.properties.template rename to Code/Mantid/Testing/PerformanceTests/Mantid.systemtests.properties.template diff --git a/Test/PerformanceTests/README.txt b/Code/Mantid/Testing/PerformanceTests/README.txt similarity index 100% rename from Test/PerformanceTests/README.txt rename to Code/Mantid/Testing/PerformanceTests/README.txt diff --git a/Test/PerformanceTests/analysis.py b/Code/Mantid/Testing/PerformanceTests/analysis.py similarity index 100% rename from Test/PerformanceTests/analysis.py rename to Code/Mantid/Testing/PerformanceTests/analysis.py diff --git a/Test/PerformanceTests/check_performance.py b/Code/Mantid/Testing/PerformanceTests/check_performance.py similarity index 100% rename from Test/PerformanceTests/check_performance.py rename to Code/Mantid/Testing/PerformanceTests/check_performance.py diff --git a/Test/PerformanceTests/make_report.py b/Code/Mantid/Testing/PerformanceTests/make_report.py similarity index 100% rename from Test/PerformanceTests/make_report.py rename to Code/Mantid/Testing/PerformanceTests/make_report.py diff --git a/Test/PerformanceTests/reporters.py b/Code/Mantid/Testing/PerformanceTests/reporters.py similarity index 100% rename from Test/PerformanceTests/reporters.py rename to Code/Mantid/Testing/PerformanceTests/reporters.py diff --git a/Test/PerformanceTests/setup.py b/Code/Mantid/Testing/PerformanceTests/setup.py similarity index 100% rename from Test/PerformanceTests/setup.py rename to Code/Mantid/Testing/PerformanceTests/setup.py diff --git a/Test/PerformanceTests/sqlresults.py b/Code/Mantid/Testing/PerformanceTests/sqlresults.py similarity index 100% rename from Test/PerformanceTests/sqlresults.py rename to Code/Mantid/Testing/PerformanceTests/sqlresults.py diff --git a/Test/PerformanceTests/testresult.py b/Code/Mantid/Testing/PerformanceTests/testresult.py similarity index 100% rename from Test/PerformanceTests/testresult.py rename to Code/Mantid/Testing/PerformanceTests/testresult.py diff --git a/Test/PerformanceTests/xunit_to_sql.py b/Code/Mantid/Testing/PerformanceTests/xunit_to_sql.py similarity index 100% rename from Test/PerformanceTests/xunit_to_sql.py rename to Code/Mantid/Testing/PerformanceTests/xunit_to_sql.py From 370128b1caea837d9199f3e3ed52c3c54160d334 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 9 Feb 2015 10:26:04 +0000 Subject: [PATCH 041/414] Initial work on prevew plot widget Refs #11036 --- .../src/Indirect/IndirectTransmission.cpp | 12 +- .../MantidQt/MantidWidgets/CMakeLists.txt | 2 + .../inc/MantidQtMantidWidgets/PreviewPlot.h | 109 ++++++++++++ .../MantidWidgets/src/PreviewPlot.cpp | 159 ++++++++++++++++++ 4 files changed, 280 insertions(+), 2 deletions(-) create mode 100644 Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h create mode 100644 Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp index 9fb077517a60..f68ec15caae4 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp @@ -2,6 +2,8 @@ #include +#include "MantidQtMantidWidgets/PreviewPlot.h" + using namespace Mantid::API; namespace MantidQt @@ -18,11 +20,17 @@ namespace CustomInterfaces m_uiForm.setupUi(parent); // Preview plot - m_plots["PreviewPlot"] = new QwtPlot(m_parentWidget); + m_plots["PreviewPlot"] = new QwtPlot(0); //m_parentWidget); m_plots["PreviewPlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); m_plots["PreviewPlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); m_plots["PreviewPlot"]->setCanvasBackground(Qt::white); - m_uiForm.plotPreview->addWidget(m_plots["PreviewPlot"]); + /* m_uiForm.plotPreview->addWidget(m_plots["PreviewPlot"]); */ + + //TODO + MantidWidgets::PreviewPlot *plot = new MantidWidgets::PreviewPlot(m_parentWidget); + plot->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + plot->setCanvasColour(Qt::white); + m_uiForm.plotPreview->addWidget(plot); // Update the preview plot when the algorithm is complete connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(transAlgDone(bool))); diff --git a/Code/Mantid/MantidQt/MantidWidgets/CMakeLists.txt b/Code/Mantid/MantidQt/MantidWidgets/CMakeLists.txt index 8bac847f43c7..db06cce1eb4b 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/CMakeLists.txt +++ b/Code/Mantid/MantidQt/MantidWidgets/CMakeLists.txt @@ -40,6 +40,7 @@ set ( SRC_FILES src/UserFunctionDialog.cpp src/WorkspaceEditorFactory.cpp src/WorkspaceSelector.cpp + src/PreviewPlot.cpp src/pqHelpWindow.cxx src/pythonCalc.cpp src/LineEditWithClear.cpp @@ -72,6 +73,7 @@ set ( MOC_FILES inc/MantidQtMantidWidgets/MWRunFiles.h inc/MantidQtMantidWidgets/PeakPicker.h inc/MantidQtMantidWidgets/pqHelpWindow.h + inc/MantidQtMantidWidgets/PreviewPlot.h inc/MantidQtMantidWidgets/PropertyHandler.h inc/MantidQtMantidWidgets/ProcessingAlgoWidget.h inc/MantidQtMantidWidgets/pythonCalc.h diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h new file mode 100644 index 000000000000..4a31c9d75049 --- /dev/null +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -0,0 +1,109 @@ +#ifndef MANTIDQTMANTIDWIDGETS_PREVIEWPLOT_H_ +#define MANTIDQTMANTIDWIDGETS_PREVIEWPLOT_H_ + +#include "WidgetDllOption.h" +#include "MantidQtAPI/MantidWidget.h" + +#include "MantidAPI/MatrixWorkspace.h" + +#include +#include +#include +#include +#include + + +namespace MantidQt +{ +namespace MantidWidgets +{ + /** + A widget to display several workspaces on a plot on a custom interface. + + Gives option to use pan and zoom options to navigate plot. + + @author Dan Nixon + + Copyright © 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source + + This file is part of Mantid. + + Mantid is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + Mantid is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + File change history is stored at: + Code Documentation is available at: + */ + + class EXPORT_OPT_MANTIDQT_MANTIDWIDGETS PreviewPlot : public API::MantidWidget + { + Q_OBJECT + + Q_PROPERTY(QColor canvasColour READ canvasColour WRITE setCanvasColour) + Q_PROPERTY(bool allowPan READ allowPan WRITE setAllowPan) + Q_PROPERTY(bool allowZoom READ allowZoom WRITE setAllowZoom) + + public: + PreviewPlot(QWidget *parent = NULL, bool init = true); + virtual ~PreviewPlot(); + + QColor canvasColour(); + void setCanvasColour(const QColor & colour); + + bool allowPan(); + void setAllowPan(bool allow); + + bool allowZoom(); + void setAllowZoom(bool allow); + + void addSpectra(Mantid::API::MatrixWorkspace_sptr ws, int specIndex = 0); + void addSpectra(const QString & wsName, int specIndex = 0); + + void removeSpectra(Mantid::API::MatrixWorkspace_sptr ws); + void removeSpectra(const QString & wsName); + + void replot(); + + private: + void handleRemoveEvent(Mantid::API::WorkspacePreDeleteNotification_ptr pNf); + void handleReplaceEvent(Mantid::API::WorkspaceAfterReplaceNotification_ptr pNf); + + private: + /// Poco Observers for ADS Notifications + Poco::NObserver m_removeObserver; + Poco::NObserver m_replaceObserver; + + /// If the widget was initialised + bool m_init; + + /// If the plot manipulation tools are allowed + bool m_allowPan; + bool m_allowZoom; + + /// The plot its self + QwtPlot *m_plot; + + /// Map of workspaces to plot curves + QMap m_curves; + + /// Plot manipulation tools + QwtPlotMagnifier *m_magnifyTool; + QwtPlotPanner *m_panTool; + QwtPlotZoomer *m_zoomTool; + + }; + +} +} + +#endif //MANTIDQTMANTIDWIDGETS_PREVIEWPLOT_H_ diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp new file mode 100644 index 000000000000..5a053fc95e51 --- /dev/null +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -0,0 +1,159 @@ +//------------------------------------------------------ +// Includes +//------------------------------------------------------ +#include "MantidQtMantidWidgets/PreviewPlot.h" + +#include +#include +#include +#include + +#include +#include + +using namespace MantidQt::MantidWidgets; + + +PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent), + m_removeObserver(*this, &PreviewPlot::handleRemoveEvent), + m_replaceObserver(*this, &PreviewPlot::handleReplaceEvent), + m_init(init), m_allowPan(false), m_allowZoom(false), + m_plot(NULL), m_curves(), + m_magnifyTool(NULL), m_panTool(NULL), m_zoomTool(NULL) +{ + if(init) + { + Mantid::API::AnalysisDataServiceImpl& ads = Mantid::API::AnalysisDataService::Instance(); + ads.notificationCenter.addObserver(m_removeObserver); + ads.notificationCenter.addObserver(m_replaceObserver); + + QHBoxLayout *mainLayout = new QHBoxLayout(this); + mainLayout->setSizeConstraint(QLayout::SetNoConstraint); + + m_plot = new QwtPlot(this); + m_plot->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + mainLayout->addWidget(m_plot); + + this->setLayout(mainLayout); + } +} + + +/** + * Destructor + * + * Removes observers on the ADS. + */ +PreviewPlot::~PreviewPlot() +{ + if(m_init) + { + Mantid::API::AnalysisDataService::Instance().notificationCenter.removeObserver(m_removeObserver); + Mantid::API::AnalysisDataService::Instance().notificationCenter.removeObserver(m_replaceObserver); + } +} + + +/** + * Gets the background colour of the plot window. + * + * @return Plot canvas colour + */ +QColor PreviewPlot::canvasColour() +{ + if(m_plot) + return m_plot->canvasBackground(); + + return QColor(); +} + + +/** + * Sets the background colour of the plot window. + * + * @param colour Plot canvas colour + */ +void PreviewPlot::setCanvasColour(const QColor & colour) +{ + if(m_plot) + m_plot->setCanvasBackground(QBrush(colour)); +} + + +/** + * Enables or disables the option to use the pan tool on the plot. + * + * @param allow If tool should be allowed + */ +void PreviewPlot::setAllowPan(bool allow) +{ + m_allowPan = allow; +} + + +/** + * Checks to see if the option to use the pan tool is enabled. + * + * @return True if tool is allowed + */ +bool PreviewPlot::allowPan() +{ + return m_allowPan; +} + + +/** + * Enables or disables the option to use the zoom tool on the plot. + * + * @param allow If tool should be allowed + */ +void PreviewPlot::setAllowZoom(bool allow) +{ + m_allowZoom = allow; +} + + +/** + * Checks to see if the option to use the zoom tool is enabled. + * + * @return True if tool is allowed + */ +bool PreviewPlot::allowZoom() +{ + return m_allowZoom; +} + + +void PreviewPlot::addSpectra(Mantid::API::MatrixWorkspace_sptr ws, int specIndex) +{ +} + + +void PreviewPlot::addSpectra(const QString & wsName, int specIndex) +{ +} + + +void PreviewPlot::removeSpectra(Mantid::API::MatrixWorkspace_sptr ws) +{ +} + + +void PreviewPlot::removeSpectra(const QString & wsName) +{ +} + + +void PreviewPlot::replot() +{ +} + + +void PreviewPlot::handleRemoveEvent(Mantid::API::WorkspacePreDeleteNotification_ptr pNf) +{ +} + + +void PreviewPlot::handleReplaceEvent(Mantid::API::WorkspaceAfterReplaceNotification_ptr pNf) +{ +} From 98041ca89fda676a096bd38e1a6e3a20961a52ba Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Mon, 9 Feb 2015 10:49:15 +0000 Subject: [PATCH 042/414] Initial dump of system test supporting framework Some modules were dropped from the other repository as they were not used, namely - emailreporter.py - sqlresultreporter.py - StressTests directory. Fixes for path changes etc will still be required for this to work. Refs #10870 --- .../lib/systemtests/algorithm_decorator.py | 61 + .../lib/systemtests/stresstesting.py | 1043 +++++++++++++++++ .../lib/systemtests/xmlreporter.py | 86 ++ .../SystemTests/scripts/InstallerTests.py | 127 ++ .../SystemTests/scripts/mantidinstaller.py | 242 ++++ .../scripts/performance/README.txt | 1 + .../scripts/performance/analysis.py | 699 +++++++++++ .../scripts/performance/make_report.py | 84 ++ .../scripts/performance/reporters.py | 126 ++ .../scripts/performance/sqlresults.py | 327 ++++++ .../scripts/performance/testresult.py | 120 ++ .../scripts/performance/xunit_to_sql.py | 137 +++ .../SystemTests/scripts/runSystemTests.py | 118 ++ .../tests/analysis/reference/README.md | 1 + 14 files changed, 3172 insertions(+) create mode 100644 Code/Mantid/Testing/SystemTests/lib/systemtests/algorithm_decorator.py create mode 100644 Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py create mode 100644 Code/Mantid/Testing/SystemTests/lib/systemtests/xmlreporter.py create mode 100644 Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py create mode 100644 Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py create mode 100644 Code/Mantid/Testing/SystemTests/scripts/performance/README.txt create mode 100644 Code/Mantid/Testing/SystemTests/scripts/performance/analysis.py create mode 100755 Code/Mantid/Testing/SystemTests/scripts/performance/make_report.py create mode 100644 Code/Mantid/Testing/SystemTests/scripts/performance/reporters.py create mode 100644 Code/Mantid/Testing/SystemTests/scripts/performance/sqlresults.py create mode 100644 Code/Mantid/Testing/SystemTests/scripts/performance/testresult.py create mode 100755 Code/Mantid/Testing/SystemTests/scripts/performance/xunit_to_sql.py create mode 100755 Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py create mode 100644 Code/Mantid/Testing/SystemTests/tests/analysis/reference/README.md diff --git a/Code/Mantid/Testing/SystemTests/lib/systemtests/algorithm_decorator.py b/Code/Mantid/Testing/SystemTests/lib/systemtests/algorithm_decorator.py new file mode 100644 index 000000000000..91c0fd54546d --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/lib/systemtests/algorithm_decorator.py @@ -0,0 +1,61 @@ +import inspect +import re + +def make_decorator(algorithm_to_decorate): + """ + Dynamically create a builder pattern style decorator around a Mantid algorithm. + This allows you to separate out setting algorithm parameters from the actual method execution. Parameters may be reset multiple times. + + Usage: + rebin = make_decorator(Rebin) + rebin.set_Params([0, 0.1, 1]) + .... + rebin.execute() + + Arguments: + algorithm_to_decorate: The mantid.simpleapi algorithm to decorate. + + + + """ + + class Decorator(object): + + def __init__(self, alg_subject): + self.__alg_subject = alg_subject + self.__parameters__ = dict() + + def execute(self, additional=None, verbose=False): + if verbose: + print "Algorithm Parameters:" + print self.__parameters__ + print + out = self.__alg_subject(**self.__parameters__) + return out + + def set_additional(self, additional): + self.__parameters__.update(**additional) + + def add_getter_setter(type, name): + + def setter(self, x): + self.__parameters__[name] = x + + def getter(self): + return self.__parameters__[name] + + setattr(type, "set_" + name, setter) + setattr(type, "get_" + name, getter) + + + argspec = inspect.getargspec(algorithm_to_decorate) + for parameter in argspec.varargs.split(','): + m = re.search('(^\w+)', parameter) # Take the parameter key part from the defaults given as 'key=value' + if m: + parameter = m.group(0).strip() + m = re.search('\w+$', parameter) # strip off any leading numerical values produced by argspec + if m: + parameter = m.group(0).strip() + add_getter_setter(Decorator, m.group(0).strip()) + + return Decorator(algorithm_to_decorate) diff --git a/Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py b/Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py new file mode 100644 index 000000000000..7527065812e6 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py @@ -0,0 +1,1043 @@ +''' +Mantid stress testing framework. This module contains all of the necessary code +to run sets of stress tests on the Mantid framework by executing scripts directly +or by importing them into MantidPlot. + +Copyright © 2009 STFC Rutherford Appleton Laboratories + +This file is part of Mantid. + +Mantid is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 3 of the License, or +(at your option) any later version. + +Mantid is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . + +File change history is stored at: . +''' + +import sys +import os +import types +import re +import time +import datetime +import platform +import subprocess +import tempfile +import imp +import inspect +import abc +import numpy +import unittest + +######################################################################### +# The base test class. +######################################################################### +class MantidStressTest(unittest.TestCase): + '''Defines a base class for stress tests, providing functions + that should be overridden by inheriting classes to perform tests. + ''' + + # Define a delimiter when reporting results + DELIMITER = '|' + + # Define a prefix for reporting results + PREFIX = 'RESULT' + + def __init__(self): + super(MantidStressTest, self).__init__() + # A list of things not to check when validating + self.disableChecking = [] + # Whether or not to strip off whitespace when doing simple ascii diff + self.stripWhitespace = True + # Tolerance + self.tolerance = 0.00000001 + # Store the resident memory of the system (in MB) before starting the test + import mantid.api + mantid.api.FrameworkManager.clear() + from mantid.kernel import MemoryStats + self.memory = MemoryStats().residentMem()/1024 + + def runTest(self): + raise NotImplementedError('"runTest(self)" should be overridden in a derived class') + + def skipTests(self): + ''' + Override this to return True when the tests should be skipped for some + reason. + See also: requiredFiles() and requiredMemoryMB() + ''' + return False + + def validate(self): + ''' + Override this to provide a pair of workspaces which should be checked for equality + by the doValidation method. + The overriding method should return a pair of strings. This could be two workspace + names, e.g. return 'workspace1','workspace2', or a workspace name and a nexus + filename (which must have nxs suffix), e.g. return 'workspace1','GEM00001.nxs'. + ''' + return None + + def requiredFiles(self): + ''' + Override this method if you want to require files for the test. + Return a list of files. + ''' + return [] + + def requiredMemoryMB(self): + ''' + Override this method to specify the amount of free memory, + in megabytes, that is required to run the test. + The test is skipped if there is not enough memory. + ''' + return 0 + + def validateMethod(self): + ''' + Override this to specify which validation method to use. Look at the validate* methods to + see what allowed values are. + ''' + return "WorkspaceToNeXus" + + def maxIterations(self): + '''Override this to perform more than 1 iteration of the implemented test.''' + return 1 + + def reportResult(self, name, value): + ''' + Send a result to be stored as a name,value pair + ''' + print self.PREFIX + self.DELIMITER + name + self.DELIMITER + str(value) + '\n', + + def __verifyRequiredFile(self, filename): + '''Return True if the specified file name is findable by Mantid.''' + from mantid.api import FileFinder + + # simple way is just getFullPath which never uses archive search + if os.path.exists(FileFinder.getFullPath(filename)): + return True + + # try full findRuns which will use archive search if it is turned on + try: + candidates = FileFinder.findRuns(filename) + for item in candidates: + if os.path.exists(item): + return True + except RuntimeError, e: + return False + + + # file was not found + return False + + def __verifyRequiredFiles(self): + # first see if there is anything to do + reqFiles = self.requiredFiles() + if len(reqFiles) <= 0: + return + + # by default everything is ok + foundAll = True + + # initialize mantid so it can get the data directories to look in + import mantid + # check that all of the files exist + for filename in reqFiles: + if not self.__verifyRequiredFile(filename): + print "Missing required file: '%s'" % filename + foundAll = False + + if not foundAll: + sys.exit(PythonTestRunner.SKIP_TEST) + + def __verifyMemory(self): + """ Do we need to skip due to lack of memory? """ + required = self.requiredMemoryMB() + if required <= 0: + return + + # Check if memory is available + from mantid.kernel import MemoryStats + MB_avail = MemoryStats().availMem()/(1024.) + if (MB_avail < required): + print "Insufficient memory available to run test! %g MB available, need %g MB." % (MB_avail,required) + sys.exit(PythonTestRunner.SKIP_TEST) + + def execute(self): + ''' + Run the defined number of iterations of this test + ''' + # Do we need to skip due to missing files? + self.__verifyRequiredFiles() + + self.__verifyMemory() + + # A custom check for skipping the tests for other reasons + if self.skipTests(): + sys.exit(PythonTestRunner.SKIP_TEST) + + # Start timer + start = time.time() + countmax = self.maxIterations() + 1 + for i in range(1, countmax): + istart = time.time() + self.runTest() + delta_t = time.time() - istart + self.reportResult('iteration time_taken', str(i) + ' %.2f' % delta_t) + delta_t = float(time.time() - start) + # Finish + #self.reportResult('time_taken', '%.2f' % delta_t) + + def __prepASCIIFile(self, filename): + """ + Prepare an ascii file for comparison using difflib. + """ + handle = open(filename, mode='r') + stuff = handle.readlines() + if self.stripWhitespace: + stuff = [line.strip() for line in stuff] + handle.close() + return stuff + + def validateASCII(self): + """ + Validate ASCII files using difflib. + """ + (measured, expected) = self.validate() + measured = self.__prepASCIIFile(measured) + expected = self.__prepASCIIFile(expected) + + # calculate the difference + import difflib + diff = difflib.Differ().compare(measured, expected) + result = [] + for line in diff: + if line.startswith('+') or line.startswith('-') or line.startswith('?'): + result.append(line) + + # print the difference + if len(result) > 0: + if self.stripWhitespace: + msg = "(whitespace striped from ends)" + else: + msg = "" + print "******************* Difference in files", msg + print "\n".join(result) + print "*******************" + return False + else: + return True + + def validateWorkspaceToNeXus(self): + ''' + Assumes the second item from self.validate() is a nexus file and loads it + to compare to the supplied workspace. + ''' + valNames = list(self.validate()) + from mantid.simpleapi import Load + numRezToCheck=len(valNames) + mismatchName=None; + + validationResult =True; + for ik in range(0,numRezToCheck,2): # check All results + workspace2 = valNames[ik+1] + if workspace2.endswith('.nxs'): + Load(Filename=workspace2,OutputWorkspace="RefFile") + workspace2 = "RefFile" + else: + raise RuntimeError("Should supply a NeXus file: %s" % workspace2) + valPair=(valNames[ik],"RefFile"); + if numRezToCheck>2: + mismatchName = valNames[ik]; + + if not(self.validateWorkspaces(valPair,mismatchName)): + validationResult = False; + print 'Workspace {0} not equal to its reference file'.format(valNames[ik]); + #end check All results + + return validationResult; + + def validateWorkspaceToWorkspace(self): + ''' + Assumes the second item from self.validate() is an existing workspace + to compare to the supplied workspace. + ''' + valNames = list(self.validate()) + return self.validateWorkspaces(valNames) + + def validateWorkspaces(self, valNames=None,mismatchName=None): + ''' + Performs a check that two workspaces are equal using the CheckWorkspacesMatch + algorithm. Loads one workspace from a nexus file if appropriate. + Returns true if: the workspaces match + OR the validate method has not been overridden. + Returns false if the workspace do not match. The reason will be in the log. + ''' + if valNames is None: + valNames = self.validate() + + from mantid.simpleapi import SaveNexus, AlgorithmManager + checker = AlgorithmManager.create("CheckWorkspacesMatch") + checker.setLogging(True) + checker.setPropertyValue("Workspace1",valNames[0]) + checker.setPropertyValue("Workspace2",valNames[1]) + checker.setPropertyValue("Tolerance", str(self.tolerance)) + if hasattr(self,'tolerance_is_reller') and self.tolerance_is_reller: + checker.setPropertyValue("ToleranceRelerr", "1") + for d in self.disableChecking: + checker.setPropertyValue("Check"+d,"0") + checker.execute() + if checker.getPropertyValue("Result") != 'Success!': + print self.__class__.__name__ + if mismatchName: + SaveNexus(InputWorkspace=valNames[0],Filename=self.__class__.__name__+mismatchName+'-mismatch.nxs') + else: + SaveNexus(InputWorkspace=valNames[0],Filename=self.__class__.__name__+'-mismatch.nxs') + return False + + return True + + def doValidation(self): + """ + Perform validation. This selects which validation method to use by the result + of validateMethod() and validate(). If validate() is not overridden this will + return True. + """ + # if no validation is specified then it must be ok + validation = self.validate() + if validation is None: + return True + + # if a simple boolean then use this + if type(validation) == bool: + return validation + # or numpy boolean + if type(validation) == numpy.bool_: + return bool(validation) + + # switch based on validation methods + method = self.validateMethod() + if method is None: + return True # don't validate + method = method.lower() + if "validateworkspacetonexus".endswith(method): + return self.validateWorkspaceToNeXus() + elif "validateworkspacetoworkspace".endswith(method): + return self.validateWorkspaceToWorkspace() + elif "validateascii".endswith(method): + return self.validateASCII() + else: + raise RuntimeError("invalid validation method '%s'" % self.validateMethod()) + + def returnValidationCode(self,code): + """ + Calls doValidation() and returns 0 in success and code if failed. This will be + used as return code from the calling python subprocess + """ + if self.doValidation(): + retcode = 0 + else: + retcode = code + if retcode == 0: + self._success = True + else: + self._success = False + # Now the validation is complete we can clear out all the stored data and check memory usage + import mantid.api + mantid.api.FrameworkManager.clear() + # Get the resident memory again and work out how much it's gone up by (in MB) + from mantid.kernel import MemoryStats + memorySwallowed = MemoryStats().residentMem()/1024 - self.memory + # Store the result + self.reportResult('memory footprint increase', memorySwallowed ) + return retcode + + def succeeded(self): + """ + Returns true if the test has been run and it succeeded, false otherwise + """ + if hasattr(self, '_success'): + return self._success + else: + return False + + def cleanup(self): + ''' + This function is called after a test has completed and can be used to + clean up, i.e. remove workspaces etc + ''' + pass + + + def assertDelta(self, value, expected, delta, msg=""): + """ + Check that a value is within +- delta of the expected value + """ + # Build the error message + if msg != "": msg += " " + msg += "Expected %g == %g within +- %g." % (value, expected, delta) + + if (value > expected+delta) or (value < expected-delta): + raise Exception(msg) + + def assertLessThan(self, value, expected, msg=""): + """ + Check that a value is < expected. + """ + # Build the error message + if msg != "": msg += " " + msg += "Expected %g < %g " % (value, expected) + + if (value >= expected): + raise Exception(msg) + + def assertGreaterThan(self, value, expected, msg=""): + """ + Check that a value is > expected. + """ + # Build the error message + if msg != "": msg += " " + msg += "Expected %g > %g " % (value, expected) + + if (value <= expected): + raise Exception(msg) + + +######################################################################### +# A class to store the results of a test +######################################################################### +class TestResult(object): + ''' + Stores the results of each test so that they can be reported later. + ''' + + def __init__(self): + self._results = [] + self.name = '' + self.filename = '' + self.date = '' + self.status = '' + self.time_taken = '' + self.total_time = '' + self.output = '' + self.err = '' + + def addItem(self, item): + ''' + Add an item to the store, this should be a list containing 2 entries: [Name, Value] + ''' + self._results.append(item) + + def resultLogs(self): + ''' + Get the map storing the results + ''' + return self._results + +######################################################################### +# A base class to support report results in an appropriate manner +######################################################################### +class ResultReporter(object): + ''' + A base class for results reporting. In order to get the results in an + appropriate form, subclass this class and implement the dispatchResults + method. + ''' + + def __init__(self): + '''Initialize a class instance, e.g. connect to a database''' + pass + + def dispatchResults(self, result): + raise NotImplementedError('"dispatchResults(self, result)" should be overridden in a derived class') + +######################################################################### +# A class to report results as formatted text output +######################################################################### +class TextResultReporter(ResultReporter): + ''' + Report the results of a test using standard out + ''' + + def dispatchResults(self, result): + ''' + Print the results to standard out + ''' + nstars = 30 + print '*' * nstars + for t in result.resultLogs(): + print '\t' + str(t[0]).ljust(15) + '-> ', str(t[1]) + print '*' * nstars + +######################################################################### +# A class to report results as junit xml +######################################################################### +from xmlreporter import XmlResultReporter + +######################################################################### +# A class to report results via email +######################################################################### +from emailreporter import EmailResultReporter + +######################################################################### +# A base class for a TestRunner +######################################################################### +class PythonTestRunner(object): + ''' + A base class to serve as a wrapper to actually run the tests in a specific + environment, i.e. console, gui + ''' + SUCCESS_CODE = 0 + GENERIC_FAIL_CODE = 1 + SEGFAULT_CODE = 139 + VALIDATION_FAIL_CODE = 99 + NOT_A_TEST = 98 + SKIP_TEST = 97 + + def __init__(self, need_escaping = False): + self._mtdpy_header = '' + self._test_dir = '' + # Get the path that this module resides in so that the tests know about it + self._framework_path = '' + for p in sys.path: + if 'Framework' in p: + self._framework_path = os.path.abspath(p).replace('\\','/') + # A string to prefix the code with + self._code_prefix = '' + self._using_escape = need_escaping + + def commandString(self, pycode): + ''' + Return the appropriate command to pass to subprocess.Popen + ''' + raise NotImplementedError('"commandString(self)" should be overridden in a derived class') + + def setMantidDir(self, mtdheader_dir): + # Store the path to MantidPythonAPI + self._mtdpy_header = os.path.abspath(mtdheader_dir).replace('\\','/') + + def setTestDir(self, test_dir): + self._test_dir = os.path.abspath(test_dir).replace('\\','/') + + def createCodePrefix(self): + if self._using_escape == True: + esc = '\\' + else: + esc = '' + + self._code_prefix = 'import sys, time;' + self._code_prefix += 'sys.path.insert(0, ' + esc + '"' + self._mtdpy_header + esc + '");' + \ + 'sys.path.append(' + esc + '"' + self._framework_path + esc + '");' + \ + 'sys.path.append(' + esc + '"' + self._test_dir + esc + '");' + + def getCodePrefix(self): + ''' + Return a prefix to the code that will be executed + ''' + return self._code_prefix + + def spawnSubProcess(self, cmd): + ''' + Spawn a new process and run the given command within it + ''' + + proc = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, bufsize=-1) + std_out = "" + std_err = "" + for line in proc.stdout: + print line, + std_out += line + proc.wait() + + return proc.returncode, std_out, std_err + + def start(self, pycode): + ''' + Run the given test code in a new subprocess + ''' + raise NotImplementedError('"run(self, pycode)" should be overridden in a derived class') + +######################################################################### +# A runner class to execute the tests on using the command line interface +######################################################################### +class PythonConsoleRunner(PythonTestRunner): + ''' + This class executes tests within a Mantid environment inside a standalone python + interpreter + ''' + + def __init__(self): + PythonTestRunner.__init__(self, True) + + def start(self, pycode): + ''' + Run the code in a new instance of a python interpreter + ''' + return self.spawnSubProcess(sys.executable + ' -c \"' + self.getCodePrefix() + pycode + '\"') + +######################################################################### +# A runner class to execute the tests on using the command line interface +######################################################################### +class MantidPlotTestRunner(PythonTestRunner): + ''' + This class executes tests within the Python scripting environment inside + MantidPlot + ''' + + def __init__(self, mtdplot_dir): + PythonTestRunner.__init__(self) + mtdplot_bin = mtdplot_dir + '/MantidPlot' + if os.name == 'nt': + mtdplot_bin += '.exe' + self._mtdplot_bin = os.path.abspath(mtdplot_bin).replace('\\','/') + + def start(self, pycode): + ''' + Run the code in a new instance of the MantidPlot scripting environment + ''' + # The code needs wrapping in a temporary file so that it can be passed + # to MantidPlot, along with the redirection of the scripting output to + # stdout + # On Windows, just using the file given back by tempfile doesn't work + # as the name is mangled to a short version where all characters after + # a space are replace by ~. So on windows use put the file in the + # current directory + if os.name == 'nt': + loc = '.' + else: + loc = '' + # MG 11/09/2009: I tried the simple tempfile.NamedTemporaryFile() method + # but this didn't work on Windows so I had to be a little long winded + # about it + fd, tmpfilepath = tempfile.mkstemp(suffix = '.py', dir = loc, text=True) + + os.write(fd, 'import sys\nsys.stdout = sys.__stdout__\n' + self.getCodePrefix() + pycode) + retcode, output, err = self.spawnSubProcess('"' +self._mtdplot_bin + '" -xq \'' + tmpfilepath + '\'') + # Remove the temporary file + os.close(fd) + os.remove(tmpfilepath) + return retcode, output, err + +######################################################################### +# A class to tie together a test and its results +######################################################################### +class TestSuite(object): + ''' + Tie together a test and its results. + ''' + def __init__(self, modname, testname, filename = None): + self._modname = modname + self._fullname = modname + # A None testname indicates the source did not load properly + # It has come this far so that it gets reported as a proper failure + # by the framework + if testname is not None: + self._fullname += '.' + testname + + self._result = TestResult() + # Add some results that are not linked to the actually test itself + self._result.name = self._fullname + if filename: + self._result.filename = filename + else: + self._result.filename = self._fullname + self._result.addItem(['test_name', self._fullname]) + sysinfo = platform.uname() + self._result.addItem(['host_name', sysinfo[1]]) + self._result.addItem(['environment', self.envAsString()]) + self._result.status = 'skipped' # the test has been skipped until it has been executed + + name = property(lambda self: self._fullname) + status = property(lambda self: self._result.status) + + def envAsString(self): + if os.name == 'nt': + system = platform.system().lower()[:3] + arch = platform.architecture()[0][:2] + env = system + arch + elif os.name == 'mac': + env = platform.mac_ver()[0] + else: + env = platform.dist()[0] + return env + + def markAsSkipped(self, reason): + self.setOutputMsg(reason) + self._result.status = 'skipped' + + def execute(self, runner): + print time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) + ': Executing ' + self._fullname + pycode = 'import ' + self._modname + ';'\ + + 'systest = ' + self._fullname + '();'\ + + 'systest.execute();'\ + + 'retcode = systest.returnValidationCode('+str(PythonTestRunner.VALIDATION_FAIL_CODE)+');'\ + + 'systest.cleanup();'\ + + 'sys.exit(retcode)' + # Start the new process + self._result.date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + self._result.addItem(['test_date',self._result.date]) + retcode, output, err = runner.start(pycode) + + + if retcode == PythonTestRunner.SUCCESS_CODE: + status = 'success' + elif retcode == PythonTestRunner.GENERIC_FAIL_CODE: + # This is most likely an algorithm failure, but it's not certain + status = 'algorithm failure' + elif retcode == PythonTestRunner.VALIDATION_FAIL_CODE: + status = 'failed validation' + elif retcode == PythonTestRunner.SEGFAULT_CODE: + status = 'crashed' + elif retcode == PythonTestRunner.SKIP_TEST: + status = 'skipped' + elif retcode < 0: + status = 'hung' + else: + status = 'unknown' + + # Check return code and add result + self._result.status = status + self._result.addItem(['status', status]) + # Dump std out so we know what happened + print output + self._result.output = output + all_lines = output.split('\n') + # Find the test results + for line in all_lines: + entries = line.split(MantidStressTest.DELIMITER) + if len(entries) == 3 and entries[0] == MantidStressTest.PREFIX: + self._result.addItem([entries[1], entries[2]]) + + def setOutputMsg(self, msg=None): + if msg is not None: + self._result.output = msg + + def reportResults(self, reporters): + for r in reporters: + r.dispatchResults(self._result) + +######################################################################### +# The main API class +######################################################################### +class TestManager(object): + '''A manager class that is responsible for overseeing the testing process. + This is the main interaction point for the framework. + ''' + + def __init__(self, test_loc, runner = PythonConsoleRunner(), output = [TextResultReporter()], + testsInclude=None, testsExclude=None): + '''Initialize a class instance''' + + # Check whether the MANTIDPATH variable is set + mtdheader_dir = os.getenv("MANTIDPATH") + if mtdheader_dir is None: + raise RuntimeError('MANTIDPATH variable not be found. Please ensure Mantid is installed correctly.') + + # Runners and reporters + self._runner = runner + self._reporters = output + + # Init mantid + sys.path.append(os.path.abspath(mtdheader_dir).replace('\\','/')) + runner.setMantidDir(mtdheader_dir) + + # If given option is a directory + if os.path.isdir(test_loc) == True: + test_dir = os.path.abspath(test_loc).replace('\\','/') + sys.path.append(test_dir) + runner.setTestDir(test_dir) + self._tests = self.loadTestsFromDir(test_dir) + else: + if os.path.exists(test_loc) == False: + print 'Cannot find file ' + test_loc + '.py. Please check the path.' + exit(2) + test_dir = os.path.abspath(os.path.dirname(test_loc)).replace('\\','/') + sys.path.append(test_dir) + runner.setTestDir(test_dir) + self._tests = self.loadTestsFromModule(os.path.basename(test_loc)) + + if len(self._tests) == 0: + print 'No tests defined in ' + test_dir + '. Please ensure all test classes sub class stresstesting.MantidStressTest.' + exit(2) + + self._passedTests = 0 + self._skippedTests = 0 + self._failedTests = 0 + self._lastTestRun = 0 + + self._testsInclude = testsInclude + self._testsExclude = testsExclude + + # Create a prefix to use when executing the code + runner.createCodePrefix() + + totalTests = property(lambda self: len(self._tests)) + skippedTests = property(lambda self: (self.totalTests - self._passedTests - self._failedTests)) + passedTests = property(lambda self: self._passedTests) + failedTests = property(lambda self: self._failedTests) + + def __shouldTest(self, suite): + if self._testsInclude is not None: + if not self._testsInclude in suite.name: + suite.markAsSkipped("NotIncludedTest") + return False + if self._testsExclude is not None: + if self._testsExclude in suite.name: + suite.markAsSkipped("ExcludedTest") + return False + return True + + def executeTests(self): + # Get the defined tests + for suite in self._tests: + if self.__shouldTest(suite): + suite.execute(self._runner) + if suite.status == "success": + self._passedTests += 1 + elif suite.status == "skipped": + self._skippedTests += 1 + else: + self._failedTests += 1 + suite.reportResults(self._reporters) + self._lastTestRun += 1 + + def markSkipped(self, reason=None): + for suite in self._tests[self._lastTestRun:]: + suite.setOutputMsg(reason) + suite.reportResults(self._reporters) # just let people know you were skipped + + def loadTestsFromDir(self, test_dir): + ''' Load all of the tests defined in the given directory''' + entries = os.listdir(test_dir) + tests = [] + regex = re.compile('^.*\.py$', re.IGNORECASE) + for file in entries: + if regex.match(file) != None: + tests.extend(self.loadTestsFromModule(os.path.join(test_dir,file))) + return tests + + def loadTestsFromModule(self, filename): + ''' + Load test classes from the given module object which has been + imported with the __import__ statement + ''' + modname = os.path.basename(filename) + modname = modname.split('.py')[0] + path = os.path.dirname(filename) + pyfile = open(filename, 'r') + tests = [] + try: + mod = imp.load_module(modname, pyfile, filename, ("","",imp.PY_SOURCE)) + mod_attrs = dir(mod) + for key in mod_attrs: + value = getattr(mod, key) + if key is "MantidStressTest" or not inspect.isclass(value): + continue + if self.isValidTestClass(value): + test_name = key + tests.append(TestSuite(modname, test_name, filename)) + except Exception: + # Error loading the source, add fake unnamed test so that an error + # will get generated when the tests are run and it will be counted properly + tests.append(TestSuite(modname, None, filename)) + finally: + pyfile.close() + return tests + + def isValidTestClass(self, class_obj): + """Returns true if the test is a valid test class. It is valid + if: the class subclassses MantidStressTest and has no abstract methods + """ + if not issubclass(class_obj, MantidStressTest): + return False + # Check if the get_reference_file is abstract or not + if hasattr(class_obj, "__abstractmethods__"): + if len(class_obj.__abstractmethods__) == 0: + return True + else: + return False + else: + return True + +######################################################################### +# Class to handle the environment +######################################################################### +class MantidFrameworkConfig: + + def __init__(self, mantidDir=None, sourceDir=None, + loglevel='information', archivesearch=False): + # force the environment variable + if mantidDir is not None: + if os.path.isfile(mantidDir): + mantidDir = os.path.split(mantidDir)[0] + os.environ['MANTIDPATH'] = mantidDir + + # add it to the python path + directory = os.getenv("MANTIDPATH") + if directory is None: + raise RuntimeError("MANTIDPATH not found.") + else: + sys.path.append(directory) + if not os.path.isdir(os.path.join(directory, "mantid")): + raise RuntimeError("Did not find mantid package in %s" % directory) + + self.__sourceDir = self.__locateSourceDir(sourceDir) + + # add location of stress tests + self.__testDir = self.__locateTestsDir() + + # add location of the analysis tests + sys.path.insert(0,self.__locateTestsDir()) + + # setup the rest of the magic directories + parentDir = os.path.split(self.__sourceDir)[0] + self.__saveDir = os.path.join(parentDir, "logs/").replace('\\','/') + self.__dataDirs = [os.path.join(parentDir, "SystemTests"), + os.path.join(parentDir, "SystemTests/AnalysisTests/ReferenceResults"), + os.path.join(parentDir, "Data"), + os.path.join(parentDir, "Data/LOQ"), + os.path.join(parentDir, "Data/SANS2D"), + os.path.join(parentDir, "Data/PEARL"), + self.__saveDir + ] + + # set the log level + self.__loglevel = loglevel + self.__datasearch = archivesearch + + def __locateSourceDir(self, suggestion): + if suggestion is None: + loc = os.path.abspath(__file__) + suggestion = os.path.split(loc)[0] # get the directory + loc = os.path.abspath(suggestion) + loc = os.path.normpath(loc) + + if os.path.isdir(loc): + return loc + else: + raise RuntimeError("Failed to find source directory") + + def __locateTestsDir(self): + loc = os.path.join(self.__sourceDir, '../SystemTests/AnalysisTests') + loc = os.path.abspath(loc) + if os.path.isdir(loc): + return loc + else: + raise RuntimeError("'%s' is not a directory (AnalysisTests)" % loc) + + def __getDataDirs(self): + # get the file of the python script + testDir = os.path.split(self.__sourceDir)[0] + + # add things to the data search path + dirs =[] + dirs.append(os.path.join(testDir, "Data")) + dirs.append(os.path.join(testDir, "Data/LOQ")) + dirs.append(os.path.join(testDir, "Data/SANS2D")) + dirs.append(os.path.join(testDir, "Data/PEARL")) + dirs.append(os.path.join(testDir, "SystemTests")) + dirs.append(os.path.join(testDir, \ + "SystemTests/AnalysisTests/ReferenceResults")) + dirs.append(os.path.abspath(os.getenv("MANTIDPATH"))) + + dirs = [os.path.normpath(item) for item in dirs] + + return dirs + + def __moveFile(self, src, dst): + if os.path.exists(src): + import shutil + shutil.move(src, dst) + + def __copyFile(self, src, dst): + if os.path.exists(src): + import shutil + shutil.copyfile(src, dst) + + saveDir = property(lambda self: self.__saveDir) + testDir = property(lambda self: self.__testDir) + + def config(self): + if not os.path.exists(self.__saveDir): + print "Making directory %s to save results" % self.__saveDir + os.mkdir(self.__saveDir) + else: + if not os.path.isdir(self.__saveDir): + raise RuntimeError("%s is not a directory" % self.__saveDir) + + # Start mantid + import mantid + from mantid.kernel import config + + # backup the existing user properties so we can step all over it + self.__userPropsFile = config.getUserFilename() + self.__userPropsFileBackup = self.__userPropsFile + ".bak" + self.__userPropsFileSystest = self.__userPropsFile + ".systest" + self.__moveFile(self.__userPropsFile, self.__userPropsFileBackup) + + # Make sure we only save these keys here + config.reset() + + # Up the log level so that failures can give useful information + config['logging.loggers.root.level'] = self.__loglevel + # Set the correct search path + data_path = '' + for dir in self.__dataDirs: + if not os.path.exists(dir): + raise RuntimeError('Directory ' + dir + ' was not found.') + search_dir = dir.replace('\\','/') + if not search_dir.endswith('/'): + search_dir += '/' + data_path += search_dir + ';' + config['datasearch.directories'] = data_path + + # Save path + config['defaultsave.directory'] = self.__saveDir + + # Do not show paraview dialog + config['paraview.ignore'] = "1" + + # Do not update instrument definitions + config['UpdateInstrumentDefinitions.OnStartup'] = "0" + + # Disable usage reports + config['usagereports.enabled'] = "0" + + # Case insensitive + config['filefinder.casesensitive'] = 'Off' + + # datasearch + if self.__datasearch: + config["datasearch.searcharchive"] = 'On' + + # Save this configuration + config.saveConfig(self.__userPropsFile) + + def restoreconfig(self): + self.__moveFile(self.__userPropsFile, self.__userPropsFileSystest) + self.__moveFile(self.__userPropsFileBackup, self.__userPropsFile) + + +#============================================================================== +def envAsString(): + """Returns a string describing the environment + (platform) of this test.""" + if os.name == 'nt': + system = platform.system().lower()[:3] + arch = platform.architecture()[0][:2] + env = system + arch + elif os.name == 'mac': + env = platform.mac_ver()[0] + else: + env = platform.dist()[0] + "-" + platform.dist()[1] + return env diff --git a/Code/Mantid/Testing/SystemTests/lib/systemtests/xmlreporter.py b/Code/Mantid/Testing/SystemTests/lib/systemtests/xmlreporter.py new file mode 100644 index 000000000000..a991fe30f7df --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/lib/systemtests/xmlreporter.py @@ -0,0 +1,86 @@ +import os +import sys +from xml.dom.minidom import getDOMImplementation +import stresstesting + +class XmlResultReporter(stresstesting.ResultReporter): + + _time_taken = 0.0 + _failures = [] + _skipped = [] + + def __init__(self, showSkipped=True): + self._doc = getDOMImplementation().createDocument(None,'testsuite',None) + self._show_skipped = showSkipped + + def reportStatus(self): + return len(self._failures) == 0 + + def getResults(self): + # print the command line summary version of the results + self._failures.sort() + self._skipped.sort() + print + if self._show_skipped and len(self._skipped) > 0: + print "SKIPPED:" + for test in self._skipped: + print test.name + if len(self._failures) > 0: + print "FAILED:" + for test in self._failures: + print test.name + + # return the xml document version + docEl = self._doc.documentElement + docEl.setAttribute('name','SystemTests') + docEl.setAttribute('tests',str(len(docEl.childNodes))) + docEl.setAttribute('failures',str(len(self._failures))) + docEl.setAttribute('skipped', str(len(self._skipped))) + docEl.setAttribute('time',str(self._time_taken)) + return self._doc.toxml() + + def dispatchResults(self, result): + ''' This relies on the order and names of the items to give the correct output ''' + test_name = result.name.split('.') + if len(test_name) > 1: + class_name = '.'.join(test_name[:-1]) + name = test_name[-1] + else: + class_name = result.name + name = result.name + elem = self._doc.createElement('testcase') + elem.setAttribute('classname',"SystemTests." + class_name) + elem.setAttribute('name',name) + if result.status == 'skipped': + self._skipped.append(result) + skipEl = self._doc.createElement('skipped') + if len(result.output) > 0: + if "Missing required file" in result.output: + skipEl.setAttribute('message', "MissingRequiredFile") + else: + skipEl.setAttribute('message', result.output) + skipEl.appendChild(self._doc.createTextNode(result.output)) + elem.appendChild(skipEl) + elif result.status != 'success': + self._failures.append(result) + failEl = self._doc.createElement('failure') + failEl.setAttribute('file',result.filename) + output = '' + if len(result.output) > 0: + output += result.output + if len(output) > 0: + failEl.appendChild(self._doc.createTextNode(output)) + elem.appendChild(failEl) + else: + time_taken = 0.0 + for t in result.resultLogs(): + if t[0] == 'iteration time_taken': + time_taken = float(t[1].split(' ')[1]) + self._time_taken += time_taken + if t[0] == 'memory footprint increase': + memEl = self._doc.createElement('memory') + memEl.appendChild(self._doc.createTextNode(t[1])) + elem.appendChild(memEl) + elem.setAttribute('time',str(time_taken)) + elem.setAttribute('totalTime',str(time_taken)) + self._doc.documentElement.appendChild(elem) diff --git a/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py b/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py new file mode 100644 index 000000000000..cae938d474bb --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py @@ -0,0 +1,127 @@ +import os +import sys +import platform +import shutil +import subprocess +from getopt import getopt + +from mantidinstaller import (createScriptLog, log, stop, failure, scriptfailure, + get_installer, run) + +''' + +This script copies Mantid installer for the system it is running on from the build server, +installs it, runs system tests and produces an xml report file SystemTestsReport.xml + +''' + +try: + opt, argv = getopt(sys.argv[1:],'nohvR:l:') +except: + opt = [('-h','')] + +if ('-h','') in opt: + print "Usage: %s [OPTIONS]" % os.path.basename(sys.argv[0]) + print + print "Valid options are:" + print " -n Run tests without installing Mantid (it must be already installed)" + print " -o Output to the screen instead of log files" + print " -h Display the usage" + print " -R Optionally only run the test matched by the regex" + print " -l Log level" + sys.exit(0) + +doInstall = True +test_regex = None +out2stdout = False +log_level = 'notice' +for option, arg in opt: + if option == '-n': + doInstall = False + if option == '-o': + out2stdout = True + if option == '-R' and arg != "": + test_regex = arg + if option == '-l' and arg != "": + log_level = arg + +# The log file for this script +parentDir = os.path.abspath('..').replace('\\','/') +if not os.path.exists(parentDir + '/logs'): + os.mkdir(parentDir + '/logs') + +createScriptLog(parentDir + '/logs/TestScript.log') +testRunLogPath = parentDir + '/logs/testsRun.log' +testRunErrPath = parentDir + '/logs/testsRun.err' + +log('Starting system tests') +installer = get_installer(doInstall) + +# Install the found package +if doInstall: + log("Installing package '%s'" % installer.mantidInstaller) + try: + installer.install() + log("Application path " + installer.mantidPlotPath) + installer.no_uninstall = False + except Exception,err: + scriptfailure("Installing failed. "+str(err)) +else: + installer.no_uninstall = True + +# Ensure MANTIDPATH points at this directory so that +# the correct properties file is loaded +mantidPlotDir = os.path.dirname(installer.mantidPlotPath) +log('MantidPlot directory %s' % mantidPlotDir) +log('Pointing MANTIDPATH at MantidPlot directory %s' % mantidPlotDir) +os.environ["MANTIDPATH"] = mantidPlotDir + +try: + # Keep hold of the version that was run + version = run(installer.mantidPlotPath + ' -v') + version_tested = open('version_tested.log','w') + if version and len(version) > 0: + version_tested.write(version) + version_tested.close() +except Exception, err: + scriptfailure('Version test failed: '+str(err), installer) + +try: + # Now get the revision number/git commit ID (remove the leading 'g' that isn't part of it) + revision = run(installer.mantidPlotPath + ' -r').lstrip('g') + revision_tested = open('revision_tested.log','w') + if revision and len(version) > 0: + revision_tested.write(revision) + revision_tested.close() +except Exception, err: + scriptfailure('Revision test failed: '+str(err), installer) + +log("Running system tests. Log files are: logs/testsRun.log and logs/testsRun.err") +try: + # Pick the correct Mantid along with the bundled python on windows + run_test_cmd = "%s %s/runSystemTests.py --loglevel=%s --mantidpath=%s" % (installer.python_cmd, os.path.dirname(os.path.realpath(__file__)), log_level, mantidPlotDir) + if test_regex is not None: + run_test_cmd += " -R " + test_regex + if out2stdout: + p = subprocess.Popen(run_test_cmd, shell=True) # no PIPE: print on screen for debugging + p.wait() + else: + p = subprocess.Popen(run_test_cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True) + out,err = p.communicate() # waits for p to finish + testsRunLog = open(testRunLogPath,'w') + if out: + testsRunLog.write(out) + testsRunLog.close() + testsRunErr = open(testRunErrPath,'w') + if err: + testsRunErr.write(err) + testsRunErr.close() + if p.returncode != 0: + failure(installer) +except Exception, exc: + scriptfailure(str(exc),installer) +except: + failure(installer) + +# Test run completed successfully +stop(installer) diff --git a/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py b/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py new file mode 100644 index 000000000000..3b566b8f4e15 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py @@ -0,0 +1,242 @@ +"""Defines classes for handling installation +""" +import platform +import os +import glob +import sys +import subprocess + +scriptLog = None + +def createScriptLog(path): + global scriptLog + scriptLog = open(path,'w') + +def stop(installer): + ''' Save the log, uninstall the package and exit with error code 0 ''' + try: + installer.uninstall() + except Exception, exc: + log("Could not uninstall package %s: %s" % (installer.mantidInstaller, str(exc))) + scriptLog.close() + sys.exit(0) + +def log(txt): + ''' Write text to the script log file ''' + if txt and len(txt) > 0: + scriptLog.write(txt) + if not txt.endswith('\n'): + scriptLog.write('\n') + print txt + +def failure(installer): + ''' Report failure of test(s), try to uninstall package and exit with code 1 ''' + try: + installer.uninstall() + except Exception, exc: + log("Could not uninstall package %s: %s" % (installer.mantidInstaller, str(exc))) + pass + + log('Tests failed') + print 'Tests failed' + sys.exit(1) + +def scriptfailure(txt, installer=None): + '''Report failure of this script, try to uninstall package and exit with code 1 ''' + if txt: + log(txt) + if installer is not None: + try: + installer.uninstall() + except Exception: + log("Could not uninstall package %s " % self.mantidInstaller) + scriptLog.close() + sys.exit(1) + + +def get_installer(do_install=True): + """ + Creates the correct class for the current platform + @param do_install :: True if installation is to be performed + """ + system = platform.system() + if system == 'Windows': + return NSISInstaller(do_install) + elif system == 'Linux': + dist = platform.dist() + if dist[0] == 'Ubuntu': + return DebInstaller(do_install) + elif dist[0] == 'redhat' and (dist[1].startswith('5.') or dist[1].startswith('6.')): + return RPMInstaller(do_install) + else: + scriptfailure('Unknown Linux flavour: %s' % str(dist)) + elif system == 'Darwin': + return DMGInstaller(do_install) + else: + raise scriptfailure("Unsupported platform") + +def run(cmd): + """Run a command in a subprocess""" + try: + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) + out = p.communicate()[0] + if p.returncode != 0: + raise Exception('Returned with code '+str(p.returncode)+'\n'+out) + except Exception,err: + log('Error in subprocess %s:\n' % str(err)) + raise + log(out) + return out + + +class MantidInstaller(object): + """ + Base-class for installer objects + """ + mantidInstaller = None + mantidPlotPath = None + no_uninstall = False + python_cmd = "python" + + def __init__(self, do_install, filepattern): + """Initialized with a pattern to + find a path to an installer + """ + if not do_install: + return + # Glob for packages + matches = glob.glob(os.path.abspath(filepattern)) + if len(matches) > 0: + # This will put the release mantid packages at the start and the nightly ones at the end + # with increasing version numbers + matches.sort() + # Make sure we don't get Vates + for match in matches: + if 'vates'in match: + matches.remove(match) + # Take the last one as it will have the highest version number + if len(matches) > 0: + self.mantidInstaller = os.path.join(os.getcwd(), matches[-1]) + log("Using installer " + self.mantidInstaller) + else: + raise RuntimeError('Unable to find installer package in "%s"' % os.getcwd()) + + def install(self): + self.do_install() + + def do_install(self): + raise NotImplementedError("Override the do_install method") + + def uninstall(self): + if not self.no_uninstall: + self.do_uninstall() + + def do_uninstall(self): + raise NotImplementedError("Override the do_uninstall method") + +class NSISInstaller(MantidInstaller): + """Uses an NSIS installer + to install Mantid + """ + + def __init__(self, do_install): + MantidInstaller.__init__(self, do_install, 'Mantid-*-win*.exe') + self.mantidPlotPath = 'C:/MantidInstall/bin/MantidPlot.exe' + self.python_cmd = "C:/MantidInstall/bin/python.exe" + + def do_install(self): + """ + The NSIS installer spawns a new process and returns immediately. + We use the start command with the /WAIT option to make it stay around + until completion. + The chained "&& exit 1" ensures that if the return code of the + installer > 0 then the resulting start process exits with a return code + of 1 so we can pick this up as a failure + """ + run('start "Installer" /wait ' + self.mantidInstaller + ' /S') + + def do_uninstall(self): + "Runs the uninstall exe" + uninstall_path = 'C:/MantidInstall/Uninstall.exe' + run('start "Uninstaller" /wait ' + uninstall_path + ' /S') + +class DebInstaller(MantidInstaller): + """Uses a deb package to install mantid + """ + + def __init__(self, do_install): + MantidInstaller.__init__(self, do_install, 'mantid*.deb') + package = os.path.basename(self.mantidInstaller) + if 'mantidnightly' in package: + self.mantidPlotPath = '/opt/mantidnightly/bin/MantidPlot' + elif 'mantidunstable' in package: + self.mantidPlotPath = '/opt/mantidunstable/bin/MantidPlot' + else: + self.mantidPlotPath = '/opt/Mantid/bin/MantidPlot' + + def do_install(self): + """Uses gdebi to run the install + """ + run('sudo gdebi -n ' + self.mantidInstaller) + + def do_uninstall(self): + """Removes the debian package + """ + package_name = os.path.basename(self.mantidInstaller).split("_")[0] + run('sudo dpkg --purge %s' % package_name) + +class RPMInstaller(MantidInstaller): + """Uses a rpm package to install mantid + """ + + def __init__(self, do_install): + MantidInstaller.__init__(self, do_install, 'mantid*.rpm') + package = os.path.basename(self.mantidInstaller) + if 'mantidnightly' in package: + self.mantidPlotPath = '/opt/mantidnightly/bin/MantidPlot' + elif 'mantidunstable' in package: + self.mantidPlotPath = '/opt/mantidunstable/bin/MantidPlot' + else: + self.mantidPlotPath = '/opt/Mantid/bin/MantidPlot' + + def do_install(self): + """Uses yum to run the install. Current user must be in sudoers + """ + try: + run('sudo yum -y install ' + self.mantidInstaller) + except Exception, exc: + # This reports an error if the same package is already installed + if 'is already installed' in str(exc): + log("Current version is up-to-date, continuing.\n") + pass + else: + raise + + def do_uninstall(self): + """Removes the rpm package + """ + package_name = os.path.basename(self.mantidInstaller).split("-")[0] + run('sudo yum -y erase %s' % package_name) + + +class DMGInstaller(MantidInstaller): + """Uses an OS X dmg file to install mantid + """ + def __init__(self, do_install): + MantidInstaller.__init__(self, do_install, 'mantid-*.dmg') + self.mantidPlotPath = '/Applications/MantidPlot.app/Contents/MacOS/MantidPlot' + os.environ['DYLD_LIBRARY_PATH'] = '/Applications/MantidPlot.app/Contents/MacOS' + + def do_install(self): + """Mounts the dmg and copies the application into the right place. + """ + p = subprocess.Popen(['hdiutil','attach',self.mantidInstaller],stdin=subprocess.PIPE,stdout=subprocess.PIPE) + p.stdin.write('yes') # This accepts the GPL + p.communicate()[0] # This captures (and discards) the GPL text + mantidInstallerName = os.path.basename(self.mantidInstaller) + mantidInstallerName = mantidInstallerName.replace('.dmg','') + run('sudo cp -r /Volumes/'+ mantidInstallerName+'/MantidPlot.app /Applications/' ) + run('hdiutil detach /Volumes/'+ mantidInstallerName+'/') + + def do_uninstall(self): + run('sudo rm -fr /Applications/MantidPlot.app/') diff --git a/Code/Mantid/Testing/SystemTests/scripts/performance/README.txt b/Code/Mantid/Testing/SystemTests/scripts/performance/README.txt new file mode 100644 index 000000000000..717d3e96cfe6 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/performance/README.txt @@ -0,0 +1 @@ +This is basically a fork of the performance test support code in the main Mantid repository (https://github.com/mantidproject/mantid/tree/master/Test/PerformanceTests) to enable performance monitoring of the system tests in a similar fashion. diff --git a/Code/Mantid/Testing/SystemTests/scripts/performance/analysis.py b/Code/Mantid/Testing/SystemTests/scripts/performance/analysis.py new file mode 100644 index 000000000000..c6d3429fae11 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/performance/analysis.py @@ -0,0 +1,699 @@ +""" Module containing functions for test +performance analyis, plotting, and saving +to other formats (CSV, PDF) """ + +import testresult +import os +import sys +import sqlresults +from sqlresults import get_results +import matplotlib +from pylab import * +import numpy as np +import datetime +import random + +# This is the date string format as returned by the database +DATE_STR_FORMAT = "%Y-%m-%d %H:%M:%S.%f" + +#============================================================================================ +def get_orderby_clause(last_num): + """Returns a order by clause that limits to the last # revisions """ + if last_num > 0: + return " ORDER BY revision DESC limit %d" % last_num + else: + return '' + + +#============================================================================================ +def get_data(name='', type='', x_field='revision', y_field='runtime', last_num=-1): + """Get the test runtime/iteration as a function of an X variable. + + Parameters + ---------- + name :: full name of the test + type :: type of test to filter by + x_field :: name of the field for the X axis. + e.g. 'revision' (default) + or 'date' : exact date/time of launch + or 'index' : using the date, but returning an index of build # + instead of the date (better scaling) + last_num :: only get the last this-many entries from the table, sorted by revision. + if < 0, then get everything + + Returns + ------- + x :: list of X values, sorted increasing + y :: list of runtime/iteration for each x + """ + + results = get_results(name, type, where_clause='', orderby_clause=get_orderby_clause(last_num)) + + # Data dict. Key = X variable; Value = (iterations total, runtime total) + data = {} + for res in results: + # Get the x field value + if x_field == 'index': + x = res['date'] + else: + x = res[x_field] + + if data.has_key(x): + old = data[x] + iters = old[0] + 1 # Iterations + runtime = old[1] + res[y_field] + else: + iters = 1 + runtime = res[y_field] + # Save the # of iterations and runtime + data[x] = (iters, runtime) + + # Now make a sorted list of (x, runtime/iteration) + sorted = [(x, y[1]/y[0]) for (x,y) in data.items()] + sorted.sort() + + x = [a for (a,b) in sorted] + # For index, convert into an integer index + if x_field == 'index': + x = range( len(x) ) + y = [b for (a,b) in sorted] + + return (x,y) + + +#============================================================================================ +def get_unique_fields(results, field): + """Given a list of TestResult, return a + list of all unique values of 'field'""" + out = set() + for res in results: + out.add( res[field] ) + return list(out) + +#============================================================================================ +def get_results_matching(results, field, value): + """Given a list of TestResult, + return a list of TestResult's where 'field' matches 'value'.""" + out = [] + for res in results: + if res[field] == value: + out.append(res) + return out + + +#============================================================================================ +def smart_ticks(index, values): + """On the current figure, set the ticks at X positions + given by index, with value given by values (ints). + But it tries to space them out in a reasonable way. + """ + if type(values[0]).__name__ == "unicode": + # Make the array of dates + dates = [] + for val in values: + try: + datetime.datetime.strptime(val, DATE_STR_FORMAT) + dates.append(val) + except: + pass + if len(dates) == 0: return + td = dates[-1] - dates[0] + if (td < datetime.timedelta(hours=1)): + values_str = [d.strftime("%M:%S") for d in dates] + elif (td < datetime.timedelta(days=1)): + values_str = [d.strftime("%H:%M") for d in dates] + else: + values_str = [d.strftime("%m-%d, %H:%M") for d in dates] + else: + # convert to list of strings + values_str = [str(val) for val in values] + + if len(values_str) == 0: return + + w = gcf().get_figwidth()*gcf().get_dpi() + spacing = w/len(index) + + tick_index = [] + tick_strings = [] + + space_available = 0 + for i in xrange(len(index)): + s = str(values_str[i]); + s_width = (len(s)+1) * 12.0 # About 12 pixels per letter? And add a space + space_available +=spacing + if space_available >= s_width: + space_available = 0 + tick_index.append(i) + tick_strings.append(s) + + xticks( tick_index, tick_strings ) + + + +#============================================================================================ +def plot_success_count(type='system', last_num=-1, x_field='revision'): + """ Plot the count of successful/failed tests vs revision number + + Parameters + ---------- + type :: 'system', or 'performance' + """ + results = get_results('', type, where_clause='', orderby_clause=get_orderby_clause(last_num)) + revisions = get_unique_fields(results, x_field) + + # Go through each revision + success = [] + fail = [] + for revision in revisions: + these = get_results_matching(results, x_field, revision) + succeeded = 0 + failed = 0 + for res in these: + if res["success"]: + succeeded += 1 + else: + failed += 1 + # Keep the list of them + success.append(succeeded) + fail.append(failed) + + figure() + revisions = np.array(revisions) + fail = np.array(fail) + success = np.array(success) + + index = np.arange(len(revisions)) +# p1 = bar(index, fail, color='r') +# p2 = bar(index, success, color='g', bottom=fail) +# legend( (p1[0], p2[0]), ('Failure', 'Success') ) + + p1 = fill_between(index, fail, 0, color='r') + p2 = fill_between(index, success+fail, fail, color='g') + #legend( (p1, p2), ('Failure', 'Success') ) + + smart_ticks( index, revisions) + + + ylabel('Success/Fail') + xlabel(x_field) + revsare = "all revs" + if last_num > 0: revsare = "last %d revs" % last_num + title("Success/Fail History of %s tests (%s)" % (type, revsare)) + + +#============================================================================================ +def plot_runtime(*args, **kwargs): + """ Call get_data() + + Parameters + ---------- + - See get_data() for the full list + """ + (x,y) = get_data(*args, **kwargs) + + figure() + index = np.arange(len(x)) + plot(index,y,'-b.') + smart_ticks( index, x) + ylabel('Runtime/iteration (sec)') + xlabel(kwargs['x_field']) + + last_num =kwargs.get('last_num',-1) + if last_num > 0: + title("Runtime History of %s (last %d revs)" % (kwargs['name'], kwargs["last_num"]) ) + else: + title("Runtime History of %s (all revs)" % kwargs['name']) + + + + +#============================================================================================ +def plot_memory(*args, **kwargs): + """ Call get_data() + + Parameters + ---------- + - See get_data() for the full list + """ + (x,y) = get_data(*args, **kwargs) + + figure() + index = np.arange(len(x)) + plot(index,y,'-b.') + smart_ticks( index, x) + ylabel("Memory 'loss' (MB)") + xlabel(kwargs['x_field']) + + last_num =kwargs.get('last_num',-1) + if last_num > 0: + title("Memory History of %s (last %d revs)" % (kwargs['name'], kwargs["last_num"]) ) + else: + title("Memory History of %s (all revs)" % kwargs['name']) + + + + + + + + + + + +# The default HTML header +default_html_header = """ + +""" + +default_html_footer = """""" + +#============================================================================================ +def make_css_file(path): + """ Make a save the report.css file to be used by all html """ + default_css = """ +table +{ +border-collapse:collapse; +background-color:FFAAAA; +} +table, th, td +{ +border: 1px solid black; +padding: 2px 6px; +} +.failedrow, .failedrow TD, .failedrow TH +{ +background-color:#FFAAAA; +color:black; +} +.alternaterow, .alternaterow TD, .alternaterow TH +{ +background-color:#FFFFAA; +color:black; +} +.error +{ +color:red; +font-weight: bold; +} + + """ + f = open(os.path.join(path, "report.css"), 'w') + f.write(default_css) + f.close() + +#============================================================================================ +def make_environment_html(res): + """Return a HTML string with details of test environment, taken from the + 'res' TestResult object""" + html = """ + + + +
Host name: %s
Environment: %s
Type of runner: %s
+ """ % (res['host'], res['environment'], res['runner']) + return html + +#============================================================================================ +def make_detailed_html_file(basedir, name, fig1, fig2, fig3, fig4, last_num): + """ Create a detailed HTML report for the named test """ + html = default_html_header + html += """

Detailed report for %s


""" % (name) + html += """runtime vs revision number (latest %d entries)\n""" % (fig1, last_num) + html += """runtime vs revision number\n""" % (fig2) + html += """memory vs revision number (latest %d entries)\n""" % (fig3, last_num) + html += """memory vs revision number\n""" % (fig4) + html += """

Test Results

""" + + fields = ['revision', 'date', 'commitid', 'compare', 'status', 'runtime', 'cpu_fraction', 'memory_change', 'variables'] + + table_row_header = "" + for field in fields: + if field == "runtime": field = "Runtime/Iter." + if field == "memory_change": field = "Memory 'loss'" + field = field[0].upper() + field[1:] + table_row_header += "%s" % field + table_row_header += "" + + html += """""" + table_row_header + + table_html = '' + results = get_results(name, type='', where_clause='') + sorted = [(res["revision"], res["variables"], res["date"], res) for res in results] + sorted.sort(reverse=False) + count = 0 + last_rev = 0 + commitid = '' + last_commitid = '' + row_class = '' + table_rows = [] + for (rev, variable, date, res) in sorted: + table_row_html = '' + if (rev != last_rev): + # Changed SVN revision. Swap row color + if row_class == '': + row_class = "class=alternaterow" + else: + row_class = '' + last_rev = rev + + if commitid != last_commitid: + last_commitid = commitid + + if res["success"]: + table_row_html += "\n" % row_class + else: + table_row_html += "\n" + + for field in fields: + val = '' + + if field == 'compare': + # Comparison to previous commit, if anything can be done + if (last_commitid != ""): + val = """diff""" % (last_commitid, commitid) + + else: + # Normal fields + val = res[field] + + # Trim the fractional seconds + if field=="date": + val = str(val)[0:19] + + # Add a trac link + if field=="commitid": + commitid = val + partial_commitid = val + if (len(partial_commitid) > 7): partial_commitid = partial_commitid[0:7]; + val = """%s""" % (commitid, partial_commitid) + + if field=="runtime": + val = "%.3f" % (res["runtime"]) + + table_row_html += "" % val + table_row_html += "\n\n" + table_rows.append(table_row_html) + + # Now print out all the rows in reverse order + table_rows.reverse() + for row in table_rows: + html += row +# # Add the row header every 30 entries +# count += 1 +# if count % 30 == 0: html += table_row_header + + # And one more at the end for good measure + html += table_row_header + html += "
%s
" + + if len(results)> 0: + html += """

Environment

+ %s""" % make_environment_html(results[0]) + + html += default_html_footer + +# last_date = sorted[-1][1]["date"] +# results = get_results(name, type='', get_log=False, where_clause=" date = '%s'" % last_date) +# if len(results)>0: +# html += + + f = open(os.path.join(basedir, "%s.htm" % name), "w") + html = html.replace("\n", os.linesep) # Fix line endings for windows + f.write(html) + f.close() + + +#============================================================================================ +def how_long_ago(timestr): + """Returns a string giving how long ago something happened, + in human-friendly way """ + import time + now = datetime.datetime.now() + then = datetime.datetime.strptime(timestr, DATE_STR_FORMAT) + td = (now-then) + sec = td.seconds + min = int(sec / 60) + hours = int(min / 60) + days = td.days + weeks = int(days / 7) + sec = sec % 60 + min = min % 60 + hours = hours % 24 + days = days % 7 + + if weeks > 0: + return "%dw%dd" % (weeks,days) + elif days > 0: + return "%dd%dh" % (days, hours) + elif hours > 0: + return "%dh%dm" % (hours, min) + elif min > 0: + return "%dm%ds" % (min, sec) + else: + return "%ds" % (sec) + + return "" + + +#============================================================================================ +def get_html_summary_table(test_names): + """Returns a html string summarizing the tests with these names """ + html = """ + + + + + + + + """ + + for name in test_names: + res = sqlresults.get_latest_result(name) + if not res is None: + # Calculate how long ago + + if not res["success"]: + html += """""" + else: + html += """""" + html += """""" % (name, name) + html += """""" % res['type'] + html += """""" % res['status'] + + # Friendly date + try: + date = datetime.datetime.strptime(res['date'], DATE_STR_FORMAT) + html += """""" % date.strftime("%b %d, %H:%M:%S") + except: + html += """""" + + html += """""" % res['runtime'] + html += """""" % res['memory_change'] + html += """""" + + html += """
Test NameTypeStatusWhen?Total runtime (s)Memory 'loss'
%s%s%s%s%s%s
""" + return html + + +#============================================================================================ +def generate_html_subproject_report(path, last_num, x_field='revision', starts_with=""): + """ HTML report for a subproject set of tests. + + starts_with : the prefix of the test name + + Returns: (filename saved, HTML for a page with ALL figures in it) + """ + basedir = os.path.abspath(path) + if not os.path.exists(basedir): + os.mkdir(basedir) + + + # Detect if you can do figures + dofigs = True + try: + figure() + rcParams['axes.titlesize'] = 'small' + except: + dofigs = False + + # Start the HTML + overview_html = "" + + # ------ Find the test names of interest ---------------- + # Limit with only those tests that exist in the latest rev + latest_rev = sqlresults.get_latest_revison() + temp_names = list(sqlresults.get_all_test_names(" revision = %d" % latest_rev)) + # Filter by their start + test_names = [] + for name in temp_names: + if name.startswith(starts_with): + test_names.append(name) + + test_names.sort() + + # -------- Report for each test ------------------------ + for name in test_names: + print "Plotting", name + overview_html += """

%s

\n""" % name + + # Path to the figures + fig1 = "%s.runtime.v.revision.png" % name + fig2 = "%s.runtime.v.revision.ALL.png" % name + fig3 = "%s.memory.v.revision.png" % name + fig4 = "%s.memory.v.revision.ALL.png" % name + + if dofigs: + # Only the latest X entries + plot_runtime(name=name,x_field=x_field,last_num=last_num) + savefig(os.path.join(basedir, fig1)) + close() + + # Plot all svn times + plot_runtime(name=name,x_field=x_field,last_num=-1) + savefig(os.path.join(basedir, fig2)) + close() + + # Only the latest X entries + plot_memory(name=name,x_field=x_field,y_field='memory_change',last_num=last_num) + savefig(os.path.join(basedir, fig3)) + close() + + # Plot all svn times + plot_memory(name=name,x_field=x_field,y_field='memory_change',last_num=-1) + savefig(os.path.join(basedir, fig4)) + close() + + overview_html += """runtime vs revision number""" % (fig1) + overview_html += """memory vs revision number\n""" % (fig3) + + make_detailed_html_file(basedir, name, fig1, fig2, fig3, fig4, last_num) + detailed_html = """
Detailed test report for %s +

+ """ % (name, name) + overview_html += detailed_html + + filename = starts_with + ".htm" + + return (filename, overview_html) + + + +#============================================================================================ +def generate_html_report(path, last_num, x_field='revision'): + """Make a comprehensive HTML report of runtime history for all tests. + Parameters + ---------- + path :: base path to the report folder + last_num :: in the shorter plot, how many SVN revs to show? + x_field :: the field to use as the x-axis. 'revision' or 'date' make sense + """ + basedir = os.path.abspath(path) + if not os.path.exists(basedir): + os.mkdir(basedir) + + # Make the CSS file to be used by all HTML + make_css_file(path) + + # Detect if you can do figures + dofigs = True + try: + figure() + except: + dofigs = False + + # --------- Start the HTML -------------- + html = default_html_header + html += """

Mantid System Tests Auto-Generated Report

""" + html += """

See an overview of performance plots for all tests by clicking here.

""" + if not dofigs: + html += """

There was an error generating plots. No figures will be present in the report.

""" + + html += """

Run Environment

+ %s + """ % ( make_environment_html(sqlresults.get_latest_result()) ) + + overview_html = "" + + # ------ Find the test names of interest ---------------- + # Limit with only those tests that exist in the latest rev + latest_rev = sqlresults.get_latest_revison() + test_names = list(sqlresults.get_all_test_names(" revision = %d" % latest_rev)) + test_names.sort() + + # ------ Find a list of subproject names -------- + subprojects = set() + for name in test_names: + n = name.find(".") + if n > 0: + subprojects.add( name[:n] ) + subprojects = list(subprojects) + subprojects.sort() + html += """

Test Subprojects

+ + """ + + for subproject in subprojects: + (filename, this_overview) = generate_html_subproject_report(path, last_num, x_field, subproject) + overview_html += this_overview + html += """ + """ % (filename, subproject) + html += """
%s
""" + + # --------- Table with the summary of latest results -------- + html += """

Overall Results Summary

""" + html += get_html_summary_table(test_names) + + # -------- Overall success history graphs ------------ + #if dofigs: + # # We report the overall success + # fig_path = "OverallSuccess.png" + # plot_success_count(type='',last_num=last_num, x_field=x_field) + # savefig(os.path.join(basedir, fig_path)) + # close() + # + # fig_path2 = "OverallSuccess.ALL.png" + # plot_success_count(type='',last_num=-1, x_field=x_field) + # savefig(os.path.join(basedir, fig_path2)) + # close() + # + # html += """

Overall Success/Failure

+ # + # + # """ % (fig_path, fig_path2) + + html += default_html_footer + + f = open(os.path.join(basedir, "report.htm"), "w") + html = html.replace("\n", os.linesep) # Fix line endings for windows + f.write(html) + f.close() + + # -------- Overview of plots ------------ + f = open(os.path.join(basedir, "overview_plot.htm"), "w") + overview_html = overview_html.replace("\n", os.linesep) # Fix line endings for windows + f.write(overview_html) + f.close() + + print "Report complete!" + + + + +#============================================================================================ +if __name__ == "__main__": + sqlresults.set_database_filename("MyFakeData.db") + # Make up some test data + if 0: + if os.path.exists("MyFakeData.db"): os.remove("MyFakeData.db") + sqlresults.generate_fake_data(300) + + + generate_html_report("../Report", 50) + +# plot_runtime(name='MyFakeTest', x_field='revision') +# plot_runtime(name='MyFakeTest', x_field='date') +# plot_success_count() +# show() + diff --git a/Code/Mantid/Testing/SystemTests/scripts/performance/make_report.py b/Code/Mantid/Testing/SystemTests/scripts/performance/make_report.py new file mode 100755 index 000000000000..1934d84e2a19 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/performance/make_report.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python + +import argparse +import sys +import os +import subprocess +import sqlite3 + +#==================================================================================== +def getSourceDir(): + """Returns the location of the source code.""" + import os + import sys + script = os.path.abspath(sys.argv[0]) + if os.path.islink(script): + script = os.path.realpath(script) + return os.path.dirname(script) + + + +def join_databases(dbfiles): + """Create a single DB joining several ones + Returns: filename created + """ + outfile = os.path.join(os.path.dirname(dbfiles[0]), "JoinedDatabases.db") + all_results = [] + # Get the results of each file + for dbfile in dbfiles: + print "Reading", dbfile + sqlresults.set_database_filename(dbfile) + these_results = sqlresults.get_results("") + all_results += these_results + # Write them into one + sqlresults.set_database_filename(outfile) + sqlresults.setup_database() + reporter = sqlresults.SQLResultReporter() + for res in all_results: + reporter.dispatchResults(res) + # Done! + return outfile + + + +#==================================================================================== +if __name__ == "__main__": + # Parse the command line + parser = argparse.ArgumentParser(description='Generates a HTML report using the Mantid System Tests results database') + + parser.add_argument('--path', dest='path', + default="./Report", + help='Path to the ouput HTML. Default "./Report".' ) + + parser.add_argument('--x_field', dest='x_field', + default="revision", + help="Field to use as the x-axis. Default: 'revision'. Other possibilities: 'date'.") + + parser.add_argument('dbfile', metavar='DBFILE', type=str, nargs='+', + default=["./MantidSystemTests.db"], + help='Required: Path to the SQL database file(s).') + + + args = parser.parse_args() + + # Import the manager definition + import analysis + import sqlresults + + if len(args.dbfile) > 1: + # Several files - join them into one big .db + dbfile = join_databases(args.dbfile) + else: + # Only one file - use it + dbfile = args.dbfile[0] + + + if not os.path.exists(dbfile): + print "Error! Could not find", dbfile + sys.exit(1) + + # This is where we look for the DB file + sqlresults.set_database_filename(dbfile) + + # Make the report + analysis.generate_html_report(args.path, 100, args.x_field) \ No newline at end of file diff --git a/Code/Mantid/Testing/SystemTests/scripts/performance/reporters.py b/Code/Mantid/Testing/SystemTests/scripts/performance/reporters.py new file mode 100644 index 000000000000..a2852ec1f4dd --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/performance/reporters.py @@ -0,0 +1,126 @@ +import os +import sys + +######################################################################### +# A base class to support report results in an appropriate manner +######################################################################### +class ResultReporter(object): + ''' + A base class for results reporting. In order to get the results in an + appropriate form, subclass this class and implement the dispatchResults + method. + ''' + + def __init__(self): + '''Initialize a class instance, e.g. connect to a database''' + pass + + def dispatchResults(self, result): + """ + Parameters + result: a TestResult object """ + raise NotImplementedError('"dispatchResults(self, result)" should be overridden in a derived class') + + +######################################################################### +# A class to report results as formatted text output +######################################################################### +class TextResultReporter(ResultReporter): + ''' + Report the results of a test using standard out + ''' + + def dispatchResults(self, result): + ''' + Print the results to standard out + ''' + nstars = 30 + print '*' * nstars + for (name, val) in result.data.items(): + str_val = str(val) + str_val = str_val.replace("\n", " ") + if len(str_val) > 50: + str_val = str_val[:50] + " . . . " + print ' ' + name.ljust(15) + '-> ', str_val + print '*' * nstars + + +######################################################################### +# A class to report results as formatted text output +######################################################################### +class LogArchivingReporter(ResultReporter): + ''' + Report the results of a test using standard out + ''' + def __init__(self, logarchive): + # Path to a log archiving folder + self.logarchive = os.path.abspath(logarchive) + if not os.path.exists(self.logarchive): + os.mkdir(self.logarchive) + + def dispatchResults(self, result): + ''' + Print the results to standard out + ''' + fullpath = os.path.join(self.logarchive, result.get_logarchive_filename()) + f = open(fullpath, "w") + f.write(result["log_contents"]) + f.close() + +######################################################################### +# A class to report results as XML that Hudson can interpret +######################################################################### +class JUnitXMLReporter(ResultReporter): + ''' + Report the results of a test to a JUnit style XML format + that can be read by Hudson/Jenkins + ''' + + def __init__(self, path): + # Path to .xml files + self._path = path + + def dispatchResults(self, result): + ''' + Make a junit .xml file + ''' + fullpath = os.path.join(self._path, "%s.xml" % result["name"]) + f = open(fullpath, 'w') + + names = result["name"].split(".") + suitename = names[0] + testname = ".".join(names[1:]) + + failure = "" + num_failures = 0 + if not result["success"]: + failure = """\n %s + """ % (result["status"], result["log_contents"]) + num_failures = 1 + + f.write(""" + + %s + + +""" % (suitename, num_failures, testname, result["runtime"], suitename, failure) ) + + + +if __name__=="__main__": + import testresult + rep = JUnitXMLReporter(".") + + res = testresult.TestResult() + res["name"] = "MyTestTest.Test" + res["status"] = "success maybe?" + res["success"] = True + res["runtime"] = 1.234 + rep.dispatchResults(res) + + res = testresult.TestResult() + res["name"] = "MyTestTest.OtherTest" + res["status"] = "failure" + res["success"] = False + res["runtime"] = 3.456 + rep.dispatchResults(res) diff --git a/Code/Mantid/Testing/SystemTests/scripts/performance/sqlresults.py b/Code/Mantid/Testing/SystemTests/scripts/performance/sqlresults.py new file mode 100644 index 000000000000..b7eb3e4289c4 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/performance/sqlresults.py @@ -0,0 +1,327 @@ +try: + import sqlite3 + has_sql = True +except ImportError: + has_sql = False + print "Error importing sqlite3. SQL will not work" + +import reporters +import datetime +import testresult +import os +import shutil +import math +import random + +#==================================================================================== +def getSourceDir(): + """Returns the location of the source code.""" + import os + import sys + script = os.path.abspath(sys.argv[0]) + if os.path.islink(script): + script = os.path.realpath(script) + return os.path.dirname(script) + + +#===================================================================== +# These are the table fields, in order +TABLE_FIELDS = ['date', 'name', 'type', 'host', 'environment', 'runner', + 'revision', 'commitid', 'runtime', 'cpu_fraction', + 'memory_change', 'success', + 'status', 'logarchive', 'variables'] + +#===================================================================== +# The default path to the database file +database_file = os.path.join(getSourceDir(), "MantidSystemTests.db") + +#===================================================================== +def get_database_filename(): + """Return the path to the database to use """ + return database_file + +#===================================================================== +def set_database_filename(value): + """Override the default database location""" + global database_file + database_file = value + +#===================================================================== +def SQLgetConnection(): + """ Get a connection to the SQL database """ + # These are automatic conversion factors + return sqlite3.connect(get_database_filename()) + + +#===================================================================== +def get_TestResult_from_row(row): + """Return a filled TestResult object from a "row" + obtained by selecting * from the TestRuns table + Returns + ------- + result :: TestResult object, with an extra + .testID member containing the ID into the table (testID field) + """ + res = testresult.TestResult() + res.testID = row[0] + # ------ Get each entry in the table --------- + for i in xrange(len(TABLE_FIELDS)): + res[TABLE_FIELDS[i]] = row[i+1] + + return (res) + + +#===================================================================== +def get_latest_result(name=''): + """Returns a TestResult object corresponding to the + last result in the table + Parameters + ---------- + name :: optional, test name to filter by""" + db = SQLgetConnection() + c = db.cursor() + where = "" + if name != "": where = " WHERE name='%s'" % name + query = """SELECT * FROM TestRuns %s ORDER BY testID DESC LIMIT 1;""" % where + c.execute(query) + # Get all rows - there should be only one + rows = c.fetchall() + c.close() + + if len(rows) > 0: + res = get_TestResult_from_row(rows[0]) + return res + else: + return None + +#===================================================================== +def get_results(name, type="", where_clause='', orderby_clause=''): + """Return a list of testresult.TestResult objects + generated from looking up in the table + Parameters: + name: test name to search for. Empty string = don't limit by name + type: limit by type; default empty string means = don't limit by type. + get_log : set to True to retrieve the log_contents too. + where_clause : an additional SQL "where" clause to further limit the search. + Do not include the WHERE keyword! + e.g "date > 2010 AND environment='mac'". + orderby_clause : a clause to order and/or limit the results. + e.g. "ORDER BY revision DESC limit 100" to get only the latest 100 revisions. + """ + out = [] + + db = SQLgetConnection() + c = db.cursor() + + query = "SELECT * FROM TestRuns " + + # Build up the where clause + where_clauses = [] + if name != "": + where_clauses.append(" name = '%s'" % name) + if (type != ""): + where_clauses.append(" type = '%s'" % type) + if (where_clause != ""): + where_clauses.append(" (" + where_clause + ")") + # Add it to the query + if len(where_clauses) > 0: + query += "WHERE " + " AND ".join(where_clauses) + # Now the ordering clause + query += " " + orderby_clause + + c.execute(query) + + # Get all rows + rows = c.fetchall() + + for row in rows: + # Turn the row into TestResult + res = get_TestResult_from_row(row) + + out.append(res) + c.close() + return out + + +#===================================================================== +def get_all_field_values(field_name, where_clause=""): + """Return a list of every entry of the given + field (e.g. 'name' or 'environment'). + Parameters: + field_name: field/column name to search for. + where_clause : an additional SQL "where" clause to further limit the search. + Do not include the WHERE keyword! + e.g "date > 2010 AND environment='mac'". + + """ + db = SQLgetConnection() + c = db.cursor() + + query = "SELECT (%s) FROM TestRuns " % field_name + if (where_clause != ""): + query += "WHERE " + where_clause + + c.execute(query) + + # Get all rows + rows = c.fetchall() + + out = [x for (x,) in rows] + + return out + +#===================================================================== +def get_latest_revison(): + """ Return the latest revision number """ + # Now get the latest revision + db = SQLgetConnection() + c = db.cursor() + query = "SELECT (revision) FROM Revisions ORDER BY revision DESC LIMIT 1;" + c.execute(query) + rows = c.fetchall() + if (len(rows)>0): + return int(rows[0][0]) + else: + return 0 + +#===================================================================== +def add_revision(): + """ Adds an entry with the current date/time to the table. + Retrieve the index of that entry = the "revision". + Returns the current revision""" + db = SQLgetConnection() + c = db.cursor() + query = "INSERT INTO Revisions VALUES(NULL, '%s');" % str(datetime.datetime.now()) + c.execute(query) + db.commit() + return get_latest_revison() + + +#===================================================================== +def get_all_test_names(where_clause=""): + """Returns a set containing all the UNIQUE test names in the database. + ---- + where_clause: Do not include the WHERE keyword! """ + return set(get_all_field_values('name', where_clause)) + + +#===================================================================== +def setup_database(): + """ Routine to set up the mysql database the first time. + WARNING: THIS DELETES ANY TABLES ALREADY THERE + """ + print "Setting up SQL database at",get_database_filename() + if os.path.exists(get_database_filename()): + print "Creating a backup at", get_database_filename()+".bak" + shutil.copyfile(get_database_filename(), get_database_filename()+".bak") + + db = SQLgetConnection() + + c = db.cursor() + try: + c.execute("DROP TABLE TestRuns;") + c.execute("DROP TABLE Revisions;") + except: + print "Error dropping tables. Perhaps one does not exist (this is normal on first run)." + + c.execute("""CREATE TABLE TestRuns ( + testID INTEGER PRIMARY KEY, + date DATETIME, name VARCHAR(60), type VARCHAR(20), + host VARCHAR(30), environment VARCHAR(50), runner VARCHAR(20), + revision INT, commitid VARCHAR(45), + runtime DOUBLE, cpu_fraction DOUBLE, memory_change INT, + success BOOL, + status VARCHAR(50), logarchive VARCHAR(80), + variables VARCHAR(200) + ); """) + + # Now a table that is just one entry per run (a fake "revision") + + c.execute("""CREATE TABLE Revisions ( + revision INTEGER PRIMARY KEY, + date DATETIME + ); """) + + +########################################################################### +# A class to report the results of stress tests to the Mantid Test database +# (requires sqlite3 module) +########################################################################### +class SQLResultReporter(reporters.ResultReporter): + ''' + Send the test results to the Mantid test results database + ''' + + def __init__(self): + pass + + + def dispatchResults(self, result): + ''' + Construct the SQL commands and send them to the databse + ''' + dbcxn = SQLgetConnection() + cur = dbcxn.cursor() + #last_id = dbcxn.insert_id() + + # Create the field for the log archive name + result["logarchive"] = result.get_logarchive_filename() + + valuessql = "INSERT INTO TestRuns VALUES(NULL, " + + # Insert the test results in the order of the table + for field in TABLE_FIELDS: + val = result[field] + # Make into a string + val_str = str(val) + + # Booleans must be 0 or 1 + if type(val).__name__ == "bool": + val_str = ["0", "1"][val] + + valuessql += "'" + val_str + "'," + + valuessql = valuessql.rstrip(',') + valuessql += ');' + cur.execute(valuessql) + # Save test id for iteration table + test_id = cur.lastrowid + + # Commit and close the connection + dbcxn.commit() + cur.close() + dbcxn.close() + + +#============================================================================================ +def generate_fake_data(num_extra = 0): + """ Make up some data for a database """ + print "Generating fake data..." + setup_database() + rep = SQLResultReporter() + for timer in [9400, 9410,9411, 9412] + range(9420,9440) + [9450, 9466] + range(9450, 9450+num_extra): + rev = add_revision() + for name in ["Project1.MyFakeTest", "Project1.AnotherFakeTest", "Project2.FakeTest", "Project2.OldTest"]: + if (name != "Project2.OldTest"): + result = testresult.TestResult() + result["name"] = name + result["date"] = datetime.datetime.now() + datetime.timedelta(days=timer, minutes=timer) + result["log_contents"] = "Revision %d" % rev + result["runtime"] = timer/10.0 + random.randrange(-2,2) + result["commitid"] = rev #'926bf82e36b4c90c95efc3f1151725696273de5a' + result["success"] = (random.randint(0,10) > 0) + result["status"] = ["failed","success"][result["success"]] + result["revision"] = rev + rep.dispatchResults(result) + print "... Fake data made." + + +#===================================================================== +if __name__ == "__main__": + set_database_filename("SqlResults.test.db") + generate_fake_data() + + res = get_latest_result() + print res + + diff --git a/Code/Mantid/Testing/SystemTests/scripts/performance/testresult.py b/Code/Mantid/Testing/SystemTests/scripts/performance/testresult.py new file mode 100644 index 000000000000..fd772de16a3d --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/performance/testresult.py @@ -0,0 +1,120 @@ +''' +Data object for a TestResult + +Copyright © 2009 STFC Rutherford Appleton Laboratories + +This file is part of Mantid. + +Mantid is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 3 of the License, or +(at your option) any later version. + +Mantid is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . + +File change history is stored at: . +''' + +import sys +import os +import reporters +import re +import time +import datetime +import platform +import subprocess +import tempfile +import sqlresults +import numpy as np + + + + +######################################################################### +######################################################################### +def envAsString(): + """ Return the environment as a string """ + if os.name == 'nt': + system = platform.system().lower()[:3] + arch = platform.architecture()[0][:2] + env = system + arch + elif os.name == 'mac': + env = platform.mac_ver()[0] + else: + env = " ".join(platform.dist()) + return env + + +######################################################################### +# A class to store the results of a test +######################################################################### +class TestResult(object): + ''' + Stores the results of each test so that they can be reported later. + ''' + + def __init__(self, + date = datetime.datetime.now(), + name="", + type="system", + host=platform.uname()[1], + environment=envAsString(), + runner="", + commitid='', + revision=0, + runtime=0.0, + speed_up=0.0, + cpu_fraction=0.0, + memory_change=0, + iterations=1, + success=False, + status="", + log_contents="", + variables=""): + """ Fill the TestResult object with the contents """ + self.data = {} + self.data["date"] = date + self.data["name"] = name + self.data["type"] = type + self.data["host"] = host + self.data["environment"] = environment + self.data["runner"] = runner + self.data["revision"] = revision + self.data["commitid"] = commitid + self.data["runtime"] = runtime + self.data["cpu_fraction"] = cpu_fraction + self.data["memory_change"] = memory_change + self.data["success"] = success + self.data["status"] = status + self.data["log_contents"] = log_contents + self.data["variables"] = variables + + + def get_logarchive_filename(self): + "Return a bare filename that will hold the archived log contents" + s = str(self.data["date"]) + s = s.replace(" ", "_") + s = s.replace(":", "-") + return "%s.%s.log" % (s, self.data["name"]) + + def __getitem__(self, key): + return self.data[key] + + def __setitem__(self, key, value): + self.data.__setitem__(key, value) + + def getData(self): + ''' Get the map storing the results ''' + return self.data + + def __str__(self): + return str(self.data) + + + diff --git a/Code/Mantid/Testing/SystemTests/scripts/performance/xunit_to_sql.py b/Code/Mantid/Testing/SystemTests/scripts/performance/xunit_to_sql.py new file mode 100755 index 000000000000..e70c27d91c99 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/performance/xunit_to_sql.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python +""" Module to convert XUnit XML to SQL database of test results of the same type used +by python system tests """ + +import argparse +import sys +import os +import sqlresults +from testresult import TestResult, envAsString +from xml.dom.minidom import parse, parseString +import re +import time +import datetime +import platform +import subprocess +import tempfile +import sqlresults +import numpy as np +import glob + +# Global SQL result reporter +sql_reporter = None +# Variables string for all tests +variables = "" +revision = 0 +commitid = '' + +def handle_testcase(case, suite_name): + """ Handle one test case and save it to DB""" + # Build the full name (Project.Suite.Case) + name = case.getAttribute("classname") + "." + case.getAttribute("name") + try: + time = float(case.getAttribute("time")) + except: + time = 0.0 + try: + total_time = float(case.getAttribute("totalTime")) + except: + total_time = 0.0 + try: + cpu_fraction = float(case.getAttribute("CPUFraction")) + except: + cpu_fraction = 0.0 + try: + memory_change = int(case.getElementsByTagName("memory").item(0).firstChild.nodeValue) + except: + memory_change = 0 + + + tr = TestResult(date = datetime.datetime.now(), + name=name, + type="performance", + host=platform.uname()[1], + environment=envAsString(), + runner="runSystemTests.py", + revision=revision, + commitid=commitid, + runtime=time, + cpu_fraction=cpu_fraction, + memory_change=memory_change, + success=True, + status="", + log_contents="", + variables=variables) + #print tr.data + # Now report it to SQL + sql_reporter.dispatchResults(tr) + +def handle_suite(suite): + """ Handle all the test cases in a suite """ + suite_name = suite.getAttribute("name") + cases = suite.getElementsByTagName("testcase") + for case in cases: + handle_testcase(case, suite_name) + + +def convert_xml(filename): + """Convert a single XML file to SQL db""" + # Parse the xml + print "Reading", filename + doc = parse(filename) + suites = doc.getElementsByTagName("testsuite") + for suite in suites: + handle_suite(suite) + + +#==================================================================================== +if __name__ == "__main__": + # Parse the command line + parser = argparse.ArgumentParser(description='Add the contents of Xunit-style XML test result files to a SQL database.') + + parser.add_argument('--db', dest='db', + default="./MantidPerformanceTests.db", + help='Full path to the SQLite database holding the results (default "./MantidPerformanceTests.db"). The database will be created if it does not exist.') + + parser.add_argument('--variables', dest='variables', + default="", + help='Optional string of comma-separated "VAR1NAME=VALUE,VAR2NAME=VALUE2" giving some parameters used, e.g. while building.') + + parser.add_argument('--commit', dest='commitid', + default="", + help='Commit ID of the current build (a 40-character SHA string).') + + parser.add_argument('xmlpath', metavar='XMLPATH', type=str, nargs='+', + default="", + help='Required: Path to the Xunit XML files.') + + args = parser.parse_args() + + # Setup the SQL database but only if it does not exist + sqlresults.set_database_filename(args.db) + if not os.path.exists(args.db): + sqlresults.setup_database() + # Set up the reporter + sql_reporter = sqlresults.SQLResultReporter() + + variables = args.variables + # Add a new revision and get the "revision" number + revision = sqlresults.add_revision() + # Save the commitid + commitid = args.commitid + + # If a directory has been provided, look there for all of the XML files + if os.path.isdir(args.xmlpath[0]): + xmldir = args.xmlpath[0] + if not os.path.isabs(xmldir): + xmldir = os.path.abspath(xmldir) + xmlfiles = glob.glob(os.path.join(xmldir, '*.xml')) + else: + xmlfiles = args.xmlpath + + # Convert each file + for file in xmlfiles: + convert_xml(file) + + + diff --git a/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py b/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py new file mode 100755 index 000000000000..88785cc679b0 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python + +import os +# set up the command line options +VERSION = "1.1" +DEFAULT_FRAMEWORK_LOC = os.path.dirname(os.path.realpath(__file__)) + "/../StressTestFramework" + +info = [] +info.append("This program will configure mantid run all of the system tests located in") +info.append("the 'SystemTests/AnalysisTests' directory and log the results in 'logs/'.") +info.append("This program will create a temporary 'Mantid.user.properties' file which") +info.append("it will rename to 'Mantid.user.properties.systest' upon completion. The") +info.append("current version of the code does not print to stdout while the test is") +info.append("running, so the impatient user may ^C to kill the process. In this case") +info.append("all of the tests that haven't been run will be marked as skipped in the") +info.append("full logs.") + +import optparse +parser = optparse.OptionParser("Usage: %prog [options]", None, + optparse.Option, VERSION, 'error', ' '.join(info)) +parser.add_option("-m", "--mantidpath", dest="mantidpath", + help="Location of mantid build") +parser.add_option("", "--email", action="store_true", + help="send an email with test status.") +parser.add_option("", "--frameworkLoc", + help="location of the stress test framework (default=%s)" % DEFAULT_FRAMEWORK_LOC) +parser.add_option("", "--disablepropmake", action="store_false", dest="makeprop", + help="By default this will move your properties file out of the way and create a new one. This option turns off this behavior.") +parser.add_option("-R", "--tests-regex", dest="testsInclude", + help="String specifying which tests to run. Simply uses 'string in testname'.") +parser.add_option("-E", "--excluderegex", dest="testsExclude", + help="String specifying which tests to not run. Simply uses 'string in testname'.") +loglevelChoices=["error", "warning", "notice", "information", "debug"] +parser.add_option("-l", "--loglevel", dest="loglevel", + choices=loglevelChoices, + help="Set the log level for test running: [" + ', '.join(loglevelChoices) + "]") +parser.add_option("", "--showskipped", dest="showskipped", action="store_true", + help="List the skipped tests.") +parser.add_option("", "--archivesearch", dest="archivesearch", action="store_true", + help="Turn on archive search for file finder.") +parser.set_defaults(frameworkLoc=DEFAULT_FRAMEWORK_LOC, mantidpath=None, makeprop=True, + loglevel="information") +(options, args) = parser.parse_args() + +# import the stress testing framework +import sys +import os +import platform +sys.path.append(options.frameworkLoc) +import stresstesting + +# Make sure the specified MantidFramework is picked up +# Use specified option if given +mantid_module_path = None +if options.mantidpath is not None: + mantid_module_path = options.mantidpath +elif os.path.exists("MantidFramework"): + pass # Current directory is in the already +elif 'MANTIDPATH' in os.environ: + mantid_module_path = os.environ['MANTIDPATH'] +else: + pass + +# Ensure that this is the one that is picked +sys.path.insert(0, mantid_module_path) + +# On Windows & OSX we need to ensure the mantid libraries in bin/Contents/MacOS can be found. +# Must be done before first import of mantid. This is the same as what a user would have to do to +# import mantid in a vanilla python session +# Unfortunately Python seems to know the path separator on each platform but +# not the dynamic library path variable name +if platform.system() == 'Windows': + path_var = "PATH" +elif platform.system() == 'Darwin': + path_var = "DYLD_LIBRARY_PATH" +else: + path_var = None +# Set the path +if path_var: + os.environ[path_var] = mantid_module_path + os.pathsep + os.environ.get(path_var, "") + +# Configure mantid +mtdconf = stresstesting.MantidFrameworkConfig(mantid_module_path, loglevel=options.loglevel, + archivesearch=options.archivesearch) +if options.makeprop: + mtdconf.config() + +# run the tests +reporter = stresstesting.XmlResultReporter(showSkipped=options.showskipped) +mgr = stresstesting.TestManager(mtdconf.testDir, output = [reporter], + testsInclude=options.testsInclude, testsExclude=options.testsExclude) +try: + mgr.executeTests() +except KeyboardInterrupt: + mgr.markSkipped("KeyboardInterrupt") + +# report the errors +success = reporter.reportStatus() +xml_report = open(os.path.join(mtdconf.saveDir, "SystemTestsReport.xml"),'w') +xml_report.write(reporter.getResults()) +xml_report.close() + +# put the configuratoin back to its original state +if options.makeprop: + mtdconf.restoreconfig() + +print +if mgr.skippedTests == mgr.totalTests: + print "All tests were skipped" + success = False # fail if everything was skipped +else: + percent = 1.-float(mgr.failedTests)/float(mgr.totalTests-mgr.skippedTests) + percent = int(100. * percent) + print "%d%s tests passed, %d tests failed out of %d (%d skipped)" % \ + (percent, '%', mgr.failedTests, (mgr.totalTests-mgr.skippedTests), mgr.skippedTests) +print 'All tests passed? ' + str(success) +if not success: + sys.exit(1) diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/README.md b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/README.md new file mode 100644 index 000000000000..820b616aa6b0 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/README.md @@ -0,0 +1 @@ +This directory stores the content links to the reference files for the system tests From 96e714ebf02559d549ddeb770958560d3bc1f1a2 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 9 Feb 2015 11:14:44 +0000 Subject: [PATCH 043/414] Ability to add spectra to plot Refs #11036 --- .../Indirect/IndirectTransmission.h | 2 + .../src/Indirect/IndirectTransmission.cpp | 26 ++- .../inc/MantidQtMantidWidgets/PreviewPlot.h | 20 ++- .../MantidWidgets/src/PreviewPlot.cpp | 150 ++++++++++++++++-- 4 files changed, 170 insertions(+), 28 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.h index c85568af87b7..66bfa664ed87 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.h @@ -4,6 +4,7 @@ #include "IndirectDataReductionTab.h" #include "ui_IndirectTransmission.h" #include "MantidKernel/System.h" +#include "MantidQtMantidWidgets/PreviewPlot.h" namespace MantidQt @@ -58,6 +59,7 @@ namespace CustomInterfaces private: Ui::IndirectTransmission m_uiForm; + MantidWidgets::PreviewPlot *m_plot; }; diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp index f68ec15caae4..2b8432b1cb71 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp @@ -2,8 +2,6 @@ #include -#include "MantidQtMantidWidgets/PreviewPlot.h" - using namespace Mantid::API; namespace MantidQt @@ -27,10 +25,10 @@ namespace CustomInterfaces /* m_uiForm.plotPreview->addWidget(m_plots["PreviewPlot"]); */ //TODO - MantidWidgets::PreviewPlot *plot = new MantidWidgets::PreviewPlot(m_parentWidget); - plot->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - plot->setCanvasColour(Qt::white); - m_uiForm.plotPreview->addWidget(plot); + m_plot = new MantidWidgets::PreviewPlot(m_parentWidget); + m_plot->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + m_plot->setCanvasColour(Qt::white); + m_uiForm.plotPreview->addWidget(m_plot); // Update the preview plot when the algorithm is complete connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(transAlgDone(bool))); @@ -131,18 +129,18 @@ namespace CustomInterfaces return; // Plot each spectrum - plotMiniPlot(QString::fromStdString(resultWsNames[0]), 0, "PreviewPlot", "SamCurve"); - plotMiniPlot(QString::fromStdString(resultWsNames[1]), 0, "PreviewPlot", "CanCurve"); - plotMiniPlot(QString::fromStdString(resultWsNames[2]), 0, "PreviewPlot", "TransCurve"); + m_plot->addSpectrum(QString::fromStdString(resultWsNames[0]), 0, Qt::red); //, "PreviewPlot", "SamCurve"); + m_plot->addSpectrum(QString::fromStdString(resultWsNames[1]), 0, Qt::black); //, "PreviewPlot", "CanCurve"); + m_plot->addSpectrum(QString::fromStdString(resultWsNames[2]), 0, Qt::green); //, "PreviewPlot", "TransCurve"); // Colour plots as per plot option - m_curves["SamCurve"]->setPen(QColor(Qt::red)); - m_curves["CanCurve"]->setPen(QColor(Qt::black)); - m_curves["TransCurve"]->setPen(QColor(Qt::green)); + /* m_curves["SamCurve"]->setPen(QColor(Qt::red)); */ + /* m_curves["CanCurve"]->setPen(QColor(Qt::black)); */ + /* m_curves["TransCurve"]->setPen(QColor(Qt::green)); */ // Set X range to data range - setXAxisToCurve("PreviewPlot", "TransCurve"); - m_plots["PreviewPlot"]->replot(); + /* setXAxisToCurve("PreviewPlot", "TransCurve"); */ + /* m_plots["PreviewPlot"]->replot(); */ } } // namespace CustomInterfaces diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h index 4a31c9d75049..63aa3f059213 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -54,6 +54,13 @@ namespace MantidWidgets Q_PROPERTY(bool allowZoom READ allowZoom WRITE setAllowZoom) public: + enum ScaleType + { + LINEAR, + LOGARITHMIC, + X_SQUARED + }; + PreviewPlot(QWidget *parent = NULL, bool init = true); virtual ~PreviewPlot(); @@ -66,18 +73,21 @@ namespace MantidWidgets bool allowZoom(); void setAllowZoom(bool allow); - void addSpectra(Mantid::API::MatrixWorkspace_sptr ws, int specIndex = 0); - void addSpectra(const QString & wsName, int specIndex = 0); + void addSpectrum(const Mantid::API::MatrixWorkspace_const_sptr ws, const size_t specIndex = 0, const QColor & curveColour = QColor()); + void addSpectrum(const QString & wsName, const size_t specIndex = 0, const QColor & curveColour = QColor()); - void removeSpectra(Mantid::API::MatrixWorkspace_sptr ws); - void removeSpectra(const QString & wsName); + void removeSpectrum(const Mantid::API::MatrixWorkspace_const_sptr ws); + void removeSpectrum(const QString & wsName); + public slots: void replot(); private: void handleRemoveEvent(Mantid::API::WorkspacePreDeleteNotification_ptr pNf); void handleReplaceEvent(Mantid::API::WorkspaceAfterReplaceNotification_ptr pNf); + void removeCurve(QwtPlotCurve *curve); + private: /// Poco Observers for ADS Notifications Poco::NObserver m_removeObserver; @@ -94,7 +104,7 @@ namespace MantidWidgets QwtPlot *m_plot; /// Map of workspaces to plot curves - QMap m_curves; + QMap m_curves; /// Plot manipulation tools QwtPlotMagnifier *m_magnifyTool; diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index 5a053fc95e51..670f1d79f74e 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -3,6 +3,9 @@ //------------------------------------------------------ #include "MantidQtMantidWidgets/PreviewPlot.h" +#include "MantidAPI/AnalysisDataService.h" +#include "MantidQtAPI/QwtWorkspaceSpectrumData.h" + #include #include #include @@ -12,6 +15,12 @@ #include using namespace MantidQt::MantidWidgets; +using namespace Mantid::API; + +namespace +{ + Mantid::Kernel::Logger g_log("PreviewPlot"); +} PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent), @@ -23,7 +32,7 @@ PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent) { if(init) { - Mantid::API::AnalysisDataServiceImpl& ads = Mantid::API::AnalysisDataService::Instance(); + AnalysisDataServiceImpl& ads = AnalysisDataService::Instance(); ads.notificationCenter.addObserver(m_removeObserver); ads.notificationCenter.addObserver(m_replaceObserver); @@ -48,8 +57,8 @@ PreviewPlot::~PreviewPlot() { if(m_init) { - Mantid::API::AnalysisDataService::Instance().notificationCenter.removeObserver(m_removeObserver); - Mantid::API::AnalysisDataService::Instance().notificationCenter.removeObserver(m_replaceObserver); + AnalysisDataService::Instance().notificationCenter.removeObserver(m_removeObserver); + AnalysisDataService::Instance().notificationCenter.removeObserver(m_replaceObserver); } } @@ -124,36 +133,159 @@ bool PreviewPlot::allowZoom() } -void PreviewPlot::addSpectra(Mantid::API::MatrixWorkspace_sptr ws, int specIndex) +/** + * Adds a workspace to the preview plot given a pointer to it. + * + * @param wsName Name of workspace in ADS + * @param specIndex Spectrrum index to plot + * @param curveColour Colour of curve to plot + */ +void PreviewPlot::addSpectrum(const MatrixWorkspace_const_sptr ws, const size_t specIndex, + const QColor & curveColour) { + using Mantid::MantidVec; + + // Check the spectrum index is in range + if(specIndex >= ws->getNumberHistograms()) + { + g_log.error() << "Workspace index is out of range, cannot plot." + << std::endl; + return; + } + + // Check the X axis is large enough + if(ws->readX(0).size() < 2) + { + g_log.error() << "X axis is too small to generate a histogram plot." + << std::endl; + return; + } + + // Create the plot data + const bool logScale(false), distribution(false); + QwtWorkspaceSpectrumData wsData(*ws, static_cast(specIndex), logScale, distribution); + + // Remove any existing curves + if(m_curves.contains(ws)) + removeCurve(m_curves[ws]); + + // Create the new curve + m_curves[ws] = new QwtPlotCurve(); + m_curves[ws]->setData(wsData); + m_curves[ws]->setPen(curveColour); + m_curves[ws]->attach(m_plot); + + // Replot + m_plot->replot(); } -void PreviewPlot::addSpectra(const QString & wsName, int specIndex) +/** + * Adds a workspace to the preview plot given its name. + * + * @param wsName Name of workspace in ADS + * @param specIndex Spectrrum index to plot + * @param curveColour Colour of curve to plot + */ +void PreviewPlot::addSpectrum(const QString & wsName, const size_t specIndex, + const QColor & curveColour) { + // Try to get a pointer from the name + std::string wsNameStr = wsName.toStdString(); + auto ws = AnalysisDataService::Instance().retrieveWS(wsName.toStdString()); + + if(!ws) + { + g_log.error() << wsNameStr + << " is not a MatrixWorkspace, not supported by PreviewPlot." + << std::endl; + return; + } + + addSpectrum(ws, specIndex, curveColour); } -void PreviewPlot::removeSpectra(Mantid::API::MatrixWorkspace_sptr ws) +/** + * Removes spectra from a gievn workspace from the plot given a pointer to it. + * + * @param ws Pointer to workspace + */ +void PreviewPlot::removeSpectrum(const MatrixWorkspace_const_sptr ws) { + // Remove the curve object + if(m_curves.contains(ws)) + removeCurve(m_curves[ws]); + + // Get the curve from the map + auto it = m_curves.find(ws); + + // Remove the curve from the map + if(it != m_curves.end()) + m_curves.erase(it); } -void PreviewPlot::removeSpectra(const QString & wsName) +/** + * Removes spectra from a gievn workspace from the plot given its name. + * + * @param wsName Name of workspace + */ +void PreviewPlot::removeSpectrum(const QString & wsName) { + // Try to get a pointer from the name + std::string wsNameStr = wsName.toStdString(); + auto ws = AnalysisDataService::Instance().retrieveWS(wsNameStr); + + if(!ws) + { + g_log.error() << wsNameStr + << " is not a MatrixWorkspace, not supported by PreviewPlot." + << std::endl; + return; + } + + removeSpectrum(ws); } +/** + * Replots the curves shown on the plot. + */ void PreviewPlot::replot() { + //TODO: replot curves? + + m_plot->replot(); +} + + +void PreviewPlot::handleRemoveEvent(WorkspacePreDeleteNotification_ptr pNf) +{ + //TODO } -void PreviewPlot::handleRemoveEvent(Mantid::API::WorkspacePreDeleteNotification_ptr pNf) +void PreviewPlot::handleReplaceEvent(WorkspaceAfterReplaceNotification_ptr pNf) { + //TODO } -void PreviewPlot::handleReplaceEvent(Mantid::API::WorkspaceAfterReplaceNotification_ptr pNf) +/** + * Removes a curve from the plot. + * + * @param curve Curve to remove + */ +void PreviewPlot::removeCurve(QwtPlotCurve * curve) { + if(!curve) + return; + + // Take it off the plot + curve->attach(NULL); + + // Delete it + delete curve; + curve = NULL; } From 3ce646364f37aaa9f5502a5420386a9e0c2dca3e Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 9 Feb 2015 12:10:26 +0000 Subject: [PATCH 044/414] Improve the way scales are handled Refs #11036 --- .../src/Indirect/IndirectTransmission.cpp | 28 +--- .../inc/MantidQtMantidWidgets/PreviewPlot.h | 7 + .../MantidWidgets/src/PreviewPlot.cpp | 133 ++++++++++++++---- 3 files changed, 118 insertions(+), 50 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp index 2b8432b1cb71..562a0bed2522 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp @@ -18,15 +18,8 @@ namespace CustomInterfaces m_uiForm.setupUi(parent); // Preview plot - m_plots["PreviewPlot"] = new QwtPlot(0); //m_parentWidget); - m_plots["PreviewPlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); - m_plots["PreviewPlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); - m_plots["PreviewPlot"]->setCanvasBackground(Qt::white); - /* m_uiForm.plotPreview->addWidget(m_plots["PreviewPlot"]); */ - - //TODO + // TODO: Move to UI file m_plot = new MantidWidgets::PreviewPlot(m_parentWidget); - m_plot->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_plot->setCanvasColour(Qt::white); m_uiForm.plotPreview->addWidget(m_plot); @@ -128,19 +121,12 @@ namespace CustomInterfaces if(resultWsNames.size() < 3) return; - // Plot each spectrum - m_plot->addSpectrum(QString::fromStdString(resultWsNames[0]), 0, Qt::red); //, "PreviewPlot", "SamCurve"); - m_plot->addSpectrum(QString::fromStdString(resultWsNames[1]), 0, Qt::black); //, "PreviewPlot", "CanCurve"); - m_plot->addSpectrum(QString::fromStdString(resultWsNames[2]), 0, Qt::green); //, "PreviewPlot", "TransCurve"); - - // Colour plots as per plot option - /* m_curves["SamCurve"]->setPen(QColor(Qt::red)); */ - /* m_curves["CanCurve"]->setPen(QColor(Qt::black)); */ - /* m_curves["TransCurve"]->setPen(QColor(Qt::green)); */ - - // Set X range to data range - /* setXAxisToCurve("PreviewPlot", "TransCurve"); */ - /* m_plots["PreviewPlot"]->replot(); */ + // Do plotting + m_plot->clear(); + m_plot->addSpectrum(QString::fromStdString(resultWsNames[0]), 0, Qt::red); + m_plot->addSpectrum(QString::fromStdString(resultWsNames[1]), 0, Qt::black); + m_plot->addSpectrum(QString::fromStdString(resultWsNames[2]), 0, Qt::green); + m_plot->resizeX(); } } // namespace CustomInterfaces diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h index 63aa3f059213..292a882d966c 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -73,6 +73,11 @@ namespace MantidWidgets bool allowZoom(); void setAllowZoom(bool allow); + void setAxisRange(QPair range, int axisID = QwtPlot::xBottom); + + QPair getCurveRange(const Mantid::API::MatrixWorkspace_const_sptr ws); + QPair getCurveRange(const QString & wsName); + void addSpectrum(const Mantid::API::MatrixWorkspace_const_sptr ws, const size_t specIndex = 0, const QColor & curveColour = QColor()); void addSpectrum(const QString & wsName, const size_t specIndex = 0, const QColor & curveColour = QColor()); @@ -80,6 +85,8 @@ namespace MantidWidgets void removeSpectrum(const QString & wsName); public slots: + void resizeX(); + void clear(); void replot(); private: diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index 670f1d79f74e..cbd145a93353 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -89,6 +89,17 @@ void PreviewPlot::setCanvasColour(const QColor & colour) } +/** + * Checks to see if the option to use the pan tool is enabled. + * + * @return True if tool is allowed + */ +bool PreviewPlot::allowPan() +{ + return m_allowPan; +} + + /** * Enables or disables the option to use the pan tool on the plot. * @@ -101,13 +112,13 @@ void PreviewPlot::setAllowPan(bool allow) /** - * Checks to see if the option to use the pan tool is enabled. + * Checks to see if the option to use the zoom tool is enabled. * * @return True if tool is allowed */ -bool PreviewPlot::allowPan() +bool PreviewPlot::allowZoom() { - return m_allowPan; + return m_allowZoom; } @@ -123,13 +134,58 @@ void PreviewPlot::setAllowZoom(bool allow) /** - * Checks to see if the option to use the zoom tool is enabled. + * Sets the range of the given axis scale to a given range. * - * @return True if tool is allowed + * @param range Pair of values for range + * @param axisID ID of axis */ -bool PreviewPlot::allowZoom() +void PreviewPlot::setAxisRange(QPair range, int axisID) { - return m_allowZoom; + if(range.first > range.second) + throw std::runtime_error("Supplied range is invalid."); + + m_plot->setAxisScale(axisID, range.first, range.second); + replot(); +} + + +/** + * Gets the X range of a curve given a pointer to the workspace. + * + * @param ws Pointer to workspace + */ +QPair PreviewPlot::getCurveRange(const Mantid::API::MatrixWorkspace_const_sptr ws) +{ + if(!m_curves.contains(ws)) + throw std::runtime_error("Workspace not on preview plot."); + + size_t numPoints = m_curves[ws]->data().size(); + + if(numPoints < 2) + return qMakePair(0.0, 0.0); + + double low = m_curves[ws]->data().x(0); + double high = m_curves[ws]->data().x(numPoints - 1); + + return qMakePair(low, high); +} + + +/** + * Gets the X range of a curve given its name. + * + * @param wsName Name of workspace + */ +QPair PreviewPlot::getCurveRange(const QString & wsName) +{ + // Try to get a pointer from the name + std::string wsNameStr = wsName.toStdString(); + auto ws = AnalysisDataService::Instance().retrieveWS(wsName.toStdString()); + + if(!ws) + throw std::runtime_error(wsNameStr + " is not a MatrixWorkspace, not supported by PreviewPlot."); + + return getCurveRange(ws); } @@ -147,19 +203,11 @@ void PreviewPlot::addSpectrum(const MatrixWorkspace_const_sptr ws, const size_t // Check the spectrum index is in range if(specIndex >= ws->getNumberHistograms()) - { - g_log.error() << "Workspace index is out of range, cannot plot." - << std::endl; - return; - } + throw std::runtime_error("Workspace index is out of range, cannot plot."); // Check the X axis is large enough if(ws->readX(0).size() < 2) - { - g_log.error() << "X axis is too small to generate a histogram plot." - << std::endl; - return; - } + throw std::runtime_error("X axis is too small to generate a histogram plot."); // Create the plot data const bool logScale(false), distribution(false); @@ -195,12 +243,7 @@ void PreviewPlot::addSpectrum(const QString & wsName, const size_t specIndex, auto ws = AnalysisDataService::Instance().retrieveWS(wsName.toStdString()); if(!ws) - { - g_log.error() << wsNameStr - << " is not a MatrixWorkspace, not supported by PreviewPlot." - << std::endl; - return; - } + throw std::runtime_error(wsNameStr + " is not a MatrixWorkspace, not supported by PreviewPlot."); addSpectrum(ws, specIndex, curveColour); } @@ -238,14 +281,47 @@ void PreviewPlot::removeSpectrum(const QString & wsName) auto ws = AnalysisDataService::Instance().retrieveWS(wsNameStr); if(!ws) + throw std::runtime_error(wsNameStr + " is not a MatrixWorkspace, not supported by PreviewPlot."); + + removeSpectrum(ws); +} + + +/** + * Resizes the X axis scale range to exactly fir the curves currently + * plotted on it. + */ +void PreviewPlot::resizeX() +{ + double low = DBL_MAX; + double high = DBL_MIN; + + for(auto it = m_curves.begin(); it != m_curves.end(); ++it) { - g_log.error() << wsNameStr - << " is not a MatrixWorkspace, not supported by PreviewPlot." - << std::endl; - return; + auto range = getCurveRange(it.key()); + + if(range.first < low) + low = range.first; + + if(range.second > high) + high = range.second; } - removeSpectrum(ws); + setAxisRange(qMakePair(low, high), QwtPlot::xBottom); +} + + +/** + * Removes all curves from the plot. + */ +void PreviewPlot::clear() +{ + for(auto it = m_curves.begin(); it != m_curves.end(); ++it) + removeCurve(it.value()); + + m_curves.clear(); + + replot(); } @@ -255,7 +331,6 @@ void PreviewPlot::removeSpectrum(const QString & wsName) void PreviewPlot::replot() { //TODO: replot curves? - m_plot->replot(); } From 7b31f84ba183d238b29a13cb4716f74a655a0c17 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Mon, 9 Feb 2015 12:36:33 +0000 Subject: [PATCH 045/414] Add an external data target for the system tests This is not added as a dependency and must be explicitly invoked. Refs #10870 --- Code/Mantid/Build/CMake/CommonSetup.cmake | 49 +++++++++++++---------- 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/Code/Mantid/Build/CMake/CommonSetup.cmake b/Code/Mantid/Build/CMake/CommonSetup.cmake index a9ee332cef5e..e9b8facc1f1e 100644 --- a/Code/Mantid/Build/CMake/CommonSetup.cmake +++ b/Code/Mantid/Build/CMake/CommonSetup.cmake @@ -305,28 +305,35 @@ endif() # External Data for testing ########################################################################### if ( CXXTEST_FOUND OR PYUNITTEST_FOUND ) - include ( MantidExternalData ) - -# None of our tests reference files directly as arguments so we have to manually -# call ExternalData_Expand_Arguments to register the files with the ExternalData -# mechanism -get_filename_component ( EXTERNALDATATEST_SOURCE_DIR ${PROJECT_SOURCE_DIR} ABSOLUTE ) -file( GLOB_RECURSE doctest_content_links - RELATIVE "${EXTERNALDATATEST_SOURCE_DIR}" "Testing/Data/DocTest/*.md5" ) -file( GLOB_RECURSE unittest_content_links - RELATIVE "${EXTERNALDATATEST_SOURCE_DIR}" "Testing/Data/UnitTest/*.md5" ) -set ( content_links "${doctest_content_links};${unittest_content_links}" ) -foreach(link ${content_links}) - string( REGEX REPLACE "\\.md5$" "" link ${link} ) - ExternalData_Expand_Arguments( StandardTestData - link_location - DATA{${link}} - ) -endforeach() + include ( MantidExternalData ) + + # None of our tests reference files directly as arguments so we have to manually + # call ExternalData_Expand_Arguments to register the files with the ExternalData + # mechanism + function(_create_data_target _targetname _content_link_patterns) + get_filename_component ( EXTERNALDATATEST_SOURCE_DIR ${PROJECT_SOURCE_DIR} ABSOLUTE ) + foreach(_pattern ${_content_link_patterns}) + file( GLOB_RECURSE _content_links + RELATIVE "${EXTERNALDATATEST_SOURCE_DIR}" ${_pattern} ) + foreach(link ${_content_links}) + string( REGEX REPLACE "\\.md5$" "" link ${link} ) + ExternalData_Expand_Arguments( ${_targetname} + link_location + DATA{${link}} + ) + endforeach() + endforeach() + # Create target to download data from the StandardTestData group. This must come after + # all tests have been added that reference the group, so we put it last. + ExternalData_Add_Target(${_targetname}) + endfunction() + + # We'll create two targets: + # - StandardTestData: data required by the unit tests and documentation tests + # - SystemTestData: data required for the system tests + _create_data_target(StandardTestData "Testing/Data/DocTest/*.md5;Testing/Data/UnitTest/*.md5") + _create_data_target(SystemTestData "Testing/Data/SystemTest/*.md5;Testing/SystemTests/tests/analysis/reference/*.md5") -# Create target to download data from the StandardTestData group. This must come after -# all tests have been added that reference the group, so we put it last. -ExternalData_Add_Target(StandardTestData) endif() ########################################################################### From 9190c787a17a672de332fa4fb53c3c65f5e635c3 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 9 Feb 2015 14:40:36 +0000 Subject: [PATCH 046/414] Added pan, zoom and magnify tools to plots Refs #11036 --- .../inc/MantidQtMantidWidgets/PreviewPlot.h | 14 ++ .../MantidWidgets/src/PreviewPlot.cpp | 144 +++++++++++++++++- 2 files changed, 154 insertions(+), 4 deletions(-) diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h index 292a882d966c..6eea74485f20 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -6,6 +6,9 @@ #include "MantidAPI/MatrixWorkspace.h" +#include +#include + #include #include #include @@ -85,6 +88,9 @@ namespace MantidWidgets void removeSpectrum(const QString & wsName); public slots: + void togglePanTool(bool enabled); + void toggleZoomTool(bool enabled); + void resetView(); void resizeX(); void clear(); void replot(); @@ -95,6 +101,10 @@ namespace MantidWidgets void removeCurve(QwtPlotCurve *curve); + private slots: + void showContextMenu(QPoint position); + void handleViewToolSelect(bool checked); + private: /// Poco Observers for ADS Notifications Poco::NObserver m_removeObserver; @@ -118,6 +128,10 @@ namespace MantidWidgets QwtPlotPanner *m_panTool; QwtPlotZoomer *m_zoomTool; + /// Context menu items + QMenu *m_contextMenu; + QActionGroup *m_plotToolGroup; + }; } diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index cbd145a93353..077bb2c77d76 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include @@ -28,7 +29,8 @@ PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent) m_replaceObserver(*this, &PreviewPlot::handleReplaceEvent), m_init(init), m_allowPan(false), m_allowZoom(false), m_plot(NULL), m_curves(), - m_magnifyTool(NULL), m_panTool(NULL), m_zoomTool(NULL) + m_magnifyTool(NULL), m_panTool(NULL), m_zoomTool(NULL), + m_contextMenu(new QMenu(this)) { if(init) { @@ -45,6 +47,54 @@ PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent) this->setLayout(mainLayout); } + + // Setup plot manipulation tools + m_zoomTool = new QwtPlotZoomer(QwtPlot::xBottom, QwtPlot::yLeft, + QwtPicker::DragSelection | QwtPicker::CornerToCorner, QwtPicker::AlwaysOff, m_plot->canvas()); + m_zoomTool->setEnabled(false); + + m_panTool = new QwtPlotPanner(m_plot->canvas()); + m_panTool->setEnabled(false); + + m_magnifyTool = new QwtPlotMagnifier(m_plot->canvas()); + m_magnifyTool->setMouseButton(Qt::NoButton); + m_magnifyTool->setEnabled(false); + + // Handle showing the context menu + m_plot->setContextMenuPolicy(Qt::CustomContextMenu); + connect(m_plot, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint))); + connect(m_contextMenu, SIGNAL(aboutToHide()), this, SLOT(contextMenuHide())); + + // Create the plot tool list for context menu + QMenu *viewToolMenu = new QMenu(m_contextMenu); + m_plotToolGroup = new QActionGroup(m_contextMenu); + m_plotToolGroup->setExclusive(true); + + QStringList plotTools; + plotTools << "None" << "Pan" << "Zoom"; + + for(auto it = plotTools.begin(); it != plotTools.end(); ++it) + { + QAction *toolAction = new QAction(*it, viewToolMenu); + toolAction->setCheckable(true); + connect(toolAction, SIGNAL(toggled(bool)), this, SLOT(handleViewToolSelect(bool))); + + // Add to the menu and action group + m_plotToolGroup->addAction(toolAction); + viewToolMenu->addAction(toolAction); + + // None is selected by default + toolAction->setChecked(*it == "None"); + } + + QAction *viewToolAction = new QAction("View Tool", this); + viewToolAction->setMenu(viewToolMenu); + m_contextMenu->addAction(viewToolAction); + + // Create the reset plot view option + QAction *resetPlotAction = new QAction("Reset Plot", m_contextMenu); + connect(resetPlotAction, SIGNAL(triggered()), this, SLOT(resetView())); + m_contextMenu->addAction(resetPlotAction); } @@ -199,8 +249,6 @@ QPair PreviewPlot::getCurveRange(const QString & wsName) void PreviewPlot::addSpectrum(const MatrixWorkspace_const_sptr ws, const size_t specIndex, const QColor & curveColour) { - using Mantid::MantidVec; - // Check the spectrum index is in range if(specIndex >= ws->getNumberHistograms()) throw std::runtime_error("Workspace index is out of range, cannot plot."); @@ -287,6 +335,52 @@ void PreviewPlot::removeSpectrum(const QString & wsName) } +/** + * Toggles the pan plot tool. + * + * @param enabled If the tool should be enabled + */ +void PreviewPlot::togglePanTool(bool enabled) +{ + // First disbale the zoom tool + if(enabled && m_zoomTool->isEnabled()) + m_zoomTool->setEnabled(false); + + m_panTool->setEnabled(enabled); + m_magnifyTool->setEnabled(enabled); +} + + +/** + * Toggles the zoom plot tool. + * + * @param enabled If the tool should be enabled + */ +void PreviewPlot::toggleZoomTool(bool enabled) +{ + // First disbale the pan tool + if(enabled && m_panTool->isEnabled()) + m_panTool->setEnabled(false); + + m_zoomTool->setEnabled(enabled); + m_magnifyTool->setEnabled(enabled); +} + + +/** + * Resets the view to a sensible default. + */ +void PreviewPlot::resetView() +{ + // Auto scale the axis + m_plot->setAxisAutoScale(QwtPlot::xBottom); + m_plot->setAxisAutoScale(QwtPlot::yLeft); + + // Set this as the default zoom level + m_zoomTool->setZoomBase(true); +} + + /** * Resizes the X axis scale range to exactly fir the curves currently * plotted on it. @@ -330,7 +424,6 @@ void PreviewPlot::clear() */ void PreviewPlot::replot() { - //TODO: replot curves? m_plot->replot(); } @@ -364,3 +457,46 @@ void PreviewPlot::removeCurve(QwtPlotCurve * curve) delete curve; curve = NULL; } + + +/** + * Handles displaying the context menu when a user right clicks on the plot. + * + * @param position Position at which to show menu + */ +void PreviewPlot::showContextMenu(QPoint position) +{ + // Show the context menu + m_contextMenu->popup(m_plot->mapToGlobal(position)); +} + + +/** + * Handles the view tool being selected from the context menu. + * + * @param checked If the option was checked + */ +void PreviewPlot::handleViewToolSelect(bool checked) +{ + if(!checked) + return; + + QAction *selectedPlotType = m_plotToolGroup->checkedAction(); + if(!selectedPlotType) + return; + + QString selectedTool = selectedPlotType->text(); + if(selectedTool == "None") + { + togglePanTool(false); + toggleZoomTool(false); + } + else if(selectedTool == "Pan") + { + togglePanTool(true); + } + else if(selectedTool == "Zoom") + { + toggleZoomTool(true); + } +} From 89c98f89c7d4fda01ba98345e69980d280cb681c Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 9 Feb 2015 15:07:06 +0000 Subject: [PATCH 047/414] Add more plots on indirect custom interfaces Refs #11036 --- .../Indirect/IndirectDiagnostics.ui | 16 +++++++++++- .../Indirect/IndirectMoments.ui | 16 +++++++++++- .../Indirect/IndirectTransmission.h | 2 -- .../Indirect/IndirectTransmission.ui | 18 ++++++++++--- .../src/Indirect/IndirectDiagnostics.cpp | 16 +++--------- .../src/Indirect/IndirectMoments.cpp | 26 ++++--------------- .../src/Indirect/IndirectTransmission.cpp | 16 ++++-------- .../MantidWidgets/src/PreviewPlot.cpp | 1 - 8 files changed, 57 insertions(+), 54 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDiagnostics.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDiagnostics.ui index a8f59082c4f4..0e6a79b6211b 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDiagnostics.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDiagnostics.ui @@ -119,7 +119,15 @@ - + + + + 255 + 255 + 255 + + + @@ -196,6 +204,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.ui index 8be1b8826496..a2ad05d818c9 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.ui @@ -117,7 +117,15 @@ 6 - + + + + 255 + 255 + 255 + + + @@ -233,6 +241,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.h index 66bfa664ed87..c85568af87b7 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.h @@ -4,7 +4,6 @@ #include "IndirectDataReductionTab.h" #include "ui_IndirectTransmission.h" #include "MantidKernel/System.h" -#include "MantidQtMantidWidgets/PreviewPlot.h" namespace MantidQt @@ -59,7 +58,6 @@ namespace CustomInterfaces private: Ui::IndirectTransmission m_uiForm; - MantidWidgets::PreviewPlot *m_plot; }; diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.ui index d2980679fa4d..6667bfc95c9d 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.ui @@ -104,11 +104,15 @@ - - - QLayout::SetMinimumSize + + + + 255 + 255 + 255 + - + @@ -224,6 +228,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp index 5e18f4558c9a..9c3a081b21b5 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp @@ -83,14 +83,6 @@ namespace CustomInterfaces // Refresh the plot window m_plots["SlicePlot"]->replot(); - // Preview plot - m_plots["SlicePreviewPlot"] = new QwtPlot(m_parentWidget); - m_plots["SlicePreviewPlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); - m_plots["SlicePreviewPlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); - m_plots["SlicePreviewPlot"]->setCanvasBackground(Qt::white); - m_uiForm.plotPreview->addWidget(m_plots["SlicePreviewPlot"]); - m_plots["SlicePreviewPlot"]->replot(); - // SIGNAL/SLOT CONNECTIONS // Update instrument information when a new instrument config is selected @@ -424,11 +416,9 @@ namespace CustomInterfaces m_pythonExportWsName = sliceWs->getName(); // Plot result spectrum - plotMiniPlot(sliceWs, 0, "SlicePreviewPlot", "SlicePreviewCurve"); - - // Set X range to data range - setXAxisToCurve("SlicePreviewPlot", "SlicePreviewCurve"); - m_plots["SlicePreviewPlot"]->replot(); + m_uiForm.ppSlicePreview->clear(); + m_uiForm.ppSlicePreview->addSpectrum(sliceWs, 0); + m_uiForm.ppSlicePreview->resizeX(); // Ungroup the output workspace sliceOutputGroup->removeAll(); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp index d0ba6815bd4c..148f0aae6a20 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp @@ -36,17 +36,6 @@ namespace CustomInterfaces // Add plot to UI m_uiForm.plotRaw->addWidget(m_plots["MomentsPlot"]); - // PREVIEW PLOT - m_plots["MomentsPreviewPlot"] = new QwtPlot(m_parentWidget); - - // Initilise plot - m_plots["MomentsPreviewPlot"]->setCanvasBackground(Qt::white); - m_plots["MomentsPreviewPlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); - m_plots["MomentsPreviewPlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); - - // Add plot to UI - m_uiForm.plotPreview->addWidget(m_plots["MomentsPreviewPlot"]); - // PROPERTY TREE m_propTrees["MomentsPropTree"] = new QtTreePropertyBrowser(); m_propTrees["MomentsPropTree"]->setFactoryForManager(m_dblManager, m_dblEdFac); @@ -253,16 +242,11 @@ namespace CustomInterfaces return; // Plot each spectrum - plotMiniPlot(QString::fromStdString(resultWsNames[0]), 0, "MomentsPreviewPlot", "Moments_M0"); - plotMiniPlot(QString::fromStdString(resultWsNames[2]), 0, "MomentsPreviewPlot", "Moments_M2"); - plotMiniPlot(QString::fromStdString(resultWsNames[3]), 0, "MomentsPreviewPlot", "Moments_M4"); - - // Colour plots as close to plot output as possible - m_curves["Moments_M0"]->setPen(QColor(Qt::green)); - m_curves["Moments_M2"]->setPen(QColor(Qt::black)); - m_curves["Moments_M4"]->setPen(QColor(Qt::red)); - - m_plots["MomentsPreviewPlot"]->replot(); + m_uiForm.ppMomentsPreview->clear(); + m_uiForm.ppMomentsPreview->addSpectrum(QString::fromStdString(resultWsNames[0]), 0, Qt::green); + m_uiForm.ppMomentsPreview->addSpectrum(QString::fromStdString(resultWsNames[2]), 0, Qt::black); + m_uiForm.ppMomentsPreview->addSpectrum(QString::fromStdString(resultWsNames[3]), 0, Qt::red); + m_uiForm.ppMomentsPreview->resizeX(); } } // namespace CustomInterfaces diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp index 562a0bed2522..0f7024ecfb38 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp @@ -17,12 +17,6 @@ namespace CustomInterfaces { m_uiForm.setupUi(parent); - // Preview plot - // TODO: Move to UI file - m_plot = new MantidWidgets::PreviewPlot(m_parentWidget); - m_plot->setCanvasColour(Qt::white); - m_uiForm.plotPreview->addWidget(m_plot); - // Update the preview plot when the algorithm is complete connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(transAlgDone(bool))); connect(m_uiForm.dsSampleInput, SIGNAL(dataReady(QString)), this, SLOT(dataLoaded())); @@ -122,11 +116,11 @@ namespace CustomInterfaces return; // Do plotting - m_plot->clear(); - m_plot->addSpectrum(QString::fromStdString(resultWsNames[0]), 0, Qt::red); - m_plot->addSpectrum(QString::fromStdString(resultWsNames[1]), 0, Qt::black); - m_plot->addSpectrum(QString::fromStdString(resultWsNames[2]), 0, Qt::green); - m_plot->resizeX(); + m_uiForm.ppPlot->clear(); + m_uiForm.ppPlot->addSpectrum(QString::fromStdString(resultWsNames[0]), 0, Qt::red); + m_uiForm.ppPlot->addSpectrum(QString::fromStdString(resultWsNames[1]), 0, Qt::black); + m_uiForm.ppPlot->addSpectrum(QString::fromStdString(resultWsNames[2]), 0, Qt::green); + m_uiForm.ppPlot->resizeX(); } } // namespace CustomInterfaces diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index 077bb2c77d76..21ec7fef227f 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -63,7 +63,6 @@ PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent) // Handle showing the context menu m_plot->setContextMenuPolicy(Qt::CustomContextMenu); connect(m_plot, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint))); - connect(m_contextMenu, SIGNAL(aboutToHide()), this, SLOT(contextMenuHide())); // Create the plot tool list for context menu QMenu *viewToolMenu = new QMenu(m_contextMenu); From c7e744ac4fda568d33fb179871e83da5c0b41a80 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Mon, 9 Feb 2015 15:08:28 +0000 Subject: [PATCH 048/414] Re #9556 Splitting gz into ZFKT and HKT --- .../CurveFitting/src/DynamicKuboToyabe.cpp | 134 +++++++++++------- 1 file changed, 84 insertions(+), 50 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index f28e0f075a8e..2193a42fdaec 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -137,36 +137,20 @@ double f1(const double x, const double G, const double w0) { } // Zero Field Kubo Toyabe relaxation function -double ZFKT (double q){ +double ZFKT (const double x, const double G){ + const double q = G*G*x*x; return (0.3333333333 + 0.6666666667*exp(-0.5*q)*(1-q)); } -// Relaxation function -double gz (const double x, const double G, const double F) +// Non-Zero field Kubo Toyabe relaxation function +double HKT (const double x, const double G, const double F) { - double w0 = 2.0*3.1415926536*0.01355342*F; - const double q = G*G*x*x; - - if (w0 == 0.0) { - // Zero field - return (ZFKT(q)); - } - else { - // Non-zero field - - if (F>2.0*G) { - w0 = 2*3.1415926*0.01355342*F ; - } else { - w0 =2*3.1415926*0.01355342*2.0*G; - } - - double p = G*G/(w0*w0); - double HKT = 1.0-2.0*p*(1-exp(-q/2.0)*cos(w0*x))+2.0*p*p*w0*integrate(f1,0.0,x,G,w0); - if (F>2.0*G) {return (HKT);} - else {return (ZFKT(q)+ (F/2.0/G)*(HKT-ZFKT(q)));} - - } + const double w0 = 2.0*3.1415926536*0.01355342*F; + const double q = G*G*x*x; + const double p = G*G/(w0*w0); + double hkt = 1.0-2.0*p*(1-exp(-q/2.0)*cos(w0*x))+2.0*p*p*w0*integrate(f1,0.0,x,G,w0); + return hkt; } // Dynamic Kubo Toyabe function @@ -180,55 +164,105 @@ void DynamicKuboToyabe::function1D(double* out, const double* xValues, const siz // Zero hopping rate if (v == 0.0) { - for (size_t i = 0; i < nData; i++) { - out[i] = A*gz(xValues[i],G,F); - } + + // Zero external field + if ( F == 0.0 ){ + for (size_t i = 0; i < nData; i++) { + out[i] = A*ZFKT(xValues[i],G); + } + } + // Non-zero external field + else{ + for (size_t i = 0; i < nData; i++) { + out[i] = A*HKT(xValues[i],G,F); + } + } } // Non-zero hopping rate else { // Make sure stepsize is smaller than spacing between xValues - int n = 1000; + //int n = 1000; //while (n funcG(n); + double efac1=exp(-v*stepsize); // survival prob for step + double efac2=(1.0-efac1); // hop prob ~ hoprate*step + // Mark's implementation - for (int i = 0; i < n; i++) { + if ( F == 0.0 ){ + // Zero field - double efac1=exp(-v*stepsize); // survival prob for step - double efac2=(1.0-efac1); // hop prob ~ hoprate*step + for (int i = 0; i < n; i++) { - funcG[0]=gz(0,G,F); - funcG[1]=gz(stepsize,G,F); + funcG[0]=ZFKT(0,G); + funcG[1]=ZFKT(stepsize,G); - for(i=1; i Date: Mon, 9 Feb 2015 15:21:41 +0000 Subject: [PATCH 049/414] Allow a RangeSelector to take a PreviewPlot in constructor Refs #11036 --- .../Indirect/IndirectDiagnostics.ui | 10 +++++++- .../src/Indirect/IndirectDiagnostics.cpp | 19 ++++---------- .../inc/MantidQtMantidWidgets/PreviewPlot.h | 1 + .../inc/MantidQtMantidWidgets/RangeSelector.h | 7 ++++-- .../MantidWidgets/src/RangeSelector.cpp | 25 ++++++++++++++----- 5 files changed, 39 insertions(+), 23 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDiagnostics.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDiagnostics.ui index 0e6a79b6211b..dc3241d5e049 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDiagnostics.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDiagnostics.ui @@ -107,7 +107,15 @@
- + + + + 255 + 255 + 255 + + +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp index 9c3a081b21b5..ff4a4c39aa94 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp @@ -67,22 +67,13 @@ namespace CustomInterfaces m_propTrees["SlicePropTree"]->addProperty(m_properties["Range2"]); // Slice plot - m_plots["SlicePlot"] = new QwtPlot(m_parentWidget); - m_rangeSelectors["SlicePeak"] = new MantidWidgets::RangeSelector(m_plots["SlicePlot"]); - m_rangeSelectors["SliceBackground"] = new MantidWidgets::RangeSelector(m_plots["SlicePlot"]); - - m_plots["SlicePlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); - m_plots["SlicePlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); - m_plots["SlicePlot"]->setCanvasBackground(Qt::white); - m_uiForm.plotRaw->addWidget(m_plots["SlicePlot"]); + m_rangeSelectors["SlicePeak"] = new MantidWidgets::RangeSelector(m_uiForm.ppRawPlot); + m_rangeSelectors["SliceBackground"] = new MantidWidgets::RangeSelector(m_uiForm.ppRawPlot); // Setup second range m_rangeSelectors["SliceBackground"]->setColour(Qt::darkGreen); // Dark green for background m_rangeSelectors["SliceBackground"]->setRange(m_rangeSelectors["SlicePeak"]->getRange()); - // Refresh the plot window - m_plots["SlicePlot"]->replot(); - // SIGNAL/SLOT CONNECTIONS // Update instrument information when a new instrument config is selected @@ -267,13 +258,13 @@ namespace CustomInterfaces const Mantid::MantidVec & dataX = input->readX(0); std::pair range(dataX.front(), dataX.back()); - plotMiniPlot(input, 0, "SlicePlot"); - setXAxisToCurve("SlicePlot", "SlicePlot"); + m_uiForm.ppRawPlot->clear(); + m_uiForm.ppRawPlot->addSpectrum(input, 0); setPlotRange("SlicePeak", m_properties["PeakStart"], m_properties["PeakEnd"], range); setPlotRange("SliceBackground", m_properties["BackgroundStart"], m_properties["BackgroundEnd"], range); - replot("SlicePlot"); + m_uiForm.ppRawPlot->resizeX(); } else { diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h index 6eea74485f20..26454be87349 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -118,6 +118,7 @@ namespace MantidWidgets bool m_allowZoom; /// The plot its self + friend class RangeSelector; QwtPlot *m_plot; /// Map of workspaces to plot curves diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RangeSelector.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RangeSelector.h index 567c20dab316..0b16b896cdce 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RangeSelector.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RangeSelector.h @@ -2,6 +2,7 @@ #define MANTIDQT_MANTIDWIDGET_POSHPLOTTING_H #include "WidgetDllOption.h" +#include "PreviewPlot.h" #include #include @@ -25,6 +26,7 @@ namespace MantidWidgets enum SelectType { XMINMAX, XSINGLE, YMINMAX, YSINGLE }; RangeSelector(QwtPlot* plot, SelectType type=XMINMAX, bool visible=true, bool infoOnly=false); + RangeSelector(PreviewPlot* plot, SelectType type=XMINMAX, bool visible=true, bool infoOnly=false); ~RangeSelector() {}; std::pair getRange(); @@ -39,7 +41,7 @@ namespace MantidWidgets void rangeChanged(double, double); void selectionChanged(double, double); void selectionChangedLazy(double, double); - + public slots: void setRange(double, double); void setMinimum(double); ///< outside setting of value @@ -51,6 +53,7 @@ namespace MantidWidgets void setVisible(bool state); private: + void init(); void setMin(double val); void setMax(double val); void setMaxMin(const double min, const double max); @@ -69,7 +72,7 @@ namespace MantidWidgets double m_max; double m_lower; ///< lowest allowed value for range double m_higher; ///< highest allowed value for range - + QwtPlotCanvas* m_canvas; QwtPlot* m_plot; diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/RangeSelector.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/RangeSelector.cpp index f4f6df930a45..07f087f3eecc 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/RangeSelector.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/RangeSelector.cpp @@ -7,12 +7,25 @@ using namespace MantidQt::MantidWidgets; -RangeSelector::RangeSelector(QwtPlot* plot, SelectType type, - bool visible, bool infoOnly) - : QwtPlotPicker(plot->canvas()), m_type(type), m_min(0.0),m_max(0.0), m_lower(0.0), - m_higher(0.0), m_canvas(plot->canvas()), m_plot(plot),m_mrkMin(NULL), m_mrkMax(NULL), - m_minChanging(false), m_maxChanging(false),m_infoOnly(infoOnly), m_visible(visible), +RangeSelector::RangeSelector(QwtPlot* plot, SelectType type, bool visible, bool infoOnly) + : QwtPlotPicker(plot->canvas()), m_type(type), m_min(0.0) ,m_max(0.0), m_lower(0.0), + m_higher(0.0), m_canvas(plot->canvas()), m_plot(plot), m_mrkMin(NULL), m_mrkMax(NULL), + m_minChanging(false), m_maxChanging(false), m_infoOnly(infoOnly), m_visible(visible), m_pen(NULL), m_movCursor() +{ + init(); +} + +RangeSelector::RangeSelector(PreviewPlot* plot, SelectType type, bool visible, bool infoOnly) + : QwtPlotPicker(plot->m_plot->canvas()), m_type(type), m_min(0.0) ,m_max(0.0), m_lower(0.0), + m_higher(0.0), m_canvas(plot->m_plot->canvas()), m_plot(plot->m_plot), m_mrkMin(NULL), m_mrkMax(NULL), + m_minChanging(false), m_maxChanging(false), m_infoOnly(infoOnly), m_visible(visible), + m_pen(NULL), m_movCursor() +{ + init(); +} + +void RangeSelector::init() { m_canvas->installEventFilter(this); @@ -22,7 +35,7 @@ RangeSelector::RangeSelector(QwtPlot* plot, SelectType type, m_mrkMax = new QwtPlotMarker(); QwtPlotMarker::LineStyle lineStyle; - + switch ( m_type ) { case XMINMAX: From e004ccafebdc9f278f7243bff0486ae8e9c33f52 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 9 Feb 2015 16:16:51 +0000 Subject: [PATCH 050/414] Added ability to switch axis types Still need to do a scale engine for x^2 scale Refs #11036 --- .../inc/MantidQtMantidWidgets/PreviewPlot.h | 18 +- .../MantidWidgets/src/PreviewPlot.cpp | 155 +++++++++++++++--- 2 files changed, 140 insertions(+), 33 deletions(-) diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h index 26454be87349..a16a11109b3f 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -55,15 +55,9 @@ namespace MantidWidgets Q_PROPERTY(QColor canvasColour READ canvasColour WRITE setCanvasColour) Q_PROPERTY(bool allowPan READ allowPan WRITE setAllowPan) Q_PROPERTY(bool allowZoom READ allowZoom WRITE setAllowZoom) + Q_PROPERTY(bool showLegend READ legendIsShown WRITE showLegend) public: - enum ScaleType - { - LINEAR, - LOGARITHMIC, - X_SQUARED - }; - PreviewPlot(QWidget *parent = NULL, bool init = true); virtual ~PreviewPlot(); @@ -76,6 +70,8 @@ namespace MantidWidgets bool allowZoom(); void setAllowZoom(bool allow); + bool legendIsShown(); + void setAxisRange(QPair range, int axisID = QwtPlot::xBottom); QPair getCurveRange(const Mantid::API::MatrixWorkspace_const_sptr ws); @@ -88,6 +84,7 @@ namespace MantidWidgets void removeSpectrum(const QString & wsName); public slots: + void showLegend(bool show); void togglePanTool(bool enabled); void toggleZoomTool(bool enabled); void resetView(); @@ -101,9 +98,12 @@ namespace MantidWidgets void removeCurve(QwtPlotCurve *curve); + QList addOptionsToMenus(QString menuName, QActionGroup *group, QStringList items, QString defaultItem); + private slots: void showContextMenu(QPoint position); - void handleViewToolSelect(bool checked); + void handleViewToolSelect(); + void handleAxisTypeSelect(); private: /// Poco Observers for ADS Notifications @@ -132,6 +132,8 @@ namespace MantidWidgets /// Context menu items QMenu *m_contextMenu; QActionGroup *m_plotToolGroup; + QActionGroup *m_xAxisTypeGroup; + QActionGroup *m_yAxisTypeGroup; }; diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index 21ec7fef227f..cc17b12ca671 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -15,6 +15,8 @@ #include #include +#include + using namespace MantidQt::MantidWidgets; using namespace Mantid::API; @@ -65,35 +67,48 @@ PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent) connect(m_plot, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint))); // Create the plot tool list for context menu - QMenu *viewToolMenu = new QMenu(m_contextMenu); m_plotToolGroup = new QActionGroup(m_contextMenu); m_plotToolGroup->setExclusive(true); QStringList plotTools; plotTools << "None" << "Pan" << "Zoom"; - - for(auto it = plotTools.begin(); it != plotTools.end(); ++it) - { - QAction *toolAction = new QAction(*it, viewToolMenu); - toolAction->setCheckable(true); - connect(toolAction, SIGNAL(toggled(bool)), this, SLOT(handleViewToolSelect(bool))); - - // Add to the menu and action group - m_plotToolGroup->addAction(toolAction); - viewToolMenu->addAction(toolAction); - - // None is selected by default - toolAction->setChecked(*it == "None"); - } - - QAction *viewToolAction = new QAction("View Tool", this); - viewToolAction->setMenu(viewToolMenu); - m_contextMenu->addAction(viewToolAction); + QList plotToolActions = addOptionsToMenus("Plot Tools", m_plotToolGroup, plotTools, "None"); + for(auto it = plotToolActions.begin(); it != plotToolActions.end(); ++it) + connect(*it, SIGNAL(triggered()), this, SLOT(handleViewToolSelect())); // Create the reset plot view option QAction *resetPlotAction = new QAction("Reset Plot", m_contextMenu); connect(resetPlotAction, SIGNAL(triggered()), this, SLOT(resetView())); m_contextMenu->addAction(resetPlotAction); + + m_contextMenu->addSeparator(); + + // Create the X axis type list for context menu + m_xAxisTypeGroup = new QActionGroup(m_contextMenu); + m_xAxisTypeGroup->setExclusive(true); + + QStringList xAxisTypes; + xAxisTypes << "Linear" << "Logarithmic" << "Squared"; + QList xAxisTypeActions = addOptionsToMenus("X Axis", m_xAxisTypeGroup, xAxisTypes, "Linear"); + for(auto it = xAxisTypeActions.begin(); it != xAxisTypeActions.end(); ++it) + connect(*it, SIGNAL(triggered()), this, SLOT(handleAxisTypeSelect())); + + // Create the X axis type list for context menu + m_yAxisTypeGroup = new QActionGroup(m_contextMenu); + m_yAxisTypeGroup->setExclusive(true); + + QStringList yAxisTypes; + yAxisTypes << "Linear" << "Logarithmic"; + QList yAxisTypeActions = addOptionsToMenus("Y Axis", m_yAxisTypeGroup, yAxisTypes, "Linear"); + for(auto it = yAxisTypeActions.begin(); it != yAxisTypeActions.end(); ++it) + connect(*it, SIGNAL(triggered()), this, SLOT(handleAxisTypeSelect())); + + m_contextMenu->addSeparator(); + + // Create the show legend option + QAction *showLegendAction = new QAction("Show Legend", m_contextMenu); + connect(showLegendAction, SIGNAL(toggled(bool)), this, SLOT(showLegend(bool))); + m_contextMenu->addAction(showLegendAction); } @@ -182,6 +197,17 @@ void PreviewPlot::setAllowZoom(bool allow) } +/** + * Checks to see if the plot legend is visible. + * + * @returns True if the legend is shown + */ +bool PreviewPlot::legendIsShown() +{ + return false; +} + + /** * Sets the range of the given axis scale to a given range. * @@ -334,6 +360,17 @@ void PreviewPlot::removeSpectrum(const QString & wsName) } +/** + * Shows or hides the plot legend. + * + * @param show If the legend should be shown + */ +void PreviewPlot::showLegend(bool show) +{ + //TODO +} + + /** * Toggles the pan plot tool. * @@ -458,6 +495,40 @@ void PreviewPlot::removeCurve(QwtPlotCurve * curve) } +/** + * Helper function for adding a set of items to an exclusive menu oon the context menu. + * + * @param menuName Name of sub menu + * @param group Pointer to ActionGroup + * @param items List of item names + * @param defaultItem Default item name + * @return List of Actions added + */ +QList PreviewPlot::addOptionsToMenus(QString menuName, QActionGroup *group, QStringList items, QString defaultItem) +{ + QMenu *menu = new QMenu(m_contextMenu); + + for(auto it = items.begin(); it != items.end(); ++it) + { + QAction *action = new QAction(*it, menu); + action->setCheckable(true); + + // Add to the menu and action group + group->addAction(action); + menu->addAction(action); + + // Select default + action->setChecked(*it == defaultItem); + } + + QAction *menuAction = new QAction(menuName, this); + menuAction->setMenu(menu); + m_contextMenu->addAction(menuAction); + + return group->actions(); +} + + /** * Handles displaying the context menu when a user right clicks on the plot. * @@ -472,14 +543,9 @@ void PreviewPlot::showContextMenu(QPoint position) /** * Handles the view tool being selected from the context menu. - * - * @param checked If the option was checked */ -void PreviewPlot::handleViewToolSelect(bool checked) +void PreviewPlot::handleViewToolSelect() { - if(!checked) - return; - QAction *selectedPlotType = m_plotToolGroup->checkedAction(); if(!selectedPlotType) return; @@ -499,3 +565,42 @@ void PreviewPlot::handleViewToolSelect(bool checked) toggleZoomTool(true); } } + + +/** + * Handles a change in the plot axis type. + */ +void PreviewPlot::handleAxisTypeSelect() +{ + QString xAxisType("Linear"); + QString yAxisType("Linear"); + + QAction *selectedXAxisType = m_xAxisTypeGroup->checkedAction(); + if(selectedXAxisType) + xAxisType = selectedXAxisType->text(); + + QAction *selectedYAxisType = m_yAxisTypeGroup->checkedAction(); + if(selectedYAxisType) + yAxisType = selectedYAxisType->text(); + + QwtScaleEngine *xEngine = NULL; + QwtScaleEngine *yEngine = NULL; + + if(xAxisType == "Linear") + xEngine = new QwtLinearScaleEngine(); + else if(xAxisType == "Logarithmic") + xEngine = new QwtLog10ScaleEngine(); + + if(yAxisType == "Linear") + yEngine = new QwtLinearScaleEngine(); + else if(yAxisType == "Logarithmic") + yEngine = new QwtLog10ScaleEngine(); + + if(xEngine) + m_plot->setAxisScaleEngine(QwtPlot::xBottom, xEngine); + + if(yEngine) + m_plot->setAxisScaleEngine(QwtPlot::yLeft, yEngine); + + m_plot->replot(); +} From 4a774d32b09069bdef8ebefccabe9aab1c89eaec Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 9 Feb 2015 16:41:34 +0000 Subject: [PATCH 051/414] Use new widget in transmission and symmetrise Refs #11036 --- .../Indirect/IndirectMoments.ui | 10 ++- .../Indirect/IndirectSymmetrise.ui | 30 +++++++- .../src/Indirect/IndirectMoments.cpp | 18 ++--- .../src/Indirect/IndirectSymmetrise.cpp | 76 +++++-------------- 4 files changed, 59 insertions(+), 75 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.ui index a2ad05d818c9..d089afd2553a 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.ui @@ -96,7 +96,15 @@
- + + + + 255 + 255 + 255 + + + diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSymmetrise.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSymmetrise.ui index 6cd8dc001310..b5b0b76b255d 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSymmetrise.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSymmetrise.ui @@ -6,8 +6,8 @@ 0 0 - 507 - 232 + 488 + 269 @@ -55,7 +55,15 @@ - + + + + 255 + 255 + 255 + + + @@ -81,7 +89,15 @@ - + + + + 255 + 255 + 255 + + + @@ -156,6 +172,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp index 148f0aae6a20..6710a3b987b0 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp @@ -23,19 +23,9 @@ namespace CustomInterfaces const unsigned int NUM_DECIMALS = 6; // RAW PLOT - m_plots["MomentsPlot"] = new QwtPlot(m_parentWidget); - /* m_curves["MomentsPlotCurve"] = new QwtPlotCurve(); */ - m_rangeSelectors["MomentsRangeSelector"] = new MantidWidgets::RangeSelector(m_plots["MomentsPlot"]); + m_rangeSelectors["MomentsRangeSelector"] = new MantidWidgets::RangeSelector(m_uiForm.ppRawPlot); m_rangeSelectors["MomentsRangeSelector"]->setInfoOnly(false); - // Initilise plot - m_plots["MomentsPlot"]->setCanvasBackground(Qt::white); - m_plots["MomentsPlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); - m_plots["MomentsPlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); - - // Add plot to UI - m_uiForm.plotRaw->addWidget(m_plots["MomentsPlot"]); - // PROPERTY TREE m_propTrees["MomentsPropTree"] = new QtTreePropertyBrowser(); m_propTrees["MomentsPropTree"]->setFactoryForManager(m_dblManager, m_dblEdFac); @@ -123,8 +113,10 @@ namespace CustomInterfaces { disconnect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(updateProperties(QtProperty*, double))); - plotMiniPlot(filename, 0, "MomentsPlot", "MomentsPlotCurve"); - std::pair range = getCurveRange("MomentsPlotCurve"); + m_uiForm.ppRawPlot->clear(); + m_uiForm.ppRawPlot->addSpectrum(filename, 0); + QPair curveRange = m_uiForm.ppRawPlot->getCurveRange(filename); + std::pair range = std::make_pair(curveRange.first, curveRange.second); setMiniPlotGuides("MomentsRangeSelector", m_properties["EMin"], m_properties["EMax"], range); setPlotRange("MomentsRangeSelector", m_properties["EMin"], m_properties["EMax"], range); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp index 619022792b4e..4e78a9df3c31 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp @@ -54,9 +54,6 @@ namespace CustomInterfaces m_dblManager->setDecimals(m_properties["PreviewSpec"], 0); rawPlotProps->addSubProperty(m_properties["PreviewSpec"]); - m_properties["PreviewRange"] = m_dblManager->addProperty("X Range"); - rawPlotProps->addSubProperty(m_properties["PreviewRange"]); - // Preview Properties // Mainly used for display rather than getting user input m_properties["NegativeYValue"] = m_dblManager->addProperty("Negative Y"); @@ -71,17 +68,10 @@ namespace CustomInterfaces m_dblManager->setDecimals(m_properties["DeltaY"], numDecimals); m_propTrees["SymmPVPropTree"]->addProperty(m_properties["DeltaY"]); - // Raw plot - m_plots["SymmRawPlot"] = new QwtPlot(m_parentWidget); - m_plots["SymmRawPlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); - m_plots["SymmRawPlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); - m_plots["SymmRawPlot"]->setCanvasBackground(Qt::white); - m_uiForm.plotRaw->addWidget(m_plots["SymmRawPlot"]); - // Indicators for Y value at each EMin position - m_rangeSelectors["NegativeEMinYPos"] = new MantidWidgets::RangeSelector(m_plots["SymmRawPlot"], + m_rangeSelectors["NegativeEMinYPos"] = new MantidWidgets::RangeSelector(m_uiForm.ppRawPlot, MantidWidgets::RangeSelector::YSINGLE, true, true); - m_rangeSelectors["PositiveEMinYPos"] = new MantidWidgets::RangeSelector(m_plots["SymmRawPlot"], + m_rangeSelectors["PositiveEMinYPos"] = new MantidWidgets::RangeSelector(m_uiForm.ppRawPlot, MantidWidgets::RangeSelector::YSINGLE, true, true); m_rangeSelectors["NegativeEMinYPos"]->setColour(Qt::red); @@ -90,7 +80,7 @@ namespace CustomInterfaces m_rangeSelectors["PositiveEMinYPos"]->setMinimum(0); // Indicator for centre of symmetry (x=0) - m_rangeSelectors["CentreMark_Raw"] = new MantidWidgets::RangeSelector(m_plots["SymmRawPlot"], + m_rangeSelectors["CentreMark_Raw"] = new MantidWidgets::RangeSelector(m_uiForm.ppRawPlot, MantidWidgets::RangeSelector::XSINGLE, true, true); m_rangeSelectors["CentreMark_Raw"]->setColour(Qt::cyan); m_rangeSelectors["CentreMark_Raw"]->setMinimum(0.0); @@ -99,38 +89,27 @@ namespace CustomInterfaces // The user can use these to move the X range // Note that the max and min of the negative range selector corespond to the opposite X value // i.e. RS min is X max - m_rangeSelectors["NegativeE_Raw"] = new MantidWidgets::RangeSelector(m_plots["SymmRawPlot"]); - m_rangeSelectors["PositiveE_Raw"] = new MantidWidgets::RangeSelector(m_plots["SymmRawPlot"]); + m_rangeSelectors["NegativeE_Raw"] = new MantidWidgets::RangeSelector(m_uiForm.ppRawPlot); + m_rangeSelectors["PositiveE_Raw"] = new MantidWidgets::RangeSelector(m_uiForm.ppRawPlot); m_rangeSelectors["NegativeE_Raw"]->setColour(Qt::darkGreen); m_rangeSelectors["PositiveE_Raw"]->setColour(Qt::darkGreen); - // Preview plot - m_plots["SymmPreviewPlot"] = new QwtPlot(m_parentWidget); - m_plots["SymmPreviewPlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); - m_plots["SymmPreviewPlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); - m_plots["SymmPreviewPlot"]->setCanvasBackground(Qt::white); - m_uiForm.plotPreview->addWidget(m_plots["SymmPreviewPlot"]); - // Indicators for negative and positive X range values on X axis - m_rangeSelectors["NegativeE_PV"] = new MantidWidgets::RangeSelector(m_plots["SymmPreviewPlot"], + m_rangeSelectors["NegativeE_PV"] = new MantidWidgets::RangeSelector(m_uiForm.ppPreviewPlot, MantidWidgets::RangeSelector::XMINMAX, true, true); - m_rangeSelectors["PositiveE_PV"] = new MantidWidgets::RangeSelector(m_plots["SymmPreviewPlot"], + m_rangeSelectors["PositiveE_PV"] = new MantidWidgets::RangeSelector(m_uiForm.ppPreviewPlot, MantidWidgets::RangeSelector::XMINMAX, true, true); m_rangeSelectors["NegativeE_PV"]->setColour(Qt::darkGreen); m_rangeSelectors["PositiveE_PV"]->setColour(Qt::darkGreen); // Indicator for centre of symmetry (x=0) - m_rangeSelectors["CentreMark_PV"] = new MantidWidgets::RangeSelector(m_plots["SymmPreviewPlot"], + m_rangeSelectors["CentreMark_PV"] = new MantidWidgets::RangeSelector(m_uiForm.ppPreviewPlot, MantidWidgets::RangeSelector::XSINGLE, true, true); m_rangeSelectors["CentreMark_PV"]->setColour(Qt::cyan); m_rangeSelectors["CentreMark_PV"]->setMinimum(0.0); - // Refresh the plot windows - m_plots["SymmRawPlot"]->replot(); - m_plots["SymmPreviewPlot"]->replot(); - // SIGNAL/SLOT CONNECTIONS // Validate the E range when it is changed connect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(verifyERange(QtProperty*, double))); @@ -151,9 +130,9 @@ namespace CustomInterfaces m_dblManager->setValue(m_properties["EMax"], 0.5); // Set default x axis range - std::pair defaultRange(-1.0, 1.0); - setAxisRange("SymmRawPlot", QwtPlot::xBottom, defaultRange); - setAxisRange("SymmPreviewPlot", QwtPlot::xBottom, defaultRange); + QPair defaultRange(-1.0, 1.0); + m_uiForm.ppRawPlot->setAxisRange(defaultRange, QwtPlot::xBottom); + m_uiForm.ppPreviewPlot->setAxisRange(defaultRange, QwtPlot::xBottom); } //---------------------------------------------------------------------------------------------- @@ -227,10 +206,8 @@ namespace CustomInterfaces updateMiniPlots(); // Set the preview range to the maximum absolute X value - auto axisRange = getCurveRange("SymmRawPlot"); + QPair axisRange = m_uiForm.ppRawPlot->getCurveRange(sampleWS); double symmRange = std::max(fabs(axisRange.first), fabs(axisRange.second)); - g_log.information() << "Symmetrise x axis range +/- " << symmRange << std::endl; - m_dblManager->setValue(m_properties["PreviewRange"], symmRange); // Set valid range for range selectors m_rangeSelectors["NegativeE_Raw"]->setRange(-symmRange, 0); @@ -257,19 +234,14 @@ namespace CustomInterfaces Mantid::API::MatrixWorkspace_sptr input = boost::dynamic_pointer_cast( Mantid::API::AnalysisDataService::Instance().retrieve(workspaceName.toStdString())); - // Set the X axis range based on the range specified by the user - std::pairrange; - range.first = -m_dblManager->value(m_properties["PreviewRange"]); - range.second = m_dblManager->value(m_properties["PreviewRange"]); - setAxisRange("SymmRawPlot", QwtPlot::xBottom, range); - // Plot the spectrum chosen by the user size_t spectrumIndex = input->getIndexFromSpectrumNumber(spectrumNumber); - plotMiniPlot(input, spectrumIndex, "SymmRawPlot"); + m_uiForm.ppRawPlot->clear(); + m_uiForm.ppRawPlot->addSpectrum(input, spectrumIndex); // Match X axis range on preview plot - setAxisRange("SymmPreviewPlot", QwtPlot::xBottom, range); - m_plots["SymmPreviewPlot"]->replot(); + m_uiForm.ppPreviewPlot->setAxisRange(m_uiForm.ppRawPlot->getCurveRange(workspaceName), QwtPlot::xBottom); + m_uiForm.ppPreviewPlot->replot(); } /** @@ -280,17 +252,6 @@ namespace CustomInterfaces */ void IndirectSymmetrise::replotNewSpectrum(QtProperty *prop, double value) { - // Validate the preview range - if(prop == m_properties["PreviewRange"]) - { - // If preview range was set negative then set it to the absolute value of the value it was set to - if(value < 0) - { - m_dblManager->setValue(m_properties["PreviewRange"], fabs(value)); - return; - } - } - // Validate the preview spectra if(prop == m_properties["PreviewSpec"]) { @@ -316,7 +277,7 @@ namespace CustomInterfaces } // If we get this far then properties are valid so update mini plots - if((prop == m_properties["PreviewSpec"]) || (prop == m_properties["PreviewRange"])) + if((prop == m_properties["PreviewSpec"])) updateMiniPlots(); } @@ -449,7 +410,8 @@ namespace CustomInterfaces // Plot preview plot size_t spectrumIndex = symmWS->getIndexFromSpectrumNumber(spectrumNumber); - plotMiniPlot("__Symmetrise_temp", spectrumIndex, "SymmPreviewPlot"); + m_uiForm.ppPreviewPlot->clear(); + m_uiForm.ppPreviewPlot->addSpectrum("__Symmetrise_temp", spectrumIndex); // Don't want this to trigger when the algorithm is run for all spectra disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(previewAlgDone(bool))); From 038ff6eae51fde219e9f5a57e7adc2f28fd68b2e Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 9 Feb 2015 16:49:51 +0000 Subject: [PATCH 052/414] Use new widget on calibration Refs #11036 --- .../Indirect/IndirectCalibration.ui | 26 ++++++++++++-- .../src/Indirect/IndirectCalibration.cpp | 36 +++++++------------ 2 files changed, 36 insertions(+), 26 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.ui index adbfa401df8b..7feb512be380 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.ui @@ -108,7 +108,15 @@ - + + + + 255 + 255 + 255 + + + @@ -168,7 +176,15 @@ - + + + + 255 + 255 + 255 + + + @@ -240,6 +256,12 @@ QWidget
MantidQtMantidWidgets/MWRunFiles.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp index cedeaa92d211..37c4503d8c11 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp @@ -45,16 +45,9 @@ namespace CustomInterfaces m_propTrees["CalPropTree"]->addProperty(m_properties["CalBackMin"]); m_propTrees["CalPropTree"]->addProperty(m_properties["CalBackMax"]); - // CAL PLOT - m_plots["CalPlot"] = new QwtPlot(m_parentWidget); - m_plots["CalPlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); - m_plots["CalPlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); - m_plots["CalPlot"]->setCanvasBackground(Qt::white); - m_uiForm.plotCalibration->addWidget(m_plots["CalPlot"]); - // Cal plot range selectors - m_rangeSelectors["CalPeak"] = new MantidWidgets::RangeSelector(m_plots["CalPlot"]); - m_rangeSelectors["CalBackground"] = new MantidWidgets::RangeSelector(m_plots["CalPlot"]); + m_rangeSelectors["CalPeak"] = new MantidWidgets::RangeSelector(m_uiForm.ppCalibration); + m_rangeSelectors["CalBackground"] = new MantidWidgets::RangeSelector(m_uiForm.ppCalibration); m_rangeSelectors["CalBackground"]->setColour(Qt::darkGreen); //Dark green to signify background range // RES PROPERTY TREE @@ -102,19 +95,12 @@ namespace CustomInterfaces m_dblManager->setValue(m_properties["ResEHigh"], 0.2); resRB->addSubProperty(m_properties["ResEHigh"]); - // RES PLOT - m_plots["ResPlot"] = new QwtPlot(m_parentWidget); - m_plots["ResPlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); - m_plots["ResPlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); - m_plots["ResPlot"]->setCanvasBackground(Qt::white); - m_uiForm.plotResolution->addWidget(m_plots["ResPlot"]); - // Res plot range selectors // Create ResBackground first so ResPeak is drawn above it - m_rangeSelectors["ResBackground"] = new MantidWidgets::RangeSelector(m_plots["ResPlot"], + m_rangeSelectors["ResBackground"] = new MantidWidgets::RangeSelector(m_uiForm.ppResolution, MantidQt::MantidWidgets::RangeSelector::XMINMAX, true, false); m_rangeSelectors["ResBackground"]->setColour(Qt::darkGreen); - m_rangeSelectors["ResPeak"] = new MantidWidgets::RangeSelector(m_plots["ResPlot"], + m_rangeSelectors["ResPeak"] = new MantidWidgets::RangeSelector(m_uiForm.ppResolution, MantidQt::MantidWidgets::RangeSelector::XMINMAX, true, true); // SIGNAL/SLOT CONNECTIONS @@ -374,13 +360,14 @@ namespace CustomInterfaces const Mantid::MantidVec & dataX = input->readX(0); std::pair range(dataX.front(), dataX.back()); - plotMiniPlot(input, 0, "CalPlot", "CalCurve"); - setXAxisToCurve("CalPlot", "CalCurve"); + m_uiForm.ppCalibration->clear(); + m_uiForm.ppCalibration->addSpectrum(input, 0); + m_uiForm.ppCalibration->resizeX(); setPlotRange("CalPeak", m_properties["CalELow"], m_properties["CalEHigh"], range); setPlotRange("CalBackground", m_properties["CalStart"], m_properties["CalEnd"], range); - replot("CalPlot"); + m_uiForm.ppCalibration->replot(); //Also replot the energy calPlotEnergy(); @@ -439,12 +426,13 @@ namespace CustomInterfaces setPlotRange("ResBackground", m_properties["ResStart"], m_properties["ResEnd"], range); - plotMiniPlot(energyWs, 0, "ResPlot", "ResCurve"); - setXAxisToCurve("ResPlot", "ResCurve"); + m_uiForm.ppResolution->clear(); + m_uiForm.ppResolution->addSpectrum(energyWs, 0); + m_uiForm.ppResolution->resizeX(); calSetDefaultResolution(energyWs); - replot("ResPlot"); + m_uiForm.ppResolution->replot(); } /** From 615d9fe6c63edbdb0cfeab3d703935591dec2c8e Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 9 Feb 2015 16:56:57 +0000 Subject: [PATCH 053/414] Remove options for disabling plot manipulation tools Refs #11036 --- .../inc/MantidQtMantidWidgets/PreviewPlot.h | 12 ----- .../MantidWidgets/src/PreviewPlot.cpp | 47 +------------------ 2 files changed, 1 insertion(+), 58 deletions(-) diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h index a16a11109b3f..b1c7184ed241 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -53,8 +53,6 @@ namespace MantidWidgets Q_OBJECT Q_PROPERTY(QColor canvasColour READ canvasColour WRITE setCanvasColour) - Q_PROPERTY(bool allowPan READ allowPan WRITE setAllowPan) - Q_PROPERTY(bool allowZoom READ allowZoom WRITE setAllowZoom) Q_PROPERTY(bool showLegend READ legendIsShown WRITE showLegend) public: @@ -64,12 +62,6 @@ namespace MantidWidgets QColor canvasColour(); void setCanvasColour(const QColor & colour); - bool allowPan(); - void setAllowPan(bool allow); - - bool allowZoom(); - void setAllowZoom(bool allow); - bool legendIsShown(); void setAxisRange(QPair range, int axisID = QwtPlot::xBottom); @@ -113,10 +105,6 @@ namespace MantidWidgets /// If the widget was initialised bool m_init; - /// If the plot manipulation tools are allowed - bool m_allowPan; - bool m_allowZoom; - /// The plot its self friend class RangeSelector; QwtPlot *m_plot; diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index cc17b12ca671..3521416a2bf4 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -29,8 +29,7 @@ namespace PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent), m_removeObserver(*this, &PreviewPlot::handleRemoveEvent), m_replaceObserver(*this, &PreviewPlot::handleReplaceEvent), - m_init(init), m_allowPan(false), m_allowZoom(false), - m_plot(NULL), m_curves(), + m_init(init), m_plot(NULL), m_curves(), m_magnifyTool(NULL), m_panTool(NULL), m_zoomTool(NULL), m_contextMenu(new QMenu(this)) { @@ -153,50 +152,6 @@ void PreviewPlot::setCanvasColour(const QColor & colour) } -/** - * Checks to see if the option to use the pan tool is enabled. - * - * @return True if tool is allowed - */ -bool PreviewPlot::allowPan() -{ - return m_allowPan; -} - - -/** - * Enables or disables the option to use the pan tool on the plot. - * - * @param allow If tool should be allowed - */ -void PreviewPlot::setAllowPan(bool allow) -{ - m_allowPan = allow; -} - - -/** - * Checks to see if the option to use the zoom tool is enabled. - * - * @return True if tool is allowed - */ -bool PreviewPlot::allowZoom() -{ - return m_allowZoom; -} - - -/** - * Enables or disables the option to use the zoom tool on the plot. - * - * @param allow If tool should be allowed - */ -void PreviewPlot::setAllowZoom(bool allow) -{ - m_allowZoom = allow; -} - - /** * Checks to see if the plot legend is visible. * From d1ed53a9e84890a9fe068eac207029faf6e85f3a Mon Sep 17 00:00:00 2001 From: Vickie Lynch Date: Mon, 9 Feb 2015 16:10:54 -0500 Subject: [PATCH 054/414] Refs #11034 workspaces for principal axes lengths --- .../MDEvents/src/IntegrateEllipsoids.cpp | 155 ++++++++++-------- 1 file changed, 91 insertions(+), 64 deletions(-) diff --git a/Code/Mantid/Framework/MDEvents/src/IntegrateEllipsoids.cpp b/Code/Mantid/Framework/MDEvents/src/IntegrateEllipsoids.cpp index 19b6ec91f76a..c413ae0d2bd5 100644 --- a/Code/Mantid/Framework/MDEvents/src/IntegrateEllipsoids.cpp +++ b/Code/Mantid/Framework/MDEvents/src/IntegrateEllipsoids.cpp @@ -14,6 +14,7 @@ #include "MantidMDEvents/UnitsConversionHelper.h" #include "MantidMDEvents/Integrate3DEvents.h" #include "MantidMDEvents/IntegrateEllipsoids.h" +#include "MantidDataObjects/Workspace2D.h" #include "MantidKernel/Statistics.h" using namespace Mantid::API; @@ -265,7 +266,7 @@ void IntegrateEllipsoids::exec() { double inti; double sigi; - std::vector r1,r2,r3; + std::vector principalaxis1,principalaxis2,principalaxis3; for (size_t i = 0; i < n_peaks; i++) { V3D hkl(peaks[i].getH(), peaks[i].getK(), peaks[i].getL()); if (Geometry::IndexingUtils::ValidIndex(hkl, 1.0)) { @@ -276,80 +277,106 @@ void IntegrateEllipsoids::exec() { axes_radii, inti, sigi); peaks[i].setIntensity(inti); peaks[i].setSigmaIntensity(sigi); - if (axes_radii.size() == 3) { - if (inti/sigi > cutoffIsigI && !specify_size) - { - r1.push_back(axes_radii[0]); - r2.push_back(axes_radii[1]); - r3.push_back(axes_radii[2]); - } - g_log.notice() - << "Radii of three axes of ellipsoid for integrating peak " << i - << " = "; - for (int i3 = 0; i3 < 3; i3++) { - g_log.notice() << axes_radii[i3] << " "; - } - g_log.notice() << std::endl; + if (axes_radii.size() == 3 && (inti/sigi > cutoffIsigI || cutoffIsigI == EMPTY_DBL())) + { + principalaxis1.push_back(axes_radii[0]); + principalaxis2.push_back(axes_radii[1]); + principalaxis3.push_back(axes_radii[2]); } } else { peaks[i].setIntensity(0.0); peaks[i].setSigmaIntensity(0.0); } } - if (r1.size() > 1 && !specify_size) - { - Statistics stats = getStatistics(r1); - g_log.notice() << "r1: " - << " mean " << stats.mean - << " standard_deviation " << stats.standard_deviation - << " minimum " << stats.minimum - << " maximum " << stats.maximum - << " median " << stats.median << "\n"; - stats = getStatistics(r2); - g_log.notice() << "r2: " - << " mean " << stats.mean - << " standard_deviation " << stats.standard_deviation - << " minimum " << stats.minimum - << " maximum " << stats.maximum - << " median " << stats.median << "\n"; - stats = getStatistics(r3); - g_log.notice() << "r3: " - << " mean " << stats.mean - << " standard_deviation " << stats.standard_deviation - << " minimum " << stats.minimum - << " maximum " << stats.maximum - << " median " << stats.median << "\n"; - specify_size=true; - peak_radius = stats.mean + numSigmas * stats.standard_deviation; - back_inner_radius = peak_radius; - back_outer_radius = peak_radius * 1.25992105; // A factor of 2 ^ (1/3) will make the background - // shell volume equal to the peak region volume. - for (size_t i = 0; i < n_peaks; i++) { - V3D hkl(peaks[i].getH(), peaks[i].getK(), peaks[i].getL()); - if (Geometry::IndexingUtils::ValidIndex(hkl, 1.0)) { - V3D peak_q(peaks[i].getQLabFrame()); - std::vector axes_radii; - integrator.ellipseIntegrateEvents(peak_q, specify_size, peak_radius, - back_inner_radius, back_outer_radius, - axes_radii, inti, sigi); - peaks[i].setIntensity(inti); - peaks[i].setSigmaIntensity(sigi); - if (axes_radii.size() == 3) { - g_log.notice() - << "Radii of three axes of ellipsoid for integrating peak " << i - << " = "; - for (int i3 = 0; i3 < 3; i3++) { - g_log.notice() << axes_radii[i3] << " "; + if (principalaxis1.size() > 1 ){ + size_t histogramNumber = 3; + Workspace_sptr wsProfile = WorkspaceFactory::Instance().create( + "Workspace2D", histogramNumber, principalaxis1.size(), principalaxis1.size()); + Workspace2D_sptr wsProfile2D = boost::dynamic_pointer_cast(wsProfile); + AnalysisDataService::Instance().addOrReplace("EllipsoidAxes", wsProfile2D); + for (size_t j = 0; j < principalaxis1.size(); j++) { + wsProfile2D->dataX(0)[j] = static_cast(j); + wsProfile2D->dataY(0)[j] = principalaxis1[j]; + wsProfile2D->dataE(0)[j] = std::sqrt(principalaxis1[j]); + wsProfile2D->dataX(1)[j] = static_cast(j); + wsProfile2D->dataY(1)[j] = principalaxis2[j]; + wsProfile2D->dataE(1)[j] = std::sqrt(principalaxis2[j]); + wsProfile2D->dataX(2)[j] = static_cast(j); + wsProfile2D->dataY(2)[j] = principalaxis3[j]; + wsProfile2D->dataE(2)[j] = std::sqrt(principalaxis3[j]); + } + Statistics stats1 = getStatistics(principalaxis1); + g_log.notice() << "principalaxis1: " + << " mean " << stats1.mean + << " standard_deviation " << stats1.standard_deviation + << " minimum " << stats1.minimum + << " maximum " << stats1.maximum + << " median " << stats1.median << "\n"; + Statistics stats2 = getStatistics(principalaxis2); + g_log.notice() << "principalaxis2: " + << " mean " << stats2.mean + << " standard_deviation " << stats2.standard_deviation + << " minimum " << stats2.minimum + << " maximum " << stats2.maximum + << " median " << stats2.median << "\n"; + Statistics stats3 = getStatistics(principalaxis3); + g_log.notice() << "principalaxis3: " + << " mean " << stats3.mean + << " standard_deviation " << stats3.standard_deviation + << " minimum " << stats3.minimum + << " maximum " << stats3.maximum + << " median " << stats3.median << "\n"; + if (cutoffIsigI != EMPTY_DBL()){ + principalaxis1.clear(); + principalaxis2.clear(); + principalaxis3.clear(); + specify_size=true; + peak_radius = std::max(std::max(stats1.mean,stats2.mean),stats3.mean) + numSigmas * + std::max(std::max(stats1.standard_deviation,stats2.standard_deviation),stats3.standard_deviation); + back_inner_radius = peak_radius; + back_outer_radius = peak_radius * 1.25992105; // A factor of 2 ^ (1/3) will make the background + // shell volume equal to the peak region volume. + for (size_t i = 0; i < n_peaks; i++) { + V3D hkl(peaks[i].getH(), peaks[i].getK(), peaks[i].getL()); + if (Geometry::IndexingUtils::ValidIndex(hkl, 1.0)) { + V3D peak_q(peaks[i].getQLabFrame()); + std::vector axes_radii; + integrator.ellipseIntegrateEvents(peak_q, specify_size, peak_radius, + back_inner_radius, back_outer_radius, + axes_radii, inti, sigi); + peaks[i].setIntensity(inti); + peaks[i].setSigmaIntensity(sigi); + if (axes_radii.size() == 3){ + principalaxis1.push_back(axes_radii[0]); + principalaxis2.push_back(axes_radii[1]); + principalaxis3.push_back(axes_radii[2]); } - g_log.notice() << std::endl; + } else { + peaks[i].setIntensity(0.0); + peaks[i].setSigmaIntensity(0.0); + } + } + if (principalaxis1.size() > 1 ){ + size_t histogramNumber = 3; + Workspace_sptr wsProfile2 = WorkspaceFactory::Instance().create( + "Workspace2D", histogramNumber, principalaxis1.size(), principalaxis1.size()); + Workspace2D_sptr wsProfile2D2 = boost::dynamic_pointer_cast(wsProfile2); + AnalysisDataService::Instance().addOrReplace("EllipsoidAxes_2ndPass", wsProfile2D2); + for (size_t j = 0; j < principalaxis1.size(); j++) { + wsProfile2D2->dataX(0)[j] = static_cast(j); + wsProfile2D2->dataY(0)[j] = principalaxis1[j]; + wsProfile2D2->dataE(0)[j] = std::sqrt(principalaxis1[j]); + wsProfile2D2->dataX(1)[j] = static_cast(j); + wsProfile2D2->dataY(1)[j] = principalaxis2[j]; + wsProfile2D2->dataE(1)[j] = std::sqrt(principalaxis2[j]); + wsProfile2D2->dataX(2)[j] = static_cast(j); + wsProfile2D2->dataY(2)[j] = principalaxis3[j]; + wsProfile2D2->dataE(2)[j] = std::sqrt(principalaxis3[j]); } - } else { - peaks[i].setIntensity(0.0); - peaks[i].setSigmaIntensity(0.0); } } - } + // This flag is used by the PeaksWorkspace to evaluate whether it has been // integrated. peak_ws->mutableRun().addProperty("PeaksIntegrated", 1, true); From bf190f831ad51c42b9e611431c5d82adf69c5667 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Tue, 10 Feb 2015 10:36:38 +0000 Subject: [PATCH 055/414] Added curve labels for preview plot Refs #11036 --- .../src/Indirect/IndirectCalibration.cpp | 4 +- .../src/Indirect/IndirectDiagnostics.cpp | 4 +- .../src/Indirect/IndirectMoments.cpp | 8 +- .../src/Indirect/IndirectSymmetrise.cpp | 6 +- .../src/Indirect/IndirectTransmission.cpp | 6 +- .../inc/MantidQtMantidWidgets/PreviewPlot.h | 16 +++- .../MantidWidgets/src/PreviewPlot.cpp | 76 +++++++++++++------ 7 files changed, 77 insertions(+), 43 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp index 37c4503d8c11..f853d0b72533 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp @@ -361,7 +361,7 @@ namespace CustomInterfaces std::pair range(dataX.front(), dataX.back()); m_uiForm.ppCalibration->clear(); - m_uiForm.ppCalibration->addSpectrum(input, 0); + m_uiForm.ppCalibration->addSpectrum("Raw", input, 0); m_uiForm.ppCalibration->resizeX(); setPlotRange("CalPeak", m_properties["CalELow"], m_properties["CalEHigh"], range); @@ -427,7 +427,7 @@ namespace CustomInterfaces setPlotRange("ResBackground", m_properties["ResStart"], m_properties["ResEnd"], range); m_uiForm.ppResolution->clear(); - m_uiForm.ppResolution->addSpectrum(energyWs, 0); + m_uiForm.ppResolution->addSpectrum("Energy", energyWs, 0); m_uiForm.ppResolution->resizeX(); calSetDefaultResolution(energyWs); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp index ff4a4c39aa94..b56ab6978bb5 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp @@ -259,7 +259,7 @@ namespace CustomInterfaces std::pair range(dataX.front(), dataX.back()); m_uiForm.ppRawPlot->clear(); - m_uiForm.ppRawPlot->addSpectrum(input, 0); + m_uiForm.ppRawPlot->addSpectrum("Raw", input, 0); setPlotRange("SlicePeak", m_properties["PeakStart"], m_properties["PeakEnd"], range); setPlotRange("SliceBackground", m_properties["BackgroundStart"], m_properties["BackgroundEnd"], range); @@ -408,7 +408,7 @@ namespace CustomInterfaces // Plot result spectrum m_uiForm.ppSlicePreview->clear(); - m_uiForm.ppSlicePreview->addSpectrum(sliceWs, 0); + m_uiForm.ppSlicePreview->addSpectrum("Slice", sliceWs, 0); m_uiForm.ppSlicePreview->resizeX(); // Ungroup the output workspace diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp index 6710a3b987b0..947d1ca2c735 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp @@ -114,7 +114,7 @@ namespace CustomInterfaces disconnect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(updateProperties(QtProperty*, double))); m_uiForm.ppRawPlot->clear(); - m_uiForm.ppRawPlot->addSpectrum(filename, 0); + m_uiForm.ppRawPlot->addSpectrum("Raw", filename, 0); QPair curveRange = m_uiForm.ppRawPlot->getCurveRange(filename); std::pair range = std::make_pair(curveRange.first, curveRange.second); setMiniPlotGuides("MomentsRangeSelector", m_properties["EMin"], m_properties["EMax"], range); @@ -235,9 +235,9 @@ namespace CustomInterfaces // Plot each spectrum m_uiForm.ppMomentsPreview->clear(); - m_uiForm.ppMomentsPreview->addSpectrum(QString::fromStdString(resultWsNames[0]), 0, Qt::green); - m_uiForm.ppMomentsPreview->addSpectrum(QString::fromStdString(resultWsNames[2]), 0, Qt::black); - m_uiForm.ppMomentsPreview->addSpectrum(QString::fromStdString(resultWsNames[3]), 0, Qt::red); + m_uiForm.ppMomentsPreview->addSpectrum("M0", QString::fromStdString(resultWsNames[0]), 0, Qt::green); + m_uiForm.ppMomentsPreview->addSpectrum("M1", QString::fromStdString(resultWsNames[2]), 0, Qt::black); + m_uiForm.ppMomentsPreview->addSpectrum("M2", QString::fromStdString(resultWsNames[3]), 0, Qt::red); m_uiForm.ppMomentsPreview->resizeX(); } diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp index 4e78a9df3c31..2fa9508e7e80 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp @@ -237,10 +237,10 @@ namespace CustomInterfaces // Plot the spectrum chosen by the user size_t spectrumIndex = input->getIndexFromSpectrumNumber(spectrumNumber); m_uiForm.ppRawPlot->clear(); - m_uiForm.ppRawPlot->addSpectrum(input, spectrumIndex); + m_uiForm.ppRawPlot->addSpectrum("Raw", input, spectrumIndex); // Match X axis range on preview plot - m_uiForm.ppPreviewPlot->setAxisRange(m_uiForm.ppRawPlot->getCurveRange(workspaceName), QwtPlot::xBottom); + m_uiForm.ppPreviewPlot->setAxisRange(m_uiForm.ppRawPlot->getCurveRange(input), QwtPlot::xBottom); m_uiForm.ppPreviewPlot->replot(); } @@ -411,7 +411,7 @@ namespace CustomInterfaces // Plot preview plot size_t spectrumIndex = symmWS->getIndexFromSpectrumNumber(spectrumNumber); m_uiForm.ppPreviewPlot->clear(); - m_uiForm.ppPreviewPlot->addSpectrum("__Symmetrise_temp", spectrumIndex); + m_uiForm.ppPreviewPlot->addSpectrum("Symmetrised", "__Symmetrise_temp", spectrumIndex); // Don't want this to trigger when the algorithm is run for all spectra disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(previewAlgDone(bool))); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp index 0f7024ecfb38..64dd63c031c6 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp @@ -117,9 +117,9 @@ namespace CustomInterfaces // Do plotting m_uiForm.ppPlot->clear(); - m_uiForm.ppPlot->addSpectrum(QString::fromStdString(resultWsNames[0]), 0, Qt::red); - m_uiForm.ppPlot->addSpectrum(QString::fromStdString(resultWsNames[1]), 0, Qt::black); - m_uiForm.ppPlot->addSpectrum(QString::fromStdString(resultWsNames[2]), 0, Qt::green); + m_uiForm.ppPlot->addSpectrum("Can", QString::fromStdString(resultWsNames[0]), 0, Qt::red); + m_uiForm.ppPlot->addSpectrum("Sample", QString::fromStdString(resultWsNames[1]), 0, Qt::black); + m_uiForm.ppPlot->addSpectrum("Transmission", QString::fromStdString(resultWsNames[2]), 0, Qt::green); m_uiForm.ppPlot->resizeX(); } diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h index b1c7184ed241..e56caff18121 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -7,6 +7,8 @@ #include "MantidAPI/MatrixWorkspace.h" #include +#include +#include #include #include @@ -69,8 +71,8 @@ namespace MantidWidgets QPair getCurveRange(const Mantid::API::MatrixWorkspace_const_sptr ws); QPair getCurveRange(const QString & wsName); - void addSpectrum(const Mantid::API::MatrixWorkspace_const_sptr ws, const size_t specIndex = 0, const QColor & curveColour = QColor()); - void addSpectrum(const QString & wsName, const size_t specIndex = 0, const QColor & curveColour = QColor()); + void addSpectrum(const QString & curveName, const Mantid::API::MatrixWorkspace_const_sptr ws, const size_t specIndex = 0, const QColor & curveColour = QColor()); + void addSpectrum(const QString & curveName, const QString & wsName, const size_t specIndex = 0, const QColor & curveColour = QColor()); void removeSpectrum(const Mantid::API::MatrixWorkspace_const_sptr ws); void removeSpectrum(const QString & wsName); @@ -105,12 +107,15 @@ namespace MantidWidgets /// If the widget was initialised bool m_init; + /// If the curve legend is shown + bool m_legendShown; + /// The plot its self friend class RangeSelector; QwtPlot *m_plot; - /// Map of workspaces to plot curves - QMap m_curves; + /// Map of curve key to plot curves and curve label + QMap> m_curves; /// Plot manipulation tools QwtPlotMagnifier *m_magnifyTool; @@ -123,6 +128,9 @@ namespace MantidWidgets QActionGroup *m_xAxisTypeGroup; QActionGroup *m_yAxisTypeGroup; + /// Layout for plot legend + QHBoxLayout *m_legendLayout; + }; } diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index 3521416a2bf4..6b57bc645646 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -13,7 +13,8 @@ #include #include -#include +#include +#include #include @@ -29,9 +30,9 @@ namespace PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent), m_removeObserver(*this, &PreviewPlot::handleRemoveEvent), m_replaceObserver(*this, &PreviewPlot::handleReplaceEvent), - m_init(init), m_plot(NULL), m_curves(), + m_init(init), m_legendShown(false), m_plot(new QwtPlot(this)), m_curves(), m_magnifyTool(NULL), m_panTool(NULL), m_zoomTool(NULL), - m_contextMenu(new QMenu(this)) + m_contextMenu(new QMenu(this)), m_legendLayout(NULL) { if(init) { @@ -39,13 +40,16 @@ PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent) ads.notificationCenter.addObserver(m_removeObserver); ads.notificationCenter.addObserver(m_replaceObserver); - QHBoxLayout *mainLayout = new QHBoxLayout(this); + QBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setSizeConstraint(QLayout::SetNoConstraint); - m_plot = new QwtPlot(this); m_plot->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); mainLayout->addWidget(m_plot); + m_legendLayout = new QHBoxLayout(mainLayout); + m_legendLayout->addStretch(); + mainLayout->addItem(m_legendLayout); + this->setLayout(mainLayout); } @@ -106,6 +110,7 @@ PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent) // Create the show legend option QAction *showLegendAction = new QAction("Show Legend", m_contextMenu); + showLegendAction->setCheckable(true); connect(showLegendAction, SIGNAL(toggled(bool)), this, SLOT(showLegend(bool))); m_contextMenu->addAction(showLegendAction); } @@ -159,7 +164,7 @@ void PreviewPlot::setCanvasColour(const QColor & colour) */ bool PreviewPlot::legendIsShown() { - return false; + return m_legendShown; } @@ -189,13 +194,13 @@ QPair PreviewPlot::getCurveRange(const Mantid::API::MatrixWorksp if(!m_curves.contains(ws)) throw std::runtime_error("Workspace not on preview plot."); - size_t numPoints = m_curves[ws]->data().size(); + size_t numPoints = m_curves[ws].first->data().size(); if(numPoints < 2) return qMakePair(0.0, 0.0); - double low = m_curves[ws]->data().x(0); - double high = m_curves[ws]->data().x(numPoints - 1); + double low = m_curves[ws].first->data().x(0); + double high = m_curves[ws].first->data().x(numPoints - 1); return qMakePair(low, high); } @@ -222,12 +227,13 @@ QPair PreviewPlot::getCurveRange(const QString & wsName) /** * Adds a workspace to the preview plot given a pointer to it. * + * @param curveName Name of curve * @param wsName Name of workspace in ADS - * @param specIndex Spectrrum index to plot + * @param specIndex Spectrum index to plot * @param curveColour Colour of curve to plot */ -void PreviewPlot::addSpectrum(const MatrixWorkspace_const_sptr ws, const size_t specIndex, - const QColor & curveColour) +void PreviewPlot::addSpectrum(const QString & curveName, const MatrixWorkspace_const_sptr ws, + const size_t specIndex, const QColor & curveColour) { // Check the spectrum index is in range if(specIndex >= ws->getNumberHistograms()) @@ -243,13 +249,23 @@ void PreviewPlot::addSpectrum(const MatrixWorkspace_const_sptr ws, const size_t // Remove any existing curves if(m_curves.contains(ws)) - removeCurve(m_curves[ws]); + removeCurve(m_curves[ws].first); // Create the new curve - m_curves[ws] = new QwtPlotCurve(); - m_curves[ws]->setData(wsData); - m_curves[ws]->setPen(curveColour); - m_curves[ws]->attach(m_plot); + QwtPlotCurve *curve = new QwtPlotCurve(); + curve->setData(wsData); + curve->setPen(curveColour); + curve->attach(m_plot); + + // Create the curve label + QLabel *label = new QLabel(curveName, this); + QPalette palette = label->palette(); + palette.setColor(label->foregroundRole(), curveColour); + label->setPalette(palette); + label->setVisible(m_legendShown); + m_legendLayout->addWidget(label); + + m_curves[ws] = qMakePair(curve, label); // Replot m_plot->replot(); @@ -259,12 +275,13 @@ void PreviewPlot::addSpectrum(const MatrixWorkspace_const_sptr ws, const size_t /** * Adds a workspace to the preview plot given its name. * + * @param curveName Name of curve * @param wsName Name of workspace in ADS - * @param specIndex Spectrrum index to plot + * @param specIndex Spectrum index to plot * @param curveColour Colour of curve to plot */ -void PreviewPlot::addSpectrum(const QString & wsName, const size_t specIndex, - const QColor & curveColour) +void PreviewPlot::addSpectrum(const QString & curveName, const QString & wsName, + const size_t specIndex, const QColor & curveColour) { // Try to get a pointer from the name std::string wsNameStr = wsName.toStdString(); @@ -273,7 +290,7 @@ void PreviewPlot::addSpectrum(const QString & wsName, const size_t specIndex, if(!ws) throw std::runtime_error(wsNameStr + " is not a MatrixWorkspace, not supported by PreviewPlot."); - addSpectrum(ws, specIndex, curveColour); + addSpectrum(curveName, ws, specIndex, curveColour); } @@ -284,9 +301,12 @@ void PreviewPlot::addSpectrum(const QString & wsName, const size_t specIndex, */ void PreviewPlot::removeSpectrum(const MatrixWorkspace_const_sptr ws) { - // Remove the curve object + // Remove the curve object and legend label if(m_curves.contains(ws)) - removeCurve(m_curves[ws]); + { + removeCurve(m_curves[ws].first); + m_legendLayout->removeWidget(m_curves[ws].second); + } // Get the curve from the map auto it = m_curves.find(ws); @@ -322,7 +342,10 @@ void PreviewPlot::removeSpectrum(const QString & wsName) */ void PreviewPlot::showLegend(bool show) { - //TODO + m_legendShown = show; + + for(auto it = m_curves.begin(); it != m_curves.end(); ++it) + it.value().second->setVisible(show); } @@ -402,7 +425,10 @@ void PreviewPlot::resizeX() void PreviewPlot::clear() { for(auto it = m_curves.begin(); it != m_curves.end(); ++it) - removeCurve(it.value()); + { + removeCurve(it.value().first); + m_legendLayout->removeWidget(it.value().second); + } m_curves.clear(); From 03af92a15195a40533f39bb48454d82b3c8f47ae Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Tue, 10 Feb 2015 11:42:41 +0000 Subject: [PATCH 056/414] Fix multiple plot legend labels being created Refs #11036 --- .../Indirect/IndirectMoments.ui | 50 ++----------------- .../Indirect/IndirectTransmission.ui | 47 ++--------------- .../inc/MantidQtMantidWidgets/PreviewPlot.h | 6 +-- .../MantidWidgets/src/PreviewPlot.cpp | 25 ++++++---- 4 files changed, 23 insertions(+), 105 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.ui index d089afd2553a..bf24dc5a5623 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectMoments.ui @@ -133,55 +133,11 @@ 255
+ + true + - - - - - - color: green; - - - M0 - - - - - - - color: black; - - - M2 - - - - - - - color: red; - - - M4 - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.ui index 6667bfc95c9d..2a09f6a209c7 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.ui @@ -112,52 +112,11 @@ 255 + + true + - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - color: rgb(255, 0, 0); - - - Sample - - - - - - - Background - - - - - - - color: rgb(0, 255, 0); - - - Transmission - - - - - diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h index e56caff18121..6845a3e28518 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -107,9 +107,6 @@ namespace MantidWidgets /// If the widget was initialised bool m_init; - /// If the curve legend is shown - bool m_legendShown; - /// The plot its self friend class RangeSelector; QwtPlot *m_plot; @@ -128,6 +125,9 @@ namespace MantidWidgets QActionGroup *m_xAxisTypeGroup; QActionGroup *m_yAxisTypeGroup; + /// Menu action for showing/hiding plot legend + QAction *m_showLegendAction; + /// Layout for plot legend QHBoxLayout *m_legendLayout; diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index 6b57bc645646..e6942519c77a 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -30,9 +30,9 @@ namespace PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent), m_removeObserver(*this, &PreviewPlot::handleRemoveEvent), m_replaceObserver(*this, &PreviewPlot::handleReplaceEvent), - m_init(init), m_legendShown(false), m_plot(new QwtPlot(this)), m_curves(), + m_init(init), m_plot(new QwtPlot(this)), m_curves(), m_magnifyTool(NULL), m_panTool(NULL), m_zoomTool(NULL), - m_contextMenu(new QMenu(this)), m_legendLayout(NULL) + m_contextMenu(new QMenu(this)), m_showLegendAction(NULL), m_legendLayout(NULL) { if(init) { @@ -44,12 +44,13 @@ PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent) mainLayout->setSizeConstraint(QLayout::SetNoConstraint); m_plot->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - mainLayout->addWidget(m_plot); m_legendLayout = new QHBoxLayout(mainLayout); m_legendLayout->addStretch(); mainLayout->addItem(m_legendLayout); + mainLayout->addWidget(m_plot); + this->setLayout(mainLayout); } @@ -109,10 +110,10 @@ PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent) m_contextMenu->addSeparator(); // Create the show legend option - QAction *showLegendAction = new QAction("Show Legend", m_contextMenu); - showLegendAction->setCheckable(true); - connect(showLegendAction, SIGNAL(toggled(bool)), this, SLOT(showLegend(bool))); - m_contextMenu->addAction(showLegendAction); + m_showLegendAction = new QAction("Show Legend", m_contextMenu); + m_showLegendAction->setCheckable(true); + connect(m_showLegendAction, SIGNAL(toggled(bool)), this, SLOT(showLegend(bool))); + m_contextMenu->addAction(m_showLegendAction); } @@ -164,7 +165,7 @@ void PreviewPlot::setCanvasColour(const QColor & colour) */ bool PreviewPlot::legendIsShown() { - return m_legendShown; + return m_showLegendAction->isChecked(); } @@ -258,11 +259,11 @@ void PreviewPlot::addSpectrum(const QString & curveName, const MatrixWorkspace_c curve->attach(m_plot); // Create the curve label - QLabel *label = new QLabel(curveName, this); + QLabel *label = new QLabel(curveName); QPalette palette = label->palette(); palette.setColor(label->foregroundRole(), curveColour); label->setPalette(palette); - label->setVisible(m_legendShown); + label->setVisible(legendIsShown()); m_legendLayout->addWidget(label); m_curves[ws] = qMakePair(curve, label); @@ -306,6 +307,7 @@ void PreviewPlot::removeSpectrum(const MatrixWorkspace_const_sptr ws) { removeCurve(m_curves[ws].first); m_legendLayout->removeWidget(m_curves[ws].second); + delete m_curves[ws].second; } // Get the curve from the map @@ -342,7 +344,7 @@ void PreviewPlot::removeSpectrum(const QString & wsName) */ void PreviewPlot::showLegend(bool show) { - m_legendShown = show; + m_showLegendAction->setChecked(show); for(auto it = m_curves.begin(); it != m_curves.end(); ++it) it.value().second->setVisible(show); @@ -428,6 +430,7 @@ void PreviewPlot::clear() { removeCurve(it.value().first); m_legendLayout->removeWidget(it.value().second); + delete it.value().second; } m_curves.clear(); From 110a9b33e514bb858563d24df295c8aef8327409 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Tue, 10 Feb 2015 17:06:13 +0000 Subject: [PATCH 057/414] Update module paths for new structure CMake now writes out two text files containing the location of the data files and the requested default save directory. The save directory now defaults to outside the source tree making it easier to clear away. Refs #10870 --- Code/Mantid/CMakeLists.txt | 3 + .../lib/systemtests/stresstesting.py | 92 ++++++++----------- .../Testing/SystemTests/scripts/.gitignore | 2 + .../SystemTests/scripts/CMakeLists.txt | 28 ++++++ .../SystemTests/scripts/runSystemTests.py | 23 ++++- 5 files changed, 90 insertions(+), 58 deletions(-) create mode 100644 Code/Mantid/Testing/SystemTests/scripts/.gitignore create mode 100644 Code/Mantid/Testing/SystemTests/scripts/CMakeLists.txt diff --git a/Code/Mantid/CMakeLists.txt b/Code/Mantid/CMakeLists.txt index 2b79286d6eb5..673bd4b295ca 100644 --- a/Code/Mantid/CMakeLists.txt +++ b/Code/Mantid/CMakeLists.txt @@ -147,6 +147,9 @@ add_subdirectory ( scripts ) add_subdirectory ( docs ) +# System tests +add_subdirectory ( Testing/SystemTests/scripts ) + ########################################################################### # Installation settings ########################################################################### diff --git a/Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py b/Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py index 7527065812e6..22820a84051a 100644 --- a/Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py +++ b/Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py @@ -22,7 +22,6 @@ File change history is stored at: . ''' - import sys import os import types @@ -38,6 +37,9 @@ import numpy import unittest +# Path to this file +THIS_MODULE_PATH = os.path.dirname(os.path.realpath(__file__)) + ######################################################################### # The base test class. ######################################################################### @@ -484,11 +486,6 @@ def dispatchResults(self, result): ######################################################################### from xmlreporter import XmlResultReporter -######################################################################### -# A class to report results via email -######################################################################### -from emailreporter import EmailResultReporter - ######################################################################### # A base class for a TestRunner ######################################################################### @@ -508,10 +505,7 @@ def __init__(self, need_escaping = False): self._mtdpy_header = '' self._test_dir = '' # Get the path that this module resides in so that the tests know about it - self._framework_path = '' - for p in sys.path: - if 'Framework' in p: - self._framework_path = os.path.abspath(p).replace('\\','/') + self._framework_path = THIS_MODULE_PATH # A string to prefix the code with self._code_prefix = '' self._using_escape = need_escaping @@ -523,7 +517,7 @@ def commandString(self, pycode): raise NotImplementedError('"commandString(self)" should be overridden in a derived class') def setMantidDir(self, mtdheader_dir): - # Store the path to MantidPythonAPI + # Store the path to mantid module self._mtdpy_header = os.path.abspath(mtdheader_dir).replace('\\','/') def setTestDir(self, test_dir): @@ -875,6 +869,7 @@ def isValidTestClass(self, class_obj): class MantidFrameworkConfig: def __init__(self, mantidDir=None, sourceDir=None, + data_dirs="", save_dir = "", loglevel='information', archivesearch=False): # force the environment variable if mantidDir is not None: @@ -900,16 +895,31 @@ def __init__(self, mantidDir=None, sourceDir=None, sys.path.insert(0,self.__locateTestsDir()) # setup the rest of the magic directories - parentDir = os.path.split(self.__sourceDir)[0] - self.__saveDir = os.path.join(parentDir, "logs/").replace('\\','/') - self.__dataDirs = [os.path.join(parentDir, "SystemTests"), - os.path.join(parentDir, "SystemTests/AnalysisTests/ReferenceResults"), - os.path.join(parentDir, "Data"), - os.path.join(parentDir, "Data/LOQ"), - os.path.join(parentDir, "Data/SANS2D"), - os.path.join(parentDir, "Data/PEARL"), - self.__saveDir - ] + self.__saveDir = save_dir + if not os.path.exists(save_dir): + print "Making directory %s to save results" % save_dir + os.mkdir(save_dir) + + else: + if not os.path.isdir(save_dir): + raise RuntimeError("%s is not a directory" % save_dir) + + # assume a string is already semicolon-seaprated + if type(data_dirs) == str: + self.__dataDirs = data_dirs + self.__dataDirs += ";%s" % self.__saveDir + else: + data_path = "" + data_dirs.append(self.__saveDir) + for direc in data_dirs: + if not os.path.exists(direc): + raise RuntimeError('Directory ' + direc + ' was not found.') + search_dir = direc.replace('\\','/') + if not search_dir.endswith('/'): + search_dir += '/' + data_path += search_dir + ';' + #endfor + self.__dataDirs = data_path # set the log level self.__loglevel = loglevel @@ -928,31 +938,15 @@ def __locateSourceDir(self, suggestion): raise RuntimeError("Failed to find source directory") def __locateTestsDir(self): - loc = os.path.join(self.__sourceDir, '../SystemTests/AnalysisTests') + loc = os.path.join(self.__sourceDir, "..", "..", "tests", "analysis") loc = os.path.abspath(loc) if os.path.isdir(loc): return loc else: - raise RuntimeError("'%s' is not a directory (AnalysisTests)" % loc) - - def __getDataDirs(self): - # get the file of the python script - testDir = os.path.split(self.__sourceDir)[0] + raise RuntimeError("Expected the analysis tests directory at '%s' but it is not a directory " % loc) - # add things to the data search path - dirs =[] - dirs.append(os.path.join(testDir, "Data")) - dirs.append(os.path.join(testDir, "Data/LOQ")) - dirs.append(os.path.join(testDir, "Data/SANS2D")) - dirs.append(os.path.join(testDir, "Data/PEARL")) - dirs.append(os.path.join(testDir, "SystemTests")) - dirs.append(os.path.join(testDir, \ - "SystemTests/AnalysisTests/ReferenceResults")) - dirs.append(os.path.abspath(os.getenv("MANTIDPATH"))) - - dirs = [os.path.normpath(item) for item in dirs] - - return dirs + def __getDataDirsAsString(self): + return self._dataDirs def __moveFile(self, src, dst): if os.path.exists(src): @@ -968,12 +962,6 @@ def __copyFile(self, src, dst): testDir = property(lambda self: self.__testDir) def config(self): - if not os.path.exists(self.__saveDir): - print "Making directory %s to save results" % self.__saveDir - os.mkdir(self.__saveDir) - else: - if not os.path.isdir(self.__saveDir): - raise RuntimeError("%s is not a directory" % self.__saveDir) # Start mantid import mantid @@ -991,15 +979,7 @@ def config(self): # Up the log level so that failures can give useful information config['logging.loggers.root.level'] = self.__loglevel # Set the correct search path - data_path = '' - for dir in self.__dataDirs: - if not os.path.exists(dir): - raise RuntimeError('Directory ' + dir + ' was not found.') - search_dir = dir.replace('\\','/') - if not search_dir.endswith('/'): - search_dir += '/' - data_path += search_dir + ';' - config['datasearch.directories'] = data_path + config['datasearch.directories'] = self.__dataDirs # Save path config['defaultsave.directory'] = self.__saveDir diff --git a/Code/Mantid/Testing/SystemTests/scripts/.gitignore b/Code/Mantid/Testing/SystemTests/scripts/.gitignore new file mode 100644 index 000000000000..a2eca9a1a72a --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/.gitignore @@ -0,0 +1,2 @@ +datasearch-directories.txt +defaultsave-directory.txt diff --git a/Code/Mantid/Testing/SystemTests/scripts/CMakeLists.txt b/Code/Mantid/Testing/SystemTests/scripts/CMakeLists.txt new file mode 100644 index 000000000000..ba4866680fca --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/CMakeLists.txt @@ -0,0 +1,28 @@ +###################################################################### +# Write out a files containing +# - the data search directories +# - the default save directory +# These will be read by the MantidConfig class to configure the +# properties file +###################################################################### +# Data search directories +set(DATA_DIRS "") +# Input data +set(SYSTEM_TEST_DATA_DIR ${ExternalData_BINARY_ROOT}/Testing/Data/SystemTest) +list(APPEND DATA_DIRS ${SYSTEM_TEST_DATA_DIR}) +list(APPEND DATA_DIRS ${SYSTEM_TEST_DATA_DIR}/LOQ) +list(APPEND DATA_DIRS ${SYSTEM_TEST_DATA_DIR}/SANS2D) +list(APPEND DATA_DIRS ${SYSTEM_TEST_DATA_DIR}/PEARL) +# Reference results +list(APPEND DATA_DIRS ${ExternalData_BINARY_ROOT}/Testing/SystemTests/tests/analysis/reference) + +# Output to file +# If this is changed, make sure to update the .gitignore in this directory +set(DATA_DIRS_FILE ${CMAKE_CURRENT_LIST_DIR}/datasearch-directories.txt) +# The quotes are important as CMake translates the list to a semicolon-separated string +file(WRITE ${DATA_DIRS_FILE} "${DATA_DIRS}") + +# Default save directory +set(SAVE_DIR ${CMAKE_CURRENT_BINARY_DIR} ) +set(SAVE_DIR_FILE ${CMAKE_CURRENT_LIST_DIR}/defaultsave-directory.txt) +file(WRITE ${SAVE_DIR_FILE} "${SAVE_DIR}") diff --git a/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py b/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py index 88785cc679b0..933eb23ffe63 100755 --- a/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py +++ b/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py @@ -3,7 +3,10 @@ import os # set up the command line options VERSION = "1.1" -DEFAULT_FRAMEWORK_LOC = os.path.dirname(os.path.realpath(__file__)) + "/../StressTestFramework" +PYFILE_PATH = os.path.dirname(os.path.realpath(__file__)) +DEFAULT_FRAMEWORK_LOC = os.path.realpath(os.path.join(PYFILE_PATH, "..","lib","systemtests")) +DATA_DIRS_LIST_PATH = os.path.join(PYFILE_PATH, "datasearch-directories.txt") +SAVE_DIR_LIST_PATH = os.path.join(PYFILE_PATH, "defaultsave-directory.txt") info = [] info.append("This program will configure mantid run all of the system tests located in") @@ -36,6 +39,10 @@ help="Set the log level for test running: [" + ', '.join(loglevelChoices) + "]") parser.add_option("", "--showskipped", dest="showskipped", action="store_true", help="List the skipped tests.") +parser.add_option("-d", "--datapaths", dest="datapaths", + help="A semicolon-separated list of directories to search for data") +parser.add_option("-s", "--savedir", dest="savedir", + help="A directory to use for the Mantid save path") parser.add_option("", "--archivesearch", dest="archivesearch", action="store_true", help="Turn on archive search for file finder.") parser.set_defaults(frameworkLoc=DEFAULT_FRAMEWORK_LOC, mantidpath=None, makeprop=True, @@ -80,7 +87,19 @@ os.environ[path_var] = mantid_module_path + os.pathsep + os.environ.get(path_var, "") # Configure mantid +# Parse files containing the search and save directories, unless otherwise given +data_paths = options.datapaths +if data_paths is None or data_paths == "": + with open(DATA_DIRS_LIST_PATH, 'r') as f_handle: + data_paths = f_handle.read().strip() + +save_dir = options.savedir +if save_dir is None or save_dir == "": + with open(SAVE_DIR_LIST_PATH, 'r') as f_handle: + save_dir = f_handle.read().strip() +# Configure properties file mtdconf = stresstesting.MantidFrameworkConfig(mantid_module_path, loglevel=options.loglevel, + data_dirs=data_paths, save_dir=save_dir, archivesearch=options.archivesearch) if options.makeprop: mtdconf.config() @@ -100,7 +119,7 @@ xml_report.write(reporter.getResults()) xml_report.close() -# put the configuratoin back to its original state +# put the configuration back to its original state if options.makeprop: mtdconf.restoreconfig() From 54f0754b27412464fbe494d83117672e080be5b7 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Tue, 10 Feb 2015 17:44:10 +0000 Subject: [PATCH 058/414] Update InstallerTests wrapper script for new layout. It can now be passed a directory to search for packages rather than assuming it should look in the current directory. Refs #10870 --- .../lib/systemtests/stresstesting.py | 4 +- .../SystemTests/scripts/InstallerTests.py | 39 ++++++++++--------- .../SystemTests/scripts/mantidinstaller.py | 34 ++++++++-------- .../SystemTests/scripts/runSystemTests.py | 10 ++--- 4 files changed, 46 insertions(+), 41 deletions(-) diff --git a/Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py b/Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py index 22820a84051a..31aa6f54b281 100644 --- a/Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py +++ b/Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py @@ -38,7 +38,7 @@ import unittest # Path to this file -THIS_MODULE_PATH = os.path.dirname(os.path.realpath(__file__)) +THIS_MODULE_DIR = os.path.dirname(os.path.realpath(__file__)) ######################################################################### # The base test class. @@ -505,7 +505,7 @@ def __init__(self, need_escaping = False): self._mtdpy_header = '' self._test_dir = '' # Get the path that this module resides in so that the tests know about it - self._framework_path = THIS_MODULE_PATH + self._framework_path = THIS_MODULE_DIR # A string to prefix the code with self._code_prefix = '' self._using_escape = need_escaping diff --git a/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py b/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py index cae938d474bb..e28a706112b3 100644 --- a/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py +++ b/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py @@ -1,3 +1,5 @@ +"""Finds a package, installs it and runs the tests against it. +""" import os import sys import platform @@ -8,15 +10,11 @@ from mantidinstaller import (createScriptLog, log, stop, failure, scriptfailure, get_installer, run) -''' - -This script copies Mantid installer for the system it is running on from the build server, -installs it, runs system tests and produces an xml report file SystemTestsReport.xml - -''' +THIS_MODULE_DIR = os.path.dirname(os.path.realpath(__file__)) +SAVE_DIR_LIST_PATH = os.path.join(THIS_MODULE_DIR, "defaultsave-directory.txt") try: - opt, argv = getopt(sys.argv[1:],'nohvR:l:') + opt, argv = getopt(sys.argv[1:],'d:nohvR:l:') except: opt = [('-h','')] @@ -24,6 +22,7 @@ print "Usage: %s [OPTIONS]" % os.path.basename(sys.argv[0]) print print "Valid options are:" + print " -d Directory to look for packages. Defaults to current working directory" print " -n Run tests without installing Mantid (it must be already installed)" print " -o Output to the screen instead of log files" print " -h Display the usage" @@ -35,6 +34,7 @@ test_regex = None out2stdout = False log_level = 'notice' +package_dir = os.getcwd() for option, arg in opt: if option == '-n': doInstall = False @@ -44,18 +44,20 @@ test_regex = arg if option == '-l' and arg != "": log_level = arg + if option == '-d' and arg != "": + package_dir = arg -# The log file for this script -parentDir = os.path.abspath('..').replace('\\','/') -if not os.path.exists(parentDir + '/logs'): - os.mkdir(parentDir + '/logs') +# Log to the configured default save directory +with open(SAVE_DIR_LIST_PATH, 'r') as f_handle: + output_dir = f_handle.read().strip() -createScriptLog(parentDir + '/logs/TestScript.log') -testRunLogPath = parentDir + '/logs/testsRun.log' -testRunErrPath = parentDir + '/logs/testsRun.err' +createScriptLog(os.path.join(output_dir, "TestScript.log")) +testRunLogPath = os.path.join(output_dir, "test_output.log") +testRunErrPath = os.path.join(output_dir, "test_errors.log") log('Starting system tests') -installer = get_installer(doInstall) +log('Searching for packages in ' + package_dir) +installer = get_installer(package_dir, doInstall) # Install the found package if doInstall: @@ -89,17 +91,18 @@ try: # Now get the revision number/git commit ID (remove the leading 'g' that isn't part of it) revision = run(installer.mantidPlotPath + ' -r').lstrip('g') - revision_tested = open('revision_tested.log','w') + revision_tested = open(os.path.join(output_dir, 'revision_tested.log'), 'w') if revision and len(version) > 0: revision_tested.write(revision) revision_tested.close() except Exception, err: scriptfailure('Revision test failed: '+str(err), installer) -log("Running system tests. Log files are: logs/testsRun.log and logs/testsRun.err") +log("Running system tests. Log files are: '%s' and '%s'" % (testRunLogPath,testRunErrPath)) try: # Pick the correct Mantid along with the bundled python on windows - run_test_cmd = "%s %s/runSystemTests.py --loglevel=%s --mantidpath=%s" % (installer.python_cmd, os.path.dirname(os.path.realpath(__file__)), log_level, mantidPlotDir) + run_test_cmd = "%s %s/runSystemTests.py --loglevel=%s --mantidpath=%s" % \ + (installer.python_cmd, THIS_MODULE_DIR, log_level, mantidPlotDir) if test_regex is not None: run_test_cmd += " -R " + test_regex if out2stdout: diff --git a/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py b/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py index 3b566b8f4e15..f78094738b9d 100644 --- a/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py +++ b/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py @@ -54,24 +54,25 @@ def scriptfailure(txt, installer=None): sys.exit(1) -def get_installer(do_install=True): +def get_installer(package_dir, do_install=True): """ Creates the correct class for the current platform + @param package_dir :: The directory to search for packages @param do_install :: True if installation is to be performed """ system = platform.system() if system == 'Windows': - return NSISInstaller(do_install) + return NSISInstaller(package_dir, do_install) elif system == 'Linux': dist = platform.dist() if dist[0] == 'Ubuntu': - return DebInstaller(do_install) - elif dist[0] == 'redhat' and (dist[1].startswith('5.') or dist[1].startswith('6.')): - return RPMInstaller(do_install) + return DebInstaller(package_dir, do_install) + elif dist[0] == 'redhat': + return RPMInstaller(package_dir, do_install) else: scriptfailure('Unknown Linux flavour: %s' % str(dist)) elif system == 'Darwin': - return DMGInstaller(do_install) + return DMGInstaller(package_dir, do_install) else: raise scriptfailure("Unsupported platform") @@ -98,14 +99,15 @@ class MantidInstaller(object): no_uninstall = False python_cmd = "python" - def __init__(self, do_install, filepattern): + def __init__(self, package_dir, filepattern, + do_install): """Initialized with a pattern to find a path to an installer """ if not do_install: return # Glob for packages - matches = glob.glob(os.path.abspath(filepattern)) + matches = glob.glob(os.path.join(package_dir, filepattern)) if len(matches) > 0: # This will put the release mantid packages at the start and the nightly ones at the end # with increasing version numbers @@ -139,8 +141,8 @@ class NSISInstaller(MantidInstaller): to install Mantid """ - def __init__(self, do_install): - MantidInstaller.__init__(self, do_install, 'Mantid-*-win*.exe') + def __init__(self, package_dir, do_install): + MantidInstaller.__init__(self, package_dir, 'Mantid-*-win*.exe', do_install) self.mantidPlotPath = 'C:/MantidInstall/bin/MantidPlot.exe' self.python_cmd = "C:/MantidInstall/bin/python.exe" @@ -164,8 +166,8 @@ class DebInstaller(MantidInstaller): """Uses a deb package to install mantid """ - def __init__(self, do_install): - MantidInstaller.__init__(self, do_install, 'mantid*.deb') + def __init__(self, package_dir, do_install): + MantidInstaller.__init__(self, package_dir, 'mantid*.deb', do_install) package = os.path.basename(self.mantidInstaller) if 'mantidnightly' in package: self.mantidPlotPath = '/opt/mantidnightly/bin/MantidPlot' @@ -189,8 +191,8 @@ class RPMInstaller(MantidInstaller): """Uses a rpm package to install mantid """ - def __init__(self, do_install): - MantidInstaller.__init__(self, do_install, 'mantid*.rpm') + def __init__(self, package_dir, do_install): + MantidInstaller.__init__(self, package_dir, 'mantid*.rpm', do_install) package = os.path.basename(self.mantidInstaller) if 'mantidnightly' in package: self.mantidPlotPath = '/opt/mantidnightly/bin/MantidPlot' @@ -222,8 +224,8 @@ def do_uninstall(self): class DMGInstaller(MantidInstaller): """Uses an OS X dmg file to install mantid """ - def __init__(self, do_install): - MantidInstaller.__init__(self, do_install, 'mantid-*.dmg') + def __init__(self, package_dir, do_install): + MantidInstaller.__init__(self, package_dir, 'mantid-*.dmg', do_install) self.mantidPlotPath = '/Applications/MantidPlot.app/Contents/MacOS/MantidPlot' os.environ['DYLD_LIBRARY_PATH'] = '/Applications/MantidPlot.app/Contents/MacOS' diff --git a/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py b/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py index 933eb23ffe63..ca5c5f1be96e 100755 --- a/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py +++ b/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py @@ -3,14 +3,14 @@ import os # set up the command line options VERSION = "1.1" -PYFILE_PATH = os.path.dirname(os.path.realpath(__file__)) -DEFAULT_FRAMEWORK_LOC = os.path.realpath(os.path.join(PYFILE_PATH, "..","lib","systemtests")) -DATA_DIRS_LIST_PATH = os.path.join(PYFILE_PATH, "datasearch-directories.txt") -SAVE_DIR_LIST_PATH = os.path.join(PYFILE_PATH, "defaultsave-directory.txt") +THIS_MODULE_DIR = os.path.dirname(os.path.realpath(__file__)) +DEFAULT_FRAMEWORK_LOC = os.path.realpath(os.path.join(THIS_MODULE_DIR, "..","lib","systemtests")) +DATA_DIRS_LIST_PATH = os.path.join(THIS_MODULE_DIR, "datasearch-directories.txt") +SAVE_DIR_LIST_PATH = os.path.join(THIS_MODULE_DIR, "defaultsave-directory.txt") info = [] info.append("This program will configure mantid run all of the system tests located in") -info.append("the 'SystemTests/AnalysisTests' directory and log the results in 'logs/'.") +info.append("the 'tests/analysis' directory.") info.append("This program will create a temporary 'Mantid.user.properties' file which") info.append("it will rename to 'Mantid.user.properties.systest' upon completion. The") info.append("current version of the code does not print to stdout while the test is") From 1d77c360a9639df973b395bd627b92654fd62a68 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Tue, 10 Feb 2015 17:47:52 +0000 Subject: [PATCH 059/414] Create version_tested.log file in binary directory. Refs #10870 --- Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py b/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py index e28a706112b3..620d4e5e7563 100644 --- a/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py +++ b/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py @@ -81,7 +81,7 @@ try: # Keep hold of the version that was run version = run(installer.mantidPlotPath + ' -v') - version_tested = open('version_tested.log','w') + version_tested = open(os.path.join(output_dir,'version_tested.log'),'w') if version and len(version) > 0: version_tested.write(version) version_tested.close() From a6ab43c4e96f6fa160dd68b9ad42ba1d9fb32c49 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Wed, 11 Feb 2015 11:55:11 +0000 Subject: [PATCH 060/414] refs #11056. Add regression test. Prove that this doesn't work yet. --- .../Framework/DataObjects/test/PeakTest.h | 81 ++++++++++++++++++- .../ComponentCreationHelper.h | 3 + .../src/ComponentCreationHelper.cpp | 40 +++++++++ 3 files changed, 120 insertions(+), 4 deletions(-) diff --git a/Code/Mantid/Framework/DataObjects/test/PeakTest.h b/Code/Mantid/Framework/DataObjects/test/PeakTest.h index e7bd1b9929f4..05ff93653ea8 100644 --- a/Code/Mantid/Framework/DataObjects/test/PeakTest.h +++ b/Code/Mantid/Framework/DataObjects/test/PeakTest.h @@ -5,6 +5,11 @@ #include "MockObjects.h" #include "MantidKernel/Timer.h" #include "MantidKernel/System.h" +#include "MantidKernel/UnitFactory.h" +#include "MantidKernel/Unit.h" +#include "MantidKernel/V3D.h" +#include "MantidKernel/PhysicalConstants.h" +#include "MantidGeometry/Instrument/ReferenceFrame.h" #include #include #include @@ -18,12 +23,25 @@ using namespace Mantid::Kernel; class PeakTest : public CxxTest::TestSuite { +private: + /// Common instrument + Instrument_sptr inst; + Instrument_sptr m_minimalInstrument; public: - /// Common instrument - Instrument_sptr inst; - void setUp() + + + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static PeakTest *createSuite() { + return new PeakTest(); + } + static void destroySuite(PeakTest *suite) { delete suite; } + + + // Constructor + PeakTest() : inst(ComponentCreationHelper::createTestInstrumentRectangular(5, 100)) { - inst = ComponentCreationHelper::createTestInstrumentRectangular(5, 100); + } void test_constructor() @@ -261,6 +279,7 @@ class PeakTest : public CxxTest::TestSuite /** Compare two peaks, but not the detector IDs etc. */ void comparePeaks(Peak & p1, Peak & p2) { + // TODO. Peak should implement bool operator==(const Peak&) and that should be tested, rather than having external functionality here. TS_ASSERT_EQUALS( p1.getQLabFrame(), p2.getQLabFrame() ); TS_ASSERT_EQUALS( p1.getQSampleFrame(), p2.getQSampleFrame() ); TS_ASSERT_EQUALS( p1.getDetPos(), p2.getDetPos() ); @@ -290,6 +309,60 @@ class PeakTest : public CxxTest::TestSuite TS_ASSERT_EQUALS( p2.getDetectorID(), -1); } + void test_setQLabFrame2() + { + + // Create fictional instrument + const V3D source(0,0,0); + const V3D sample(15, 0, 0); + const V3D detectorPos(20, 5, 0); + const V3D beam1 = sample - source; + const V3D beam2 = detectorPos - sample; + auto minimalInstrument = ComponentCreationHelper::createMinimalInstrument( source, sample, detectorPos ); + + // Calculate energy of neutron based on velocity + const double velocity = 1.1 * 10e3; // m/sec + double efixed = 0.5 * Mantid::PhysicalConstants::NeutronMass * velocity * velocity ; // In Joules + efixed = efixed / Mantid::PhysicalConstants::meV; + + // Derive distances and angles + const double l1 = beam1.norm(); + const double l2 = beam2.norm(); + const double scatteringAngle2 = beam2.angle(beam1); + const V3D qLabDir = beam1 - beam2; + + // Derive the wavelength + std::vector x; + const double microSecsInSec = 1e6; + x.push_back( ( (l1 + l2) / velocity ) * microSecsInSec ); // Make a TOF + std::vector y; + Unit_sptr unitOfLambda = UnitFactory::Instance().create("Wavelength"); + unitOfLambda->fromTOF(x, y, l1, l2, scatteringAngle2, 0, efixed, 0); + + // Derive QLab for diffraction + const double wavenumber_in_angstrom_times_tof_in_microsec = + (Mantid::PhysicalConstants::NeutronMass * (l1 + l2) * 1e-10 * microSecsInSec) / + Mantid::PhysicalConstants::h_bar; + + V3D qLab = qLabDir * wavenumber_in_angstrom_times_tof_in_microsec; + + + //Peak peak(minimalInstrument, 1 /* detector id */, x[0] /*wavelength*/); + + + + Peak peak; // Everything will be default + peak.setInstrument(minimalInstrument); // Can't do anything without the instrument + peak.setQLabFrame(qLab); + auto detector = peak.getDetector(); + + TS_ASSERT_EQUALS(1, detector->getID()); + TS_ASSERT_EQUALS(detectorPos, detector->getPos()) + + // Test that wavelengths aggree firstly. + //TS_ASSERT_EQUALS(x[0], peak.getWavelength()); + } + /** Create peaks using Q in sample frame + a goniometer rotation matrix*/ void test_setQSampleFrame() { diff --git a/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/ComponentCreationHelper.h b/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/ComponentCreationHelper.h index 030e53a84b3a..073fe49bd53c 100644 --- a/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/ComponentCreationHelper.h +++ b/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/ComponentCreationHelper.h @@ -150,6 +150,9 @@ createTestInstrumentRectangular(int num_banks, int pixels, Mantid::Geometry::Instrument_sptr createTestInstrumentRectangular2(int num_banks, int pixels, double pixelSpacing = 0.008); + +/// Creates a mimimal valid virtual instrument. +Mantid::Geometry::Instrument_sptr createMinimalInstrument(const Mantid::Kernel::V3D& sourcePos, const Mantid::Kernel::V3D& samplePos, const Mantid::Kernel::V3D& detectorPos ); } #endif // COMPONENTCREATIONHELPERS_H_ diff --git a/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp b/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp index 110cb9803fb1..5434f0c11c1b 100644 --- a/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp +++ b/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp @@ -20,9 +20,11 @@ #include "MantidGeometry/Instrument/DetectorGroup.h" #include "MantidGeometry/Instrument/Detector.h" #include "MantidGeometry/Instrument/RectangularDetector.h" +#include "MantidGeometry/Instrument/ReferenceFrame.h" #include #include +#include #include "MantidGeometry/IDetector.h" using namespace Mantid::Geometry; @@ -559,4 +561,42 @@ Instrument_sptr createTestInstrumentRectangular2(int num_banks, int pixels, return testInst; } + +/** + * createOneDetectorInstrument, creates the most simple possible definition of an instrument in which we can extract a valid L1 and L2 distance for unit calculations. + * + * Beam direction is along X, + * Up direction is Y + * + * @param sourcePos : V3D position + * @param samplePos : V3D sample position + * @param detectorPos : V3D detector position + * @return Instrument generated. + */ +Instrument_sptr createMinimalInstrument(const V3D& sourcePos, const V3D& samplePos, const V3D& detectorPos ) +{ + Instrument_sptr instrument = boost::make_shared(); + instrument->setReferenceFrame( + boost::make_shared(Mantid::Geometry::Y /*up*/, Mantid::Geometry::X /*along*/, Left, "0,0,0")); + + // A source + ObjComponent *source = new ObjComponent("source"); + source->setPos(sourcePos); + instrument->add(source); + instrument->markAsSource(source); + + // A sample + ObjComponent *sample = new ObjComponent("some-surface-holder"); + source->setPos(samplePos); + instrument->add(sample); + instrument->markAsSamplePos(sample); + + // A detector + Detector *det = new Detector("point-detector", 1 /*detector id*/, NULL); + det->setPos(detectorPos); + instrument->add(det); + instrument->markAsDetector(det); + + return instrument; +} } From 01575f7b2cfec2436a6d40b9bcbd59cd90e9621e Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Wed, 11 Feb 2015 12:01:32 +0000 Subject: [PATCH 061/414] Handle WS updates from ADS Refs #11036 --- .../inc/MantidQtMantidWidgets/PreviewPlot.h | 21 ++- .../MantidWidgets/src/PreviewPlot.cpp | 132 ++++++++++++------ 2 files changed, 112 insertions(+), 41 deletions(-) diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h index 6845a3e28518..f66860380d9e 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -77,6 +77,10 @@ namespace MantidWidgets void removeSpectrum(const Mantid::API::MatrixWorkspace_const_sptr ws); void removeSpectrum(const QString & wsName); + signals: + /// Signals that the plot should be refreshed + void needToReplot(); + public slots: void showLegend(bool show); void togglePanTool(bool enabled); @@ -87,9 +91,22 @@ namespace MantidWidgets void replot(); private: + /// Holds information about a plot curve + struct PlotCurveConfiguration + { + QwtPlotCurve *curve; + QLabel *label; + QColor colour; + size_t wsIndex; + + PlotCurveConfiguration(): + curve(NULL), label(NULL) {} + }; + void handleRemoveEvent(Mantid::API::WorkspacePreDeleteNotification_ptr pNf); void handleReplaceEvent(Mantid::API::WorkspaceAfterReplaceNotification_ptr pNf); + QwtPlotCurve * addCurve(const Mantid::API::MatrixWorkspace_const_sptr ws, const size_t specIndex, const QColor & curveColour); void removeCurve(QwtPlotCurve *curve); QList addOptionsToMenus(QString menuName, QActionGroup *group, QStringList items, QString defaultItem); @@ -111,8 +128,8 @@ namespace MantidWidgets friend class RangeSelector; QwtPlot *m_plot; - /// Map of curve key to plot curves and curve label - QMap> m_curves; + /// Map of curve key to plot info + QMap m_curves; /// Plot manipulation tools QwtPlotMagnifier *m_magnifyTool; diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index e6942519c77a..e6d62e29951a 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -44,13 +44,12 @@ PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent) mainLayout->setSizeConstraint(QLayout::SetNoConstraint); m_plot->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + mainLayout->addWidget(m_plot); m_legendLayout = new QHBoxLayout(mainLayout); m_legendLayout->addStretch(); mainLayout->addItem(m_legendLayout); - mainLayout->addWidget(m_plot); - this->setLayout(mainLayout); } @@ -114,6 +113,8 @@ PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent) m_showLegendAction->setCheckable(true); connect(m_showLegendAction, SIGNAL(toggled(bool)), this, SLOT(showLegend(bool))); m_contextMenu->addAction(m_showLegendAction); + + connect(this, SIGNAL(needToReplot()), this, SLOT(replot())); } @@ -195,13 +196,13 @@ QPair PreviewPlot::getCurveRange(const Mantid::API::MatrixWorksp if(!m_curves.contains(ws)) throw std::runtime_error("Workspace not on preview plot."); - size_t numPoints = m_curves[ws].first->data().size(); + size_t numPoints = m_curves[ws].curve->data().size(); if(numPoints < 2) return qMakePair(0.0, 0.0); - double low = m_curves[ws].first->data().x(0); - double high = m_curves[ws].first->data().x(numPoints - 1); + double low = m_curves[ws].curve->data().x(0); + double high = m_curves[ws].curve->data().x(numPoints - 1); return qMakePair(low, high); } @@ -236,27 +237,8 @@ QPair PreviewPlot::getCurveRange(const QString & wsName) void PreviewPlot::addSpectrum(const QString & curveName, const MatrixWorkspace_const_sptr ws, const size_t specIndex, const QColor & curveColour) { - // Check the spectrum index is in range - if(specIndex >= ws->getNumberHistograms()) - throw std::runtime_error("Workspace index is out of range, cannot plot."); - - // Check the X axis is large enough - if(ws->readX(0).size() < 2) - throw std::runtime_error("X axis is too small to generate a histogram plot."); - - // Create the plot data - const bool logScale(false), distribution(false); - QwtWorkspaceSpectrumData wsData(*ws, static_cast(specIndex), logScale, distribution); - - // Remove any existing curves - if(m_curves.contains(ws)) - removeCurve(m_curves[ws].first); - - // Create the new curve - QwtPlotCurve *curve = new QwtPlotCurve(); - curve->setData(wsData); - curve->setPen(curveColour); - curve->attach(m_plot); + // Create the curve + QwtPlotCurve * curve = addCurve(ws, specIndex, curveColour); // Create the curve label QLabel *label = new QLabel(curveName); @@ -266,10 +248,13 @@ void PreviewPlot::addSpectrum(const QString & curveName, const MatrixWorkspace_c label->setVisible(legendIsShown()); m_legendLayout->addWidget(label); - m_curves[ws] = qMakePair(curve, label); + m_curves[ws].curve = curve; + m_curves[ws].label = label; + m_curves[ws].colour = curveColour; + m_curves[ws].wsIndex = specIndex; // Replot - m_plot->replot(); + emit needToReplot(); } @@ -305,9 +290,9 @@ void PreviewPlot::removeSpectrum(const MatrixWorkspace_const_sptr ws) // Remove the curve object and legend label if(m_curves.contains(ws)) { - removeCurve(m_curves[ws].first); - m_legendLayout->removeWidget(m_curves[ws].second); - delete m_curves[ws].second; + removeCurve(m_curves[ws].curve); + m_legendLayout->removeWidget(m_curves[ws].label); + delete m_curves[ws].label; } // Get the curve from the map @@ -347,7 +332,7 @@ void PreviewPlot::showLegend(bool show) m_showLegendAction->setChecked(show); for(auto it = m_curves.begin(); it != m_curves.end(); ++it) - it.value().second->setVisible(show); + it.value().label->setVisible(show); } @@ -428,14 +413,14 @@ void PreviewPlot::clear() { for(auto it = m_curves.begin(); it != m_curves.end(); ++it) { - removeCurve(it.value().first); - m_legendLayout->removeWidget(it.value().second); - delete it.value().second; + removeCurve(it.value().curve); + m_legendLayout->removeWidget(it.value().label); + delete it.value().label; } m_curves.clear(); - replot(); + emit needToReplot(); } @@ -448,15 +433,84 @@ void PreviewPlot::replot() } +/** + * Handle a workspace being deleted from ADS. + * + * Removes it from the plot (via removeSpectrum). + * + * @param pNF Poco notification + */ void PreviewPlot::handleRemoveEvent(WorkspacePreDeleteNotification_ptr pNf) { - //TODO + MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast(pNf->object()); + + // Ignore non matrix worksapces and those not in the plot + if(!ws || !m_curves.contains(ws)) + return; + + // Remove the workspace + removeSpectrum(ws); + + emit needToReplot(); } +/** + * Handle a workspace being modified in ADS. + * + * Removes the existing curve and re adds it to reflect new data. + * + * @param pNf Poco notification + */ void PreviewPlot::handleReplaceEvent(WorkspaceAfterReplaceNotification_ptr pNf) { - //TODO + MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast(pNf->object()); + + // Ignore non matrix worksapces and those not in the plot + if(!ws || !m_curves.contains(ws)) + return; + + // Replace the existing curve + m_curves[ws].curve = addCurve(ws, m_curves[ws].wsIndex, m_curves[ws].colour); + + emit needToReplot(); +} + + +/** + * Creates a new curve and adds it to the plot. + * + * @param ws Worksapce pointer + * @param specIndex Index of histogram to plot + * @param curveColour Colour of curve + * @return Pointer to new curve + */ +QwtPlotCurve * PreviewPlot::addCurve(const MatrixWorkspace_const_sptr ws, const size_t specIndex, + const QColor & curveColour) +{ + // Check the spectrum index is in range + if(specIndex >= ws->getNumberHistograms()) + throw std::runtime_error("Workspace index is out of range, cannot plot."); + + // Check the X axis is large enough + if(ws->readX(0).size() < 2) + throw std::runtime_error("X axis is too small to generate a histogram plot."); + + // Create the plot data + const bool logScale(false), distribution(false); + QwtWorkspaceSpectrumData wsData(*ws, static_cast(specIndex), logScale, distribution); + + // Remove any existing curves + if(m_curves.contains(ws)) + removeCurve(m_curves[ws].curve); + + // Create the new curve + QwtPlotCurve *curve = new QwtPlotCurve(); + curve->setData(wsData); + curve->setPen(curveColour); + curve->attach(m_plot); + + return curve; } @@ -505,7 +559,7 @@ QList PreviewPlot::addOptionsToMenus(QString menuName, QActionGroup * action->setChecked(*it == defaultItem); } - QAction *menuAction = new QAction(menuName, this); + QAction *menuAction = new QAction(menuName, menu); menuAction->setMenu(menu); m_contextMenu->addAction(menuAction); From b0d5c230ad5bd4a6c25b660fd46d4de7997ea115 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Wed, 11 Feb 2015 13:33:18 +0000 Subject: [PATCH 062/414] refs #11056. Peak doesn't assume reference frame. This was a serious problem that caused a crash with my regression test as soon as I started using my new fake instrument, which is defined in a different reference frame. The setQLab, now uses the instrument reference frame to complete the calculations rather than assuming what it is. --- .../Mantid/Framework/DataObjects/src/Peak.cpp | 32 ++++++++++++------- .../Framework/DataObjects/test/PeakTest.h | 8 +++-- .../Instrument/ReferenceFrame.h | 2 +- 3 files changed, 27 insertions(+), 15 deletions(-) diff --git a/Code/Mantid/Framework/DataObjects/src/Peak.cpp b/Code/Mantid/Framework/DataObjects/src/Peak.cpp index 5e6101ff5e9b..846a66aa985c 100644 --- a/Code/Mantid/Framework/DataObjects/src/Peak.cpp +++ b/Code/Mantid/Framework/DataObjects/src/Peak.cpp @@ -1,6 +1,7 @@ #include "MantidDataObjects/Peak.h" #include "MantidDataObjects/NoShape.h" #include "MantidGeometry/Instrument/RectangularDetector.h" +#include "MantidGeometry/Instrument/ReferenceFrame.h" #include "MantidGeometry/Objects/InstrumentRayTracer.h" #include "MantidKernel/Strings.h" #include "MantidKernel/System.h" @@ -495,25 +496,32 @@ void Peak::setQLabFrame(Mantid::Kernel::V3D QLabFrame, m_Col = -1; m_BankName = "None"; + // The q-vector direction of the peak is = goniometer * ub * hkl_vector V3D q = QLabFrame; - /* The incident neutron wavevector is in the +Z direction, ki = 1/wl (in z - * direction). + /* The incident neutron wavevector is along the beam direction, ki = 1/wl (usually z, but referenceframe is definitive). * In the inelastic convention, q = ki - kf. - * The final neutron wavector kf = -qx in x; -qy in y; and (-qz+1/wl) in z. + * The final neutron wavector kf = -qx in x; -qy in y; and (-q.beam_dir+1/wl) in beam direction. * AND: norm(kf) = norm(ki) = 2*pi/wavelength - * THEREFORE: 1/wl = norm(q)^2 / (2*qz) + * THEREFORE: 1/wl = norm(q)^2 / (2*q.beam_dir) */ double norm_q = q.norm(); + if(!this->m_inst) + { + throw std::invalid_argument("Setting QLab without an instrument would lead to an inconsistent state for the Peak"); + } + boost::shared_ptr refFrame = this->m_inst->getReferenceFrame(); + const V3D refBeamDir = refFrame->vecPointingAlongBeam(); + const double qBeam = q.scalar_prod(refBeamDir); if (norm_q == 0.0) throw std::invalid_argument("Peak::setQLabFrame(): Q cannot be 0,0,0."); - if (q.Z() == 0.0) + if ( qBeam == 0.0) throw std::invalid_argument( - "Peak::setQLabFrame(): Q cannot be 0 in the Z (beam) direction."); + "Peak::setQLabFrame(): Q cannot be 0 in the beam direction."); - double one_over_wl = (norm_q * norm_q) / (2.0 * q.Z()); + double one_over_wl = (norm_q * norm_q) / (2.0 * qBeam); double wl = (2.0 * M_PI) / one_over_wl; if (wl < 0.0) { std::ostringstream mess; @@ -522,16 +530,16 @@ void Peak::setQLabFrame(Mantid::Kernel::V3D QLabFrame, throw std::invalid_argument(mess.str()); } - // This is the scattered direction, kf = (-qx, -qy, 1/wl-qz) - V3D beam = q * -1.0; - beam.setZ(one_over_wl - q.Z()); - beam.normalize(); // Save the wavelength this->setWavelength(wl); + V3D detectorDir = q * -1.0; + detectorDir[refFrame->pointingAlongBeam()] = one_over_wl - q.Z(); + detectorDir.normalize(); + // Use the given detector distance to find the detector position. - detPos = samplePos + beam * detectorDistance; + detPos = samplePos + detectorDir * detectorDistance; } /** After creating a peak using the Q in the lab frame, diff --git a/Code/Mantid/Framework/DataObjects/test/PeakTest.h b/Code/Mantid/Framework/DataObjects/test/PeakTest.h index 05ff93653ea8..3e2e5fa05aee 100644 --- a/Code/Mantid/Framework/DataObjects/test/PeakTest.h +++ b/Code/Mantid/Framework/DataObjects/test/PeakTest.h @@ -356,8 +356,12 @@ class PeakTest : public CxxTest::TestSuite peak.setQLabFrame(qLab); auto detector = peak.getDetector(); - TS_ASSERT_EQUALS(1, detector->getID()); - TS_ASSERT_EQUALS(detectorPos, detector->getPos()) + TSM_ASSERT("No detector", detector); + if(detector) + { + TS_ASSERT_EQUALS(1, detector->getID()); + TS_ASSERT_EQUALS(detectorPos, detector->getPos()); + } // Test that wavelengths aggree firstly. //TS_ASSERT_EQUALS(x[0], peak.getWavelength()); diff --git a/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Instrument/ReferenceFrame.h b/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Instrument/ReferenceFrame.h index fb4c388bfe30..338e060f4ce3 100644 --- a/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Instrument/ReferenceFrame.h +++ b/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Instrument/ReferenceFrame.h @@ -8,7 +8,7 @@ namespace Mantid { namespace Geometry { /// Type to describe pointing along options -enum PointingAlong { X, Y, Z }; +enum PointingAlong { X=0, Y=1, Z=2 }; /// Type to distingusih between l and r handedness enum Handedness { Left, Right }; From 7db86202b7dca91e192fe9e95274837ea1f56c2a Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Wed, 11 Feb 2015 15:43:01 +0000 Subject: [PATCH 063/414] refs #11056. Peak looks up detector after setQLab. Refactor to use the ray tracing tools to look up the detector. Distance is optional, but I'd rather remove it altogether. --- .../Framework/API/inc/MantidAPI/IPeak.h | 3 +- .../DataObjects/inc/MantidDataObjects/Peak.h | 10 ++++- .../Mantid/Framework/DataObjects/src/Peak.cpp | 38 ++++++++++++++++--- .../Framework/DataObjects/test/PeakTest.h | 4 +- .../src/ComponentCreationHelper.cpp | 5 ++- 5 files changed, 48 insertions(+), 12 deletions(-) diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h b/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h index 442f9cca369e..a0c92986df81 100644 --- a/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h +++ b/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h @@ -7,6 +7,7 @@ #include "MantidKernel/Matrix.h" #include "MantidKernel/V3D.h" #include "MantidKernel/PhysicalConstants.h" +#include namespace Mantid { namespace API { @@ -52,7 +53,7 @@ class MANTID_API_DLL IPeak { virtual void setQSampleFrame(Mantid::Kernel::V3D QSampleFrame, double detectorDistance = 1.0) = 0; virtual void setQLabFrame(Mantid::Kernel::V3D QLabFrame, - double detectorDistance = 1.0) = 0; + boost::optional detectorDistance = boost::optional()) = 0; virtual void setWavelength(double wavelength) = 0; virtual double getWavelength() const = 0; diff --git a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Peak.h b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Peak.h index 877e8adad604..cc3a5a084750 100644 --- a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Peak.h +++ b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Peak.h @@ -3,12 +3,15 @@ #include "MantidAPI/IPeak.h" #include "MantidGeometry/Instrument.h" +#include "MantidKernel/Logger.h" #include "MantidKernel/Matrix.h" #include "MantidKernel/V3D.h" #include "MantidKernel/PhysicalConstants.h" #include "MantidKernel/System.h" #include "MantidGeometry/Crystal/PeakShape.h" #include +#include + namespace Mantid { namespace DataObjects { @@ -85,7 +88,7 @@ class DLLExport Peak : public API::IPeak { void setQSampleFrame(Mantid::Kernel::V3D QSampleFrame, double detectorDistance = 1.0); void setQLabFrame(Mantid::Kernel::V3D QLabFrame, - double detectorDistance = 1.0); + boost::optional detectorDistance = boost::optional()); void setWavelength(double wavelength); double getWavelength() const; @@ -134,7 +137,7 @@ class DLLExport Peak : public API::IPeak { private: - + bool findDetector(const Mantid::Kernel::V3D &beam); /// Shared pointer to the instrument (for calculating some values ) Geometry::Instrument_const_sptr m_inst; @@ -208,6 +211,9 @@ class DLLExport Peak : public API::IPeak { /// Peak shape Mantid::Geometry::PeakShape_const_sptr m_peakShape; + + /// Static logger + static Mantid::Kernel::Logger g_log; }; } // namespace Mantid diff --git a/Code/Mantid/Framework/DataObjects/src/Peak.cpp b/Code/Mantid/Framework/DataObjects/src/Peak.cpp index 846a66aa985c..f71934530f6f 100644 --- a/Code/Mantid/Framework/DataObjects/src/Peak.cpp +++ b/Code/Mantid/Framework/DataObjects/src/Peak.cpp @@ -484,11 +484,11 @@ void Peak::setQSampleFrame(Mantid::Kernel::V3D QSampleFrame, * This is in inelastic convention: momentum transfer of the LATTICE! * Also, q does have a 2pi factor = it is equal to 2pi/wavelength (in *Angstroms). - * @param detectorDistance :: distance between the sample and the detector. - * Used to give a valid TOF. Default 1.0 meters. + * @param detectorDistance :: distance between the sample and the detector. If this is provided. Then we do not + * ray trace to find the intersecing detector. */ void Peak::setQLabFrame(Mantid::Kernel::V3D QLabFrame, - double detectorDistance) { + boost::optional detectorDistance) { // Clear out the detector = we can't know them m_DetectorID = -1; m_det = IDetector_sptr(); @@ -535,11 +535,25 @@ void Peak::setQLabFrame(Mantid::Kernel::V3D QLabFrame, this->setWavelength(wl); V3D detectorDir = q * -1.0; - detectorDir[refFrame->pointingAlongBeam()] = one_over_wl - q.Z(); + detectorDir[refFrame->pointingAlongBeam()] = one_over_wl - qBeam; detectorDir.normalize(); // Use the given detector distance to find the detector position. - detPos = samplePos + detectorDir * detectorDistance; + if(detectorDistance.is_initialized()) + { + detPos = samplePos + detectorDir * detectorDistance.get(); + // We do not-update the detector as by manually setting the distance the client seems to know better. + } + else + { + // Find the detector + const bool found = findDetector(detectorDir); + if (!found) + { + // This is important, so we ought to log when this fails to happen. + g_log.debug("Could not find detector after setting qLab via setQLab with QLab : " + q.toString()); + } + } } /** After creating a peak using the Q in the lab frame, @@ -552,12 +566,22 @@ void Peak::setQLabFrame(Mantid::Kernel::V3D QLabFrame, * @return true if the detector ID was found. */ bool Peak::findDetector() { - bool found = false; + // Scattered beam direction V3D oldDetPos = detPos; V3D beam = detPos - samplePos; beam.normalize(); + return findDetector(beam); +} + +/** + * @brief Peak::findDetector : Find the detector along the beam location. sets the detector, and detector position if found + * @param beam : detector direction from the sample as V3D + * @return True if a detector has been found + */ +bool Peak::findDetector(const Mantid::Kernel::V3D &beam) { + bool found = false; // Create a ray tracer InstrumentRayTracer tracker(m_inst); tracker.traceFromSample(beam); @@ -904,5 +928,7 @@ Mantid::Kernel::V3D Peak::getDetectorPosition() const { return getDetector()->getPos(); } +Mantid::Kernel::Logger Peak::g_log("PeakLogger"); + } // namespace Mantid } // namespace DataObjects diff --git a/Code/Mantid/Framework/DataObjects/test/PeakTest.h b/Code/Mantid/Framework/DataObjects/test/PeakTest.h index 3e2e5fa05aee..ab61f6e678d8 100644 --- a/Code/Mantid/Framework/DataObjects/test/PeakTest.h +++ b/Code/Mantid/Framework/DataObjects/test/PeakTest.h @@ -329,7 +329,7 @@ class PeakTest : public CxxTest::TestSuite const double l1 = beam1.norm(); const double l2 = beam2.norm(); const double scatteringAngle2 = beam2.angle(beam1); - const V3D qLabDir = beam1 - beam2; + const V3D qLabDir = (beam1/l1) - (beam2/l2); // Derive the wavelength std::vector x; @@ -427,7 +427,7 @@ class PeakTest : public CxxTest::TestSuite const double wavelength = 2; Peak p(inst, detectorId, wavelength); TSM_ASSERT_THROWS_NOTHING("Nothing wrong here, detector is valid", p.getDetectorPosition()); - p.setQLabFrame(V3D(1,1,1), 1); // This sets the detector pointer to null and detector id to -1; + p.setQLabFrame(V3D(1,1,1), 1.0); // This sets the detector pointer to null and detector id to -1; TSM_ASSERT_THROWS("Detector is not valid", p.getDetectorPosition(), Mantid::Kernel::Exception::NullPointerException&); } diff --git a/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp b/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp index 5434f0c11c1b..0d694bc98c49 100644 --- a/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp +++ b/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp @@ -582,18 +582,21 @@ Instrument_sptr createMinimalInstrument(const V3D& sourcePos, const V3D& sampleP // A source ObjComponent *source = new ObjComponent("source"); source->setPos(sourcePos); + source->setShape(createSphere(0.01 /*1cm*/, V3D(0,0,0), "1")); instrument->add(source); instrument->markAsSource(source); // A sample ObjComponent *sample = new ObjComponent("some-surface-holder"); - source->setPos(samplePos); + sample->setPos(samplePos); + sample->setShape(createSphere(0.01 /*1cm*/, V3D(0,0,0), "1")); instrument->add(sample); instrument->markAsSamplePos(sample); // A detector Detector *det = new Detector("point-detector", 1 /*detector id*/, NULL); det->setPos(detectorPos); + det->setShape(createSphere(0.01 /*1cm*/, V3D(0,0,0), "1")); instrument->add(det); instrument->markAsDetector(det); From 9e49fff7ccf91994f80683c3072aef65c99367e9 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Wed, 11 Feb 2015 15:55:25 +0000 Subject: [PATCH 064/414] Support setting X Squared axis Refs #11036 --- .../inc/MantidQtMantidWidgets/PreviewPlot.h | 13 ++- .../MantidWidgets/src/PreviewPlot.cpp | 107 ++++++++++++++---- 2 files changed, 93 insertions(+), 27 deletions(-) diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h index f66860380d9e..aea0178bcc51 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -68,13 +68,13 @@ namespace MantidWidgets void setAxisRange(QPair range, int axisID = QwtPlot::xBottom); - QPair getCurveRange(const Mantid::API::MatrixWorkspace_const_sptr ws); + QPair getCurveRange(const Mantid::API::MatrixWorkspace_sptr ws); QPair getCurveRange(const QString & wsName); - void addSpectrum(const QString & curveName, const Mantid::API::MatrixWorkspace_const_sptr ws, const size_t specIndex = 0, const QColor & curveColour = QColor()); + void addSpectrum(const QString & curveName, const Mantid::API::MatrixWorkspace_sptr ws, const size_t specIndex = 0, const QColor & curveColour = QColor()); void addSpectrum(const QString & curveName, const QString & wsName, const size_t specIndex = 0, const QColor & curveColour = QColor()); - void removeSpectrum(const Mantid::API::MatrixWorkspace_const_sptr ws); + void removeSpectrum(const Mantid::API::MatrixWorkspace_sptr ws); void removeSpectrum(const QString & wsName); signals: @@ -89,6 +89,7 @@ namespace MantidWidgets void resizeX(); void clear(); void replot(); + void hardReplot(); private: /// Holds information about a plot curve @@ -106,11 +107,13 @@ namespace MantidWidgets void handleRemoveEvent(Mantid::API::WorkspacePreDeleteNotification_ptr pNf); void handleReplaceEvent(Mantid::API::WorkspaceAfterReplaceNotification_ptr pNf); - QwtPlotCurve * addCurve(const Mantid::API::MatrixWorkspace_const_sptr ws, const size_t specIndex, const QColor & curveColour); + QwtPlotCurve * addCurve(Mantid::API::MatrixWorkspace_sptr ws, const size_t specIndex, const QColor & curveColour); void removeCurve(QwtPlotCurve *curve); QList addOptionsToMenus(QString menuName, QActionGroup *group, QStringList items, QString defaultItem); + QString getAxisType(int axisID); + private slots: void showContextMenu(QPoint position); void handleViewToolSelect(); @@ -129,7 +132,7 @@ namespace MantidWidgets QwtPlot *m_plot; /// Map of curve key to plot info - QMap m_curves; + QMap m_curves; /// Plot manipulation tools QwtPlotMagnifier *m_magnifyTool; diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index e6d62e29951a..21ab5bd9242e 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -4,6 +4,7 @@ #include "MantidQtMantidWidgets/PreviewPlot.h" #include "MantidAPI/AnalysisDataService.h" +#include "MantidAPI/AlgorithmManager.h" #include "MantidQtAPI/QwtWorkspaceSpectrumData.h" #include @@ -191,7 +192,7 @@ void PreviewPlot::setAxisRange(QPair range, int axisID) * * @param ws Pointer to workspace */ -QPair PreviewPlot::getCurveRange(const Mantid::API::MatrixWorkspace_const_sptr ws) +QPair PreviewPlot::getCurveRange(const Mantid::API::MatrixWorkspace_sptr ws) { if(!m_curves.contains(ws)) throw std::runtime_error("Workspace not on preview plot."); @@ -217,7 +218,7 @@ QPair PreviewPlot::getCurveRange(const QString & wsName) { // Try to get a pointer from the name std::string wsNameStr = wsName.toStdString(); - auto ws = AnalysisDataService::Instance().retrieveWS(wsName.toStdString()); + auto ws = AnalysisDataService::Instance().retrieveWS(wsName.toStdString()); if(!ws) throw std::runtime_error(wsNameStr + " is not a MatrixWorkspace, not supported by PreviewPlot."); @@ -234,7 +235,7 @@ QPair PreviewPlot::getCurveRange(const QString & wsName) * @param specIndex Spectrum index to plot * @param curveColour Colour of curve to plot */ -void PreviewPlot::addSpectrum(const QString & curveName, const MatrixWorkspace_const_sptr ws, +void PreviewPlot::addSpectrum(const QString & curveName, const MatrixWorkspace_sptr ws, const size_t specIndex, const QColor & curveColour) { // Create the curve @@ -271,7 +272,7 @@ void PreviewPlot::addSpectrum(const QString & curveName, const QString & wsName, { // Try to get a pointer from the name std::string wsNameStr = wsName.toStdString(); - auto ws = AnalysisDataService::Instance().retrieveWS(wsName.toStdString()); + auto ws = AnalysisDataService::Instance().retrieveWS(wsName.toStdString()); if(!ws) throw std::runtime_error(wsNameStr + " is not a MatrixWorkspace, not supported by PreviewPlot."); @@ -285,7 +286,7 @@ void PreviewPlot::addSpectrum(const QString & curveName, const QString & wsName, * * @param ws Pointer to workspace */ -void PreviewPlot::removeSpectrum(const MatrixWorkspace_const_sptr ws) +void PreviewPlot::removeSpectrum(const MatrixWorkspace_sptr ws) { // Remove the curve object and legend label if(m_curves.contains(ws)) @@ -313,7 +314,7 @@ void PreviewPlot::removeSpectrum(const QString & wsName) { // Try to get a pointer from the name std::string wsNameStr = wsName.toStdString(); - auto ws = AnalysisDataService::Instance().retrieveWS(wsNameStr); + auto ws = AnalysisDataService::Instance().retrieveWS(wsNameStr); if(!ws) throw std::runtime_error(wsNameStr + " is not a MatrixWorkspace, not supported by PreviewPlot."); @@ -433,6 +434,20 @@ void PreviewPlot::replot() } +/** + * Removes all curves and re-adds them. + */ +void PreviewPlot::hardReplot() +{ + QList keys = m_curves.keys(); + + for(auto it = keys.begin(); it != keys.end(); ++it) + m_curves[*it].curve = addCurve(*it, m_curves[*it].wsIndex, m_curves[*it].colour); + + replot(); +} + + /** * Handle a workspace being deleted from ADS. * @@ -485,7 +500,7 @@ void PreviewPlot::handleReplaceEvent(WorkspaceAfterReplaceNotification_ptr pNf) * @param curveColour Colour of curve * @return Pointer to new curve */ -QwtPlotCurve * PreviewPlot::addCurve(const MatrixWorkspace_const_sptr ws, const size_t specIndex, +QwtPlotCurve * PreviewPlot::addCurve(MatrixWorkspace_sptr ws, const size_t specIndex, const QColor & curveColour) { // Check the spectrum index is in range @@ -496,14 +511,28 @@ QwtPlotCurve * PreviewPlot::addCurve(const MatrixWorkspace_const_sptr ws, const if(ws->readX(0).size() < 2) throw std::runtime_error("X axis is too small to generate a histogram plot."); - // Create the plot data - const bool logScale(false), distribution(false); - QwtWorkspaceSpectrumData wsData(*ws, static_cast(specIndex), logScale, distribution); - // Remove any existing curves if(m_curves.contains(ws)) removeCurve(m_curves[ws].curve); + // Convert X axis to squared if needed + if(getAxisType(QwtPlot::xBottom) == "Squared") + { + Mantid::API::IAlgorithm_sptr convertXAlg = Mantid::API::AlgorithmManager::Instance().create("ConvertAxisByFormula"); + convertXAlg->initialize(); + convertXAlg->setChild(true); + convertXAlg->setLogging(false); + convertXAlg->setProperty("InputWorkspace", ws); + convertXAlg->setProperty("OutputWorkspace", "__PreviewPlot_Anon"); + convertXAlg->setProperty("Axis", "X"); + convertXAlg->setProperty("Formula", "x^2"); + convertXAlg->execute(); + ws = convertXAlg->getProperty("OutputWorkspace"); + } + + // Create the plot data + QwtWorkspaceSpectrumData wsData(*ws, static_cast(specIndex), false, false); + // Create the new curve QwtPlotCurve *curve = new QwtPlotCurve(); curve->setData(wsData); @@ -567,6 +596,31 @@ QList PreviewPlot::addOptionsToMenus(QString menuName, QActionGroup * } +/** + * Returns the type of axis scale specified for a giev axis. + * + * @param axisID ID of axis + * @return Axis type as string + */ +QString PreviewPlot::getAxisType(int axisID) +{ + QString axisType("Linear"); + QAction * selectedAxisType = NULL; + + if(axisID == QwtPlot::xBottom) + selectedAxisType = m_xAxisTypeGroup->checkedAction(); + else if (axisID == QwtPlot::yLeft) + selectedAxisType = m_yAxisTypeGroup->checkedAction(); + else + return QString(); + + if(selectedAxisType) + axisType = selectedAxisType->text(); + + return axisType; +} + + /** * Handles displaying the context menu when a user right clicks on the plot. * @@ -610,35 +664,44 @@ void PreviewPlot::handleViewToolSelect() */ void PreviewPlot::handleAxisTypeSelect() { - QString xAxisType("Linear"); - QString yAxisType("Linear"); - - QAction *selectedXAxisType = m_xAxisTypeGroup->checkedAction(); - if(selectedXAxisType) - xAxisType = selectedXAxisType->text(); - - QAction *selectedYAxisType = m_yAxisTypeGroup->checkedAction(); - if(selectedYAxisType) - yAxisType = selectedYAxisType->text(); + // Determine the type of engine to use for each axis + QString xAxisType = getAxisType(QwtPlot::xBottom); + QString yAxisType = getAxisType(QwtPlot::yLeft); QwtScaleEngine *xEngine = NULL; QwtScaleEngine *yEngine = NULL; + // Get the X axis engine if(xAxisType == "Linear") + { xEngine = new QwtLinearScaleEngine(); + } else if(xAxisType == "Logarithmic") + { xEngine = new QwtLog10ScaleEngine(); + } + else if(xAxisType == "Squared") + { + xEngine = new QwtLinearScaleEngine(); + } + // Get the Y axis engine if(yAxisType == "Linear") + { yEngine = new QwtLinearScaleEngine(); + } else if(yAxisType == "Logarithmic") + { yEngine = new QwtLog10ScaleEngine(); + } + // Set the axis scale engines if(xEngine) m_plot->setAxisScaleEngine(QwtPlot::xBottom, xEngine); if(yEngine) m_plot->setAxisScaleEngine(QwtPlot::yLeft, yEngine); - m_plot->replot(); + // Update the plot + hardReplot(); } From 2c47c9efb330b451e4ce7534fec9a400fec2e012 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Wed, 11 Feb 2015 16:03:45 +0000 Subject: [PATCH 065/414] Update buildscripts for new setup Changes: - any references to develop have been removed - pull_request builds will also build packages Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript | 70 +++++++++++++++------------ 1 file changed, 40 insertions(+), 30 deletions(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript b/Code/Mantid/Build/Jenkins/buildscript index 61417dc99d96..693cdaf874ae 100755 --- a/Code/Mantid/Build/Jenkins/buildscript +++ b/Code/Mantid/Build/Jenkins/buildscript @@ -4,9 +4,10 @@ # # Notes: # -# WORKSPACE, JOB_NAME & NODE_LABEL are environment variables that are set by -# Jenkins. The last one corresponds to any labels set on a slave. -# BUILD_THREADS & PARAVIEW_DIR should be set in the configuration of each slave. +# WORKSPACE, JOB_NAME, NODE_LABEL GIT_COMMIT are environment variables that +# are set by Jenkins. The last one corresponds to any labels set on a slave. +# BUILD_THREADS & PARAVIEW_DIR should be set in the configuration of each +# slave. ############################################################################### ############################################################################### @@ -15,6 +16,9 @@ cmake --version echo "SHA1=${sha1}" +############################################################################### +# Setup clang +############################################################################### if [[ ${JOB_NAME} == *clang* ]]; then # Assuming we are using the clang compiler echo "Using clang/llvm compiler." @@ -61,22 +65,37 @@ if [ -z "$MANTID_DATA_STORE" ]; then fi ############################################################################### -# Check whether this is a clean build (must have 'clean' in the job name) +# Check job requirements from the name ############################################################################### if [[ ${JOB_NAME} == *clean* ]]; then CLEANBUILD=true + BUILDPKG=true +fi +if [[ ${JOB_NAME} == *pull_requests* ]]; then + BUILDPKG=true +fi + +############################################################################### +# Clean build directory if required +############################################################################### +if [[ "$CLEANBUILD" == true ]]; then # Removing the build directory entirely guarantees a completely clean build rm -rf $WORKSPACE/build +fi - # Set some variables relating to the linux packages created from clean builds +############################################################################### +# Packaging options +############################################################################### +if [[ "$BUILDPKG" == true ]]; then + # Set some variables relating to the linux packages if [[ $(uname) != 'Darwin' ]]; then # Use different suffix for linux builds - if [[ ${JOB_NAME} == *master* ]]; then + if [[ ${JOB_NAME} == *release* ]]; then + PACKAGINGVARS="-DENVVARS_ON_INSTALL=True -DCPACK_SET_DESTDIR=ON -DPACKAGE_DOCS=ON" + elif [[ ${JOB_NAME} == *master* ]]; then PACKAGINGVARS="-DENVVARS_ON_INSTALL=False -DCMAKE_INSTALL_PREFIX=/opt/mantidnightly -DCPACK_PACKAGE_SUFFIX=nightly -DCPACK_SET_DESTDIR=OFF -DPACKAGE_DOCS=ON" - elif [[ ${JOB_NAME} == *develop* ]]; then + else PACKAGINGVARS="-DENVVARS_ON_INSTALL=False -DCMAKE_INSTALL_PREFIX=/opt/mantidunstable -DCPACK_PACKAGE_SUFFIX=unstable -DCPACK_SET_DESTDIR=OFF -DPACKAGE_DOCS=ON" - elif [[ ${JOB_NAME} == *release* ]]; then - PACKAGINGVARS="-DENVVARS_ON_INSTALL=True -DCPACK_SET_DESTDIR=ON -DPACKAGE_DOCS=ON" fi else # Mac packaging @@ -100,6 +119,12 @@ fi [ -d $WORKSPACE/build ] || mkdir $WORKSPACE/build cd $WORKSPACE/build +############################################################################### +# Clean up any artifacts from last build so that if it fails +# they don't get archived again +############################################################################### +rm -f *.dmg *.rpm *.deb *.tar.gz + ############################################################################### ## Check the required build configuration ############################################################################### @@ -148,38 +173,23 @@ rm -f ~/.mantid/Mantid.user.properties $SCL_ON_RHEL6 "ctest -j$BUILD_THREADS --schedule-random --output-on-failure" ############################################################################### -# Documentation -# Build Qt help on all platforms for a clean build so that it can be packaged +# Create the install kit if required. This includes building the Qt help +# documentation ############################################################################### -if [[ "$CLEANBUILD" == true ]]; then +if [[ "$BUILDPKG" == true ]]; then # Workaround so that the target can find the properties file # CMake doesn't easily allow environment variables on custom targets if [[ $(uname) == 'Darwin' ]]; then export MANTIDPATH=$PWD/bin fi $SCL_ON_RHEL6 "cmake --build . --target docs-qthelp" -fi - -############################################################################### -# Create the install kit if this is a clean or non-Mac build -############################################################################### -rm -f *.dmg *.rpm *.deb *.tar.gz -# Always build a package on linux -if [[ $(uname) != 'Darwin' ]]; then $SCL_ON_RHEL6 "cpack" -fi - -if [[ "$CLEANBUILD" == true ]]; then - # On the Mac, only create a package for clean builds - if [[ $(uname) == 'Darwin' ]]; then - $SCL_ON_RHEL6 "cpack" - fi - # We could build the source tarball anywhere, but we choose to do it on RHEL6 - # We also parcel up the documentation into a tar file that is easier to move around + # Source tarball on clean build (arbitrarily choose rhel6) + # Also, parcel up the documentation into a tar file that is easier to move around # and labelled by the commit id it was built with. This assumes the Jenkins git plugin # has set the GIT_COMMIT environment variable - if [[ "$ON_RHEL6" == true ]]; then + if [[ "$CLEANBUILD" == true && "$ON_RHEL6" == true ]]; then $SCL_ON_RHEL6 "cmake --build . --target docs-html" tar -cjf mantiddocs-g${GIT_COMMIT:0:7}.tar.bz2 --exclude='*.buildinfo' --exclude="MantidProject.q*" docs/html # The ..._PREFIX argument avoids opt/Mantid directories at the top of the tree From 1c087677e65118c3e1a397a86396dcb746a234e1 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Wed, 11 Feb 2015 16:50:26 +0000 Subject: [PATCH 066/414] Move preview plot layout to UI file Seems to fix issues with legend labels moving when window is resized. Refs #11036 --- .../MantidQt/MantidWidgets/CMakeLists.txt | 1 + .../inc/MantidQtMantidWidgets/PreviewPlot.h | 8 +-- .../inc/MantidQtMantidWidgets/PreviewPlot.ui | 34 +++++++++++ .../MantidWidgets/src/PreviewPlot.cpp | 61 ++++++++----------- .../MantidWidgets/src/RangeSelector.cpp | 4 +- 5 files changed, 66 insertions(+), 42 deletions(-) create mode 100644 Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.ui diff --git a/Code/Mantid/MantidQt/MantidWidgets/CMakeLists.txt b/Code/Mantid/MantidQt/MantidWidgets/CMakeLists.txt index db06cce1eb4b..22b7da812b64 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/CMakeLists.txt +++ b/Code/Mantid/MantidQt/MantidWidgets/CMakeLists.txt @@ -119,6 +119,7 @@ set ( UI_FILES inc/MantidQtMantidWidgets/SequentialFitDialog.ui inc/MantidQtMantidWidgets/SlicingAlgorithmDialog.ui inc/MantidQtMantidWidgets/UserFunctionDialog.ui + inc/MantidQtMantidWidgets/PreviewPlot.ui inc/MantidQtMantidWidgets/pqHelpWindow.ui ) diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h index aea0178bcc51..9b4187e4aa68 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -1,6 +1,8 @@ #ifndef MANTIDQTMANTIDWIDGETS_PREVIEWPLOT_H_ #define MANTIDQTMANTIDWIDGETS_PREVIEWPLOT_H_ +#include "ui_PreviewPlot.h" + #include "WidgetDllOption.h" #include "MantidQtAPI/MantidWidget.h" @@ -120,6 +122,8 @@ namespace MantidWidgets void handleAxisTypeSelect(); private: + Ui::PreviewPlot m_uiForm; + /// Poco Observers for ADS Notifications Poco::NObserver m_removeObserver; Poco::NObserver m_replaceObserver; @@ -129,7 +133,6 @@ namespace MantidWidgets /// The plot its self friend class RangeSelector; - QwtPlot *m_plot; /// Map of curve key to plot info QMap m_curves; @@ -148,9 +151,6 @@ namespace MantidWidgets /// Menu action for showing/hiding plot legend QAction *m_showLegendAction; - /// Layout for plot legend - QHBoxLayout *m_legendLayout; - }; } diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.ui b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.ui new file mode 100644 index 000000000000..26b0ff597164 --- /dev/null +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.ui @@ -0,0 +1,34 @@ + + + PreviewPlot + + + + 0 + 0 + 300 + 259 + + + + Form + + + + + + + + + + + + + QwtPlot + QFrame +
qwt_plot.h
+
+
+ + +
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index 21ab5bd9242e..e49c4ed88bdb 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -31,44 +31,35 @@ namespace PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent), m_removeObserver(*this, &PreviewPlot::handleRemoveEvent), m_replaceObserver(*this, &PreviewPlot::handleReplaceEvent), - m_init(init), m_plot(new QwtPlot(this)), m_curves(), + m_init(init), m_curves(), m_magnifyTool(NULL), m_panTool(NULL), m_zoomTool(NULL), - m_contextMenu(new QMenu(this)), m_showLegendAction(NULL), m_legendLayout(NULL) + m_contextMenu(new QMenu(this)), m_showLegendAction(NULL) { + m_uiForm.setupUi(this); + m_uiForm.loLegend->addStretch(); + if(init) { AnalysisDataServiceImpl& ads = AnalysisDataService::Instance(); ads.notificationCenter.addObserver(m_removeObserver); ads.notificationCenter.addObserver(m_replaceObserver); - - QBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->setSizeConstraint(QLayout::SetNoConstraint); - - m_plot->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - mainLayout->addWidget(m_plot); - - m_legendLayout = new QHBoxLayout(mainLayout); - m_legendLayout->addStretch(); - mainLayout->addItem(m_legendLayout); - - this->setLayout(mainLayout); } // Setup plot manipulation tools m_zoomTool = new QwtPlotZoomer(QwtPlot::xBottom, QwtPlot::yLeft, - QwtPicker::DragSelection | QwtPicker::CornerToCorner, QwtPicker::AlwaysOff, m_plot->canvas()); + QwtPicker::DragSelection | QwtPicker::CornerToCorner, QwtPicker::AlwaysOff, m_uiForm.plot->canvas()); m_zoomTool->setEnabled(false); - m_panTool = new QwtPlotPanner(m_plot->canvas()); + m_panTool = new QwtPlotPanner(m_uiForm.plot->canvas()); m_panTool->setEnabled(false); - m_magnifyTool = new QwtPlotMagnifier(m_plot->canvas()); + m_magnifyTool = new QwtPlotMagnifier(m_uiForm.plot->canvas()); m_magnifyTool->setMouseButton(Qt::NoButton); m_magnifyTool->setEnabled(false); // Handle showing the context menu - m_plot->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_plot, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint))); + m_uiForm.plot->setContextMenuPolicy(Qt::CustomContextMenu); + connect(m_uiForm.plot, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint))); // Create the plot tool list for context menu m_plotToolGroup = new QActionGroup(m_contextMenu); @@ -141,10 +132,7 @@ PreviewPlot::~PreviewPlot() */ QColor PreviewPlot::canvasColour() { - if(m_plot) - return m_plot->canvasBackground(); - - return QColor(); + return m_uiForm.plot->canvasBackground(); } @@ -155,8 +143,7 @@ QColor PreviewPlot::canvasColour() */ void PreviewPlot::setCanvasColour(const QColor & colour) { - if(m_plot) - m_plot->setCanvasBackground(QBrush(colour)); + m_uiForm.plot->setCanvasBackground(QBrush(colour)); } @@ -182,7 +169,7 @@ void PreviewPlot::setAxisRange(QPair range, int axisID) if(range.first > range.second) throw std::runtime_error("Supplied range is invalid."); - m_plot->setAxisScale(axisID, range.first, range.second); + m_uiForm.plot->setAxisScale(axisID, range.first, range.second); replot(); } @@ -247,7 +234,9 @@ void PreviewPlot::addSpectrum(const QString & curveName, const MatrixWorkspace_s palette.setColor(label->foregroundRole(), curveColour); label->setPalette(palette); label->setVisible(legendIsShown()); - m_legendLayout->addWidget(label); + label->setWordWrap(true); + label->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); + m_uiForm.loLegend->addWidget(label); m_curves[ws].curve = curve; m_curves[ws].label = label; @@ -292,7 +281,7 @@ void PreviewPlot::removeSpectrum(const MatrixWorkspace_sptr ws) if(m_curves.contains(ws)) { removeCurve(m_curves[ws].curve); - m_legendLayout->removeWidget(m_curves[ws].label); + m_uiForm.loLegend->removeWidget(m_curves[ws].label); delete m_curves[ws].label; } @@ -375,8 +364,8 @@ void PreviewPlot::toggleZoomTool(bool enabled) void PreviewPlot::resetView() { // Auto scale the axis - m_plot->setAxisAutoScale(QwtPlot::xBottom); - m_plot->setAxisAutoScale(QwtPlot::yLeft); + m_uiForm.plot->setAxisAutoScale(QwtPlot::xBottom); + m_uiForm.plot->setAxisAutoScale(QwtPlot::yLeft); // Set this as the default zoom level m_zoomTool->setZoomBase(true); @@ -415,7 +404,7 @@ void PreviewPlot::clear() for(auto it = m_curves.begin(); it != m_curves.end(); ++it) { removeCurve(it.value().curve); - m_legendLayout->removeWidget(it.value().label); + m_uiForm.loLegend->removeWidget(it.value().label); delete it.value().label; } @@ -430,7 +419,7 @@ void PreviewPlot::clear() */ void PreviewPlot::replot() { - m_plot->replot(); + m_uiForm.plot->replot(); } @@ -537,7 +526,7 @@ QwtPlotCurve * PreviewPlot::addCurve(MatrixWorkspace_sptr ws, const size_t specI QwtPlotCurve *curve = new QwtPlotCurve(); curve->setData(wsData); curve->setPen(curveColour); - curve->attach(m_plot); + curve->attach(m_uiForm.plot); return curve; } @@ -629,7 +618,7 @@ QString PreviewPlot::getAxisType(int axisID) void PreviewPlot::showContextMenu(QPoint position) { // Show the context menu - m_contextMenu->popup(m_plot->mapToGlobal(position)); + m_contextMenu->popup(m_uiForm.plot->mapToGlobal(position)); } @@ -697,10 +686,10 @@ void PreviewPlot::handleAxisTypeSelect() // Set the axis scale engines if(xEngine) - m_plot->setAxisScaleEngine(QwtPlot::xBottom, xEngine); + m_uiForm.plot->setAxisScaleEngine(QwtPlot::xBottom, xEngine); if(yEngine) - m_plot->setAxisScaleEngine(QwtPlot::yLeft, yEngine); + m_uiForm.plot->setAxisScaleEngine(QwtPlot::yLeft, yEngine); // Update the plot hardReplot(); diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/RangeSelector.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/RangeSelector.cpp index 07f087f3eecc..30334d6da2cb 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/RangeSelector.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/RangeSelector.cpp @@ -17,8 +17,8 @@ RangeSelector::RangeSelector(QwtPlot* plot, SelectType type, bool visible, bool } RangeSelector::RangeSelector(PreviewPlot* plot, SelectType type, bool visible, bool infoOnly) - : QwtPlotPicker(plot->m_plot->canvas()), m_type(type), m_min(0.0) ,m_max(0.0), m_lower(0.0), - m_higher(0.0), m_canvas(plot->m_plot->canvas()), m_plot(plot->m_plot), m_mrkMin(NULL), m_mrkMax(NULL), + : QwtPlotPicker(plot->m_uiForm.plot->canvas()), m_type(type), m_min(0.0) ,m_max(0.0), m_lower(0.0), + m_higher(0.0), m_canvas(plot->m_uiForm.plot->canvas()), m_plot(plot->m_uiForm.plot), m_mrkMin(NULL), m_mrkMax(NULL), m_minChanging(false), m_maxChanging(false), m_infoOnly(infoOnly), m_visible(visible), m_pen(NULL), m_movCursor() { From 043325d925888cd5a967e1050a4acfb1a890bd66 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Thu, 12 Feb 2015 09:39:30 +0000 Subject: [PATCH 067/414] Replace plots on MSD fit and corrections Allow removal of a curve by legend name Refs #11036 --- .../Indirect/ApplyCorr.h | 2 +- .../Indirect/ApplyCorr.ui | 48 ++++++++----------- .../Indirect/MSDFit.ui | 47 +++++++++--------- .../src/Indirect/ApplyCorr.cpp | 42 ++++++---------- .../CustomInterfaces/src/Indirect/MSDFit.cpp | 38 ++++++--------- .../inc/MantidQtMantidWidgets/PreviewPlot.h | 1 + .../MantidWidgets/src/PreviewPlot.cpp | 16 +++++++ 7 files changed, 90 insertions(+), 104 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyCorr.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyCorr.h index 6c1de920cc03..f7d9256f52b6 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyCorr.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyCorr.h @@ -36,7 +36,7 @@ namespace IDA Ui::ApplyCorr m_uiForm; /// Pointer to the result workspace (for plotting) - Mantid::API::MatrixWorkspace_sptr outputWs; + Mantid::API::MatrixWorkspace_sptr m_outputWs; }; } // namespace IDA diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyCorr.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyCorr.ui index a5646f2b65a1..0e8320365ada 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyCorr.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyCorr.ui @@ -202,37 +202,21 @@ - + + + + 255 + 255 + 255 + + + + true + + - - - - - Sample - - - - - - - color: rgb(255, 0, 0); - - - Can - - - - - - - color: rgb(0, 255, 0); - - - Corrected - - - + @@ -364,6 +348,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/MSDFit.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/MSDFit.ui index 942a71ebe321..e6c4c88ef9b1 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/MSDFit.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/MSDFit.ui @@ -6,8 +6,8 @@ 0 0 - 444 - 223 + 422 + 265
@@ -54,10 +54,21 @@ - + + + true + + + + 255 + 255 + 255 + + + - + @@ -78,23 +89,6 @@
- - - - Sample - - - - - - - color: rgb(255, 0, 0); - - - Fit - - -
@@ -218,11 +212,14 @@ + + true + Plot Result - true + false @@ -257,6 +254,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ApplyCorr.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ApplyCorr.cpp index fd36d64f8bd6..b70a1033fe98 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ApplyCorr.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ApplyCorr.cpp @@ -29,13 +29,6 @@ namespace IDA connect(m_uiForm.dsSample, SIGNAL(dataReady(const QString&)), this, SLOT(newData(const QString&))); connect(m_uiForm.spPreviewSpec, SIGNAL(valueChanged(int)), this, SLOT(plotPreview(int))); - // Create the plot - m_plots["ApplyCorrPlot"] = new QwtPlot(m_parentWidget); - m_plots["ApplyCorrPlot"]->setCanvasBackground(Qt::white); - m_plots["ApplyCorrPlot"]->setAxisFont(QwtPlot::xBottom, m_parentWidget->font()); - m_plots["ApplyCorrPlot"]->setAxisFont(QwtPlot::yLeft, m_parentWidget->font()); - m_uiForm.plotPreview->addWidget(m_plots["ApplyCorrPlot"]); - m_uiForm.spPreviewSpec->setMinimum(0); m_uiForm.spPreviewSpec->setMaximum(0); } @@ -47,14 +40,12 @@ namespace IDA */ void ApplyCorr::newData(const QString &dataName) { - removeCurve("CalcCurve"); - removeCurve("CanCurve"); - // removeCurve would usually need a replot() but this is done in plotMiniPlot() - - plotMiniPlot(dataName, 0, "ApplyCorrPlot", "ApplyCorrSampleCurve"); - - MatrixWorkspace_const_sptr sampleWs = AnalysisDataService::Instance().retrieveWS(dataName.toStdString()); + const MatrixWorkspace_sptr sampleWs = AnalysisDataService::Instance().retrieveWS(dataName.toStdString()); m_uiForm.spPreviewSpec->setMaximum(static_cast(sampleWs->getNumberHistograms()) - 1); + + // Plot the sample curve + m_uiForm.ppPreview->clear(); + m_uiForm.ppPreview->addSpectrum("Sample", sampleWs, 0, Qt::black); } void ApplyCorr::run() @@ -175,7 +166,7 @@ namespace IDA QString pyOutput = runPythonCode(pyInput).trimmed(); - outputWs = AnalysisDataService::Instance().retrieveWS(pyOutput.toStdString()); + m_outputWs = AnalysisDataService::Instance().retrieveWS(pyOutput.toStdString()); plotPreview(m_uiForm.spPreviewSpec->value()); // Set the result workspace for Python script export @@ -260,33 +251,28 @@ namespace IDA { bool useCan = m_uiForm.ckUseCan->isChecked(); + m_uiForm.ppPreview->clear(); + // Plot sample - QString sample = m_uiForm.dsSample->getCurrentDataName(); + const QString sample = m_uiForm.dsSample->getCurrentDataName(); if(AnalysisDataService::Instance().doesExist(sample.toStdString())) { - MatrixWorkspace_const_sptr sampleWs = AnalysisDataService::Instance().retrieveWS(sample.toStdString()); - plotMiniPlot(sampleWs, specIndex, "ApplyCorrPlot", "ApplyCorrSampleCurve"); + m_uiForm.ppPreview->addSpectrum("Sample", sample, specIndex, Qt::black); } // Plot result - if(outputWs) + if(m_outputWs) { - plotMiniPlot(outputWs, specIndex, "ApplyCorrPlot", "CalcCurve"); - m_curves["CalcCurve"]->setPen(QColor(Qt::green)); + m_uiForm.ppPreview->addSpectrum("Corrected", m_outputWs, specIndex, Qt::green); } // Plot can if(useCan) { QString container = m_uiForm.dsContainer->getCurrentDataName(); - MatrixWorkspace_const_sptr canWs = AnalysisDataService::Instance().retrieveWS(container.toStdString()); - plotMiniPlot(canWs, specIndex, "ApplyCorrPlot", "CanCurve"); - m_curves["CanCurve"]->setPen(QColor(Qt::red)); + const MatrixWorkspace_sptr canWs = AnalysisDataService::Instance().retrieveWS(container.toStdString()); + m_uiForm.ppPreview->addSpectrum("Can", canWs, specIndex, Qt::red); } - else - removeCurve("CanCurve"); - - replot("ApplyCorrPlot"); } } // namespace IDA diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/MSDFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/MSDFit.cpp index 364913ca92f8..1717520f353e 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/MSDFit.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/MSDFit.cpp @@ -44,15 +44,7 @@ namespace IDA m_msdTree->addProperty(m_properties["Start"]); m_msdTree->addProperty(m_properties["End"]); - m_plots["MSDPlot"] = new QwtPlot(m_parentWidget); - m_uiForm.plot->addWidget(m_plots["MSDPlot"]); - - // Cosmetics - m_plots["MSDPlot"]->setAxisFont(QwtPlot::xBottom, m_parentWidget->font()); - m_plots["MSDPlot"]->setAxisFont(QwtPlot::yLeft, m_parentWidget->font()); - m_plots["MSDPlot"]->setCanvasBackground(Qt::white); - - m_rangeSelectors["MSDRange"] = new MantidWidgets::RangeSelector(m_plots["MSDPlot"]); + m_rangeSelectors["MSDRange"] = new MantidWidgets::RangeSelector(m_uiForm.ppPlot); connect(m_rangeSelectors["MSDRange"], SIGNAL(minValueChanged(double)), this, SLOT(minChanged(double))); connect(m_rangeSelectors["MSDRange"], SIGNAL(maxValueChanged(double)), this, SLOT(maxChanged(double))); @@ -149,13 +141,15 @@ namespace IDA { if(Mantid::API::AnalysisDataService::Instance().doesExist(wsName.toStdString())) { - //read the fit from the workspace + // Get the workspace auto groupWs = Mantid::API::AnalysisDataService::Instance().retrieveWS(wsName.toStdString()); auto ws = boost::dynamic_pointer_cast(groupWs->getItem(0)); - plotMiniPlot(ws, 1, "MSDPlot", "MSDFitCurve"); - QPen fitPen(Qt::red, Qt::SolidLine); - m_curves["MSDFitCurve"]->setPen(fitPen); - replot("MSDPlot"); + + // Remove the old fit + m_uiForm.ppPlot->removeSpectrumByCurveName("Fit"); + + // Plot the new fit + m_uiForm.ppPlot->addSpectrum("Fit", ws, 1, Qt::red); } } @@ -187,6 +181,8 @@ namespace IDA void MSDFit::plotInput() { + m_uiForm.ppPlot->clear(); + QString wsname = m_uiForm.dsSampleInput->getCurrentDataName(); if(!AnalysisDataService::Instance().doesExist(wsname.toStdString())) @@ -195,18 +191,15 @@ namespace IDA return; } - auto ws = AnalysisDataService::Instance().retrieveWS(wsname.toStdString()); + auto ws = AnalysisDataService::Instance().retrieveWS(wsname.toStdString()); int wsIndex = m_uiForm.spPlotSpectrum->value(); - plotMiniPlot(ws, wsIndex, "MSDPlot", "MSDDataCurve"); + m_uiForm.ppPlot->addSpectrum("Sample", ws, wsIndex); try { - const std::pair range = getCurveRange("MSDDataCurve"); + QPair range = m_uiForm.ppPlot->getCurveRange(ws); m_rangeSelectors["MSDRange"]->setRange(range.first, range.second); - - // Replot - replot("MSDPlot"); } catch(std::invalid_argument & exc) { @@ -214,10 +207,6 @@ namespace IDA } m_currentWsName = wsname; - - // Remove the old fit curve - removeCurve("MSDFitCurve"); - replot("MSDPlot"); } /** @@ -259,6 +248,7 @@ namespace IDA if ( prop == m_properties["Start"] ) m_rangeSelectors["MSDRange"]->setMinimum(val); else if ( prop == m_properties["End"] ) m_rangeSelectors["MSDRange"]->setMaximum(val); } + } // namespace IDA } // namespace CustomInterfaces } // namespace MantidQt diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h index 9b4187e4aa68..9bb38e7e0e19 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -78,6 +78,7 @@ namespace MantidWidgets void removeSpectrum(const Mantid::API::MatrixWorkspace_sptr ws); void removeSpectrum(const QString & wsName); + void removeSpectrumByCurveName(const QString & name); signals: /// Signals that the plot should be refreshed diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index e49c4ed88bdb..25a1ebee34bc 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -312,6 +312,22 @@ void PreviewPlot::removeSpectrum(const QString & wsName) } +/** + * Removes a curve from the plot given its name (as displayed in the legend). + * + * @param name Name of curve + */ +void PreviewPlot::removeSpectrumByCurveName(const QString & name) +{ + for(auto it = m_curves.begin(); it != m_curves.end(); ++it) + { + QLabel *label = it.value().label; + if(label && label->text() == name) + removeSpectrum(it.key()); + } +} + + /** * Shows or hides the plot legend. * From e1f908eecd73c4a9589ffaff8e0ecebe5877fa5e Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Thu, 12 Feb 2015 10:00:50 +0000 Subject: [PATCH 068/414] Added new MSD and Fury plots Refs #11036 --- .../Indirect/Elwin.ui | 45 ++++++++++--------- .../MantidQtCustomInterfaces/Indirect/Fury.ui | 19 +++++++- .../CustomInterfaces/src/Indirect/Elwin.cpp | 18 +++----- .../CustomInterfaces/src/Indirect/Fury.cpp | 25 ++++------- 4 files changed, 55 insertions(+), 52 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Elwin.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Elwin.ui index 147dea816d51..ab156ca3e5bf 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Elwin.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Elwin.ui @@ -6,8 +6,8 @@ 0 0 - 444 - 251 + 506 + 355 @@ -49,7 +49,7 @@ - + @@ -91,43 +91,38 @@ - + + + + 255 + 255 + 255 + + +
- - - - - Qt::Horizontal - - - - 40 - 20 - - - - - + + SE log name: - + - - + + Qt::Horizontal @@ -185,6 +180,12 @@ QWidget
MantidQtMantidWidgets/MWRunFiles.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Fury.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Fury.ui index a9f91fc7f6fc..5b80c208e983 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Fury.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Fury.ui @@ -113,7 +113,18 @@
- + + + + 255 + 255 + 255 + + + + true + +
@@ -187,6 +198,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp index d1d59ab7e27a..6dc0df914304 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp @@ -63,26 +63,18 @@ namespace IDA m_elwTree->addProperty(m_properties["BackgroundRange"]); m_elwTree->addProperty(m_properties["Normalise"]); - // Create Slice Plot Widget for Range Selection - m_plots["ElwinPlot"] = new QwtPlot(m_parentWidget); - m_plots["ElwinPlot"]->setAxisFont(QwtPlot::xBottom, m_parentWidget->font()); - m_plots["ElwinPlot"]->setAxisFont(QwtPlot::yLeft, m_parentWidget->font()); - m_uiForm.plot->addWidget(m_plots["ElwinPlot"]); - m_plots["ElwinPlot"]->setCanvasBackground(Qt::white); // We always want one range selector... the second one can be controlled from // within the elwinTwoRanges(bool state) function - m_rangeSelectors["ElwinIntegrationRange"] = new MantidWidgets::RangeSelector(m_plots["ElwinPlot"]); + m_rangeSelectors["ElwinIntegrationRange"] = new MantidWidgets::RangeSelector(m_uiForm.ppPlot); connect(m_rangeSelectors["ElwinIntegrationRange"], SIGNAL(minValueChanged(double)), this, SLOT(minChanged(double))); connect(m_rangeSelectors["ElwinIntegrationRange"], SIGNAL(maxValueChanged(double)), this, SLOT(maxChanged(double))); // create the second range - m_rangeSelectors["ElwinBackgroundRange"] = new MantidWidgets::RangeSelector(m_plots["ElwinPlot"]); + m_rangeSelectors["ElwinBackgroundRange"] = new MantidWidgets::RangeSelector(m_uiForm.ppPlot); m_rangeSelectors["ElwinBackgroundRange"]->setColour(Qt::darkGreen); // dark green for background connect(m_rangeSelectors["ElwinIntegrationRange"], SIGNAL(rangeChanged(double, double)), m_rangeSelectors["ElwinBackgroundRange"], SLOT(setRange(double, double))); connect(m_rangeSelectors["ElwinBackgroundRange"], SIGNAL(minValueChanged(double)), this, SLOT(minChanged(double))); connect(m_rangeSelectors["ElwinBackgroundRange"], SIGNAL(maxValueChanged(double)), this, SLOT(maxChanged(double))); m_rangeSelectors["ElwinBackgroundRange"]->setRange(m_rangeSelectors["ElwinIntegrationRange"]->getRange()); - // Refresh the plot window - replot("ElwinPlot"); connect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(updateRS(QtProperty*, double))); connect(m_blnManager, SIGNAL(valueChanged(QtProperty*, bool)), this, SLOT(twoRanges(QtProperty*, bool))); @@ -362,13 +354,13 @@ namespace IDA setDefaultResolution(ws); setDefaultSampleLog(ws); - plotMiniPlot(ws, specNo, "ElwinPlot", "ElwinDataCurve"); + m_uiForm.ppPlot->clear(); + m_uiForm.ppPlot->addSpectrum("Sample", ws, specNo); try { - const std::pair range = getCurveRange("ElwinDataCurve"); + QPair range = m_uiForm.ppPlot->getCurveRange(ws); m_rangeSelectors["ElwinIntegrationRange"]->setRange(range.first, range.second); - replot("ElwinPlot"); } catch(std::invalid_argument & exc) { diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Fury.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Fury.cpp index 21377a1f0488..59fc186d63b8 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Fury.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Fury.cpp @@ -15,8 +15,7 @@ namespace Mantid::Kernel::Logger g_log("Fury"); } -using Mantid::API::MatrixWorkspace; -using Mantid::API::MatrixWorkspace_const_sptr; +using namespace Mantid::API; namespace MantidQt { @@ -36,12 +35,6 @@ namespace IDA m_furTree = new QtTreePropertyBrowser(); m_uiForm.properties->addWidget(m_furTree); - m_plots["FuryPlot"] = new QwtPlot(m_parentWidget); - m_uiForm.plot->addWidget(m_plots["FuryPlot"]); - m_plots["FuryPlot"]->setCanvasBackground(Qt::white); - m_plots["FuryPlot"]->setAxisFont(QwtPlot::xBottom, m_parentWidget->font()); - m_plots["FuryPlot"]->setAxisFont(QwtPlot::yLeft, m_parentWidget->font()); - // Create and configure properties m_properties["ELow"] = m_dblManager->addProperty("ELow"); m_dblManager->setDecimals(m_properties["ELow"], NUM_DECIMALS); @@ -75,7 +68,7 @@ namespace IDA m_furTree->setFactoryForManager(m_dblManager, m_dblEdFac); - m_rangeSelectors["FuryRange"] = new MantidQt::MantidWidgets::RangeSelector(m_plots["FuryPlot"]); + m_rangeSelectors["FuryRange"] = new MantidQt::MantidWidgets::RangeSelector(m_uiForm.ppPlot); // signals / slots & validators connect(m_rangeSelectors["FuryRange"], SIGNAL(selectionChangedLazy(double, double)), this, SLOT(rsRangeChangedLazy(double, double))); @@ -250,10 +243,10 @@ namespace IDA void Fury::plotInput(const QString& wsname) { - MatrixWorkspace_const_sptr workspace; + MatrixWorkspace_sptr workspace; try { - workspace = Mantid::API::AnalysisDataService::Instance().retrieveWS(wsname.toStdString()); + workspace = Mantid::API::AnalysisDataService::Instance().retrieveWS(wsname.toStdString()); } catch(Mantid::Kernel::Exception::NotFoundError&) { @@ -261,13 +254,15 @@ namespace IDA return; } - plotMiniPlot(workspace, 0, "FuryPlot", "FuryCurve"); + m_uiForm.ppPlot->clear(); + m_uiForm.ppPlot->addSpectrum("Sample", workspace, 0); + try { - const std::pair range = getCurveRange("FuryCurve"); + QPair range = m_uiForm.ppPlot->getCurveRange(workspace); double rounded_min(range.first); double rounded_max(range.second); - const std::string instrName( workspace->getInstrument()->getName() ); + const std::string instrName(workspace->getInstrument()->getName()); if(instrName == "BASIS") { m_rangeSelectors["FuryRange"]->setRange(range.first, range.second); @@ -308,8 +303,6 @@ namespace IDA //set default value for width m_dblManager->setValue(m_properties["EWidth"], 0.005); } - - replot("FuryPlot"); } catch(std::invalid_argument & exc) { From 1b5a920cb6fd985d56fe39bc57325314c0d8a154 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Thu, 12 Feb 2015 10:44:50 +0000 Subject: [PATCH 069/414] Re #9556 Updating function according to fortran code provided --- .../CurveFitting/src/DynamicKuboToyabe.cpp | 217 ++++-------------- 1 file changed, 51 insertions(+), 166 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index 2193a42fdaec..613853730dbb 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -40,100 +40,57 @@ void DynamicKuboToyabe::init() declareParameter("Nu", 0.0, "Hopping rate"); } +double getDKT (double t, double sig, double nu){ -//------------------------------------------------------------------------------------------------ -// Routines from Numerical Recipes - -double midpnt(double func(const double, const double, const double), - const double a, const double b, const int n, const double g, const double w0) { -// quote & modified from numerical recipe 2nd edtion (page147) - - static double s; - - if (n==1) { - s = (b-a)*func(0.5*(a+b),g,w0); - return (s); - } else { - double x, tnm, sum, del, ddel; - int it, j; - for (it=1,j=1;j c(n+1); - std::vector d(n+1); - for (i=1;i<=n;i++){ - double dift; - if((dift=fabs(x-xa[i]))= K) { - polint(&h[j-K],&s[j-K],K,0.0,ss,dss); - if (fabs(dss) <= fabs(ss)) return ss; - } - h[j+1]=h[j]/9.0; - } - throw std::runtime_error("integrate(): Too many steps in routine integrate\n"); - return 0.0; -} -//-------------------------------------------------------------------------------------------------------------------------------------- + if ( (sig == oldsig) && (nu == oldnu) ){ + // Re-use previous computation + xi=int(fabs(t)/eps); + if (xi>tsmax-2) + xi = tsmax-2; + xe=(fabs(t)/eps)-xi; + return gd[xi+1]*(1-xe)+xe*gd[xi+2]; + } + + oldsig=sig; + oldnu =nu; + hop = nu*eps; + + // Generate static Kubo-Toyabe + for (k=1; k<=tsmax; k++){ + tt = (k-1)*eps*sig*(k-1)*eps*sig; + gs[k]=0.3333333333+0.6666666667*(1-tt)*exp(-tt/2); + } + + // Generate dynamic f-u-f + for (k=1; k<=tsmax; k++){ + y=gs[k]; + for (j=k-1; j>=2; j--){ + y=y*(1-hop)+hop*gd[k-j+1]*gs[j]; + } + gd[k]=y; + } -double f1(const double x, const double G, const double w0) { + + // Interpolate table. If beyond end, extrapolate... + xi=int(abs(t)/eps); + if (xi>tsmax-2) + xi = tsmax-2; + xe=abs(t)/eps-xi; + return gd[xi+1]*(1-xe)+xe*gd[xi+2]; - return( exp(-G*G*x*x/2)*sin(w0*x)); } // Zero Field Kubo Toyabe relaxation function @@ -146,11 +103,7 @@ double ZFKT (const double x, const double G){ // Non-Zero field Kubo Toyabe relaxation function double HKT (const double x, const double G, const double F) { - const double w0 = 2.0*3.1415926536*0.01355342*F; - const double q = G*G*x*x; - const double p = G*G/(w0*w0); - double hkt = 1.0-2.0*p*(1-exp(-q/2.0)*cos(w0*x))+2.0*p*p*w0*integrate(f1,0.0,x,G,w0); - return hkt; + throw std::runtime_error("HKT not implemented yet"); } // Dynamic Kubo Toyabe function @@ -162,7 +115,7 @@ void DynamicKuboToyabe::function1D(double* out, const double* xValues, const siz const double& v = fabs(getParameter("Nu")); - // Zero hopping rate + // Zero hopping rate if (v == 0.0) { // Zero external field @@ -182,88 +135,20 @@ void DynamicKuboToyabe::function1D(double* out, const double* xValues, const siz // Non-zero hopping rate else { - // Make sure stepsize is smaller than spacing between xValues - //int n = 1000; - //while (n funcG(n); - - double efac1=exp(-v*stepsize); // survival prob for step - double efac2=(1.0-efac1); // hop prob ~ hoprate*step - - // Mark's implementation - if ( F == 0.0 ){ - // Zero field - - for (int i = 0; i < n; i++) { + if ( F==0.0 ) { - funcG[0]=ZFKT(0,G); - funcG[1]=ZFKT(stepsize,G); - - for(i=1; i Date: Thu, 12 Feb 2015 10:49:19 +0000 Subject: [PATCH 070/414] Re #9556 Updating some values and temporarily disabling some tests --- .../CurveFitting/test/DynamicKuboToyabeTest.h | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h index 0eaef5a0d20d..1ef182d01e08 100644 --- a/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h @@ -73,14 +73,14 @@ class DynamicKuboToyabeTest : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING(dkt.function(x,y)); - TS_ASSERT_DELTA( y[0], 1.000000, 0.000001); - TS_ASSERT_DELTA( y[1], 0.849898, 0.000001); - TS_ASSERT_DELTA( y[2], 0.621963, 0.000001); - TS_ASSERT_DELTA( y[3], 0.443612, 0.000001); - TS_ASSERT_DELTA( y[4], 0.317374, 0.000001); + TS_ASSERT_DELTA( y[0], 1.0000, 0.0001); + TS_ASSERT_DELTA( y[1], 0.8501, 0.0001); + TS_ASSERT_DELTA( y[2], 0.6252, 0.0001); + TS_ASSERT_DELTA( y[3], 0.4490, 0.0001); + TS_ASSERT_DELTA( y[4], 0.3233, 0.0001); } - void testZNDKTFunction() + void xtestZNDKTFunction() { // Test Dynamic Kubo Toyabe (DKT) for non-zero Field and Zero Nu (ZN) const double asym = 1.0; @@ -108,7 +108,7 @@ class DynamicKuboToyabeTest : public CxxTest::TestSuite TS_ASSERT_DELTA( y[4], 0.055052, 0.000001); } - void testDKTFunction() + void xtestDKTFunction() { // Test Dynamic Kubo Toyabe (DKT) (non-zero Field, non-zero Nu) const double asym = 1.0; From 59d368aeec062c028be0f0627f272c9de114c395 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Thu, 12 Feb 2015 10:53:46 +0000 Subject: [PATCH 071/414] Re #9556 Being more strict with test results --- .../CurveFitting/test/DynamicKuboToyabeTest.h | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h index 1ef182d01e08..74e8717d9fb9 100644 --- a/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h @@ -72,12 +72,11 @@ class DynamicKuboToyabeTest : public CxxTest::TestSuite Mantid::API::FunctionValues y(x); TS_ASSERT_THROWS_NOTHING(dkt.function(x,y)); - - TS_ASSERT_DELTA( y[0], 1.0000, 0.0001); - TS_ASSERT_DELTA( y[1], 0.8501, 0.0001); - TS_ASSERT_DELTA( y[2], 0.6252, 0.0001); - TS_ASSERT_DELTA( y[3], 0.4490, 0.0001); - TS_ASSERT_DELTA( y[4], 0.3233, 0.0001); + TS_ASSERT_DELTA( y[0], 1.000000, 0.000001); + TS_ASSERT_DELTA( y[1], 0.850107, 0.000001); + TS_ASSERT_DELTA( y[2], 0.625283, 0.000001); + TS_ASSERT_DELTA( y[3], 0.449064, 0.000001); + TS_ASSERT_DELTA( y[4], 0.323394, 0.000001); } void xtestZNDKTFunction() From e69074ae838df54df334628a1aba046e5adaec4a Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Thu, 12 Feb 2015 11:05:23 +0000 Subject: [PATCH 072/414] Re #9556 Updating documentation --- Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst b/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst index 85aeb26ddd97..5dc384cf2170 100644 --- a/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst +++ b/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst @@ -14,16 +14,18 @@ by .. math:: G_z \left(t\right) = g_z\left(t\right) e^{-\nu t} + \nu \int_0^t g_z\left(\tau\right) e^{-\nu\tau} G_z\left(t-\tau\right) d\tau -where :math:`g_z\left(t\right)` is the static KT function. +where :math:`g_z\left(t\right)` is the static KT function, and :math:`\nu` the muon hopping rate. | In zero field, :math:`B_0=0`: .. math:: g_z\left(t\right) = \mbox{A} \Bigg[ \frac{1}{3} + \frac{2}{3} \left( 1 - {\Delta}^2 {t}^2 \right) e^{-\frac{1}{2}\Delta^2 t^2} \Bigg] -| In the presence of a longitudinal field, :math:`B_0=\omega_0 /\gamma_{\mu}>0`: +| In the presence of a longitudinal field, :math:`B_0=\omega_0 /\left(2\pi \gamma_{\mu}\right)>0`: .. math:: g_z\left(t\right) = \mbox{A} \Bigg[ 1 - 2\frac{\Delta^2}{\omega_0^2}\Big(1-cos(\omega_0 t)e^{-\frac{1}{2}\Delta^2 t^2}\Big) + 2\frac{\Delta^4}{\omega_0^4}\omega_0\int_0^\tau \sin(\omega_0\tau)e^{-\frac{1}{2}\Delta^2\tau^2}d\tau \Bigg] +Note: The static function in longitudinal field will be implemented soon. In the meantime, please fix the external field :math:`B_0` (F parameter) to 0. + .. attributes:: .. properties:: From 316d13e2416fcf1cce09dbdb0ebcb31c917a2e82 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Thu, 12 Feb 2015 11:16:12 +0000 Subject: [PATCH 073/414] Run the system tests on RHEL6 pull request builds. Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript | 36 +++++++++++++++++++-------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript b/Code/Mantid/Build/Jenkins/buildscript index 693cdaf874ae..b1899d337d4a 100755 --- a/Code/Mantid/Build/Jenkins/buildscript +++ b/Code/Mantid/Build/Jenkins/buildscript @@ -64,6 +64,16 @@ if [ -z "$MANTID_DATA_STORE" ]; then export MANTID_DATA_STORE=$(dirname $WORKSPACE) fi +############################################################################### +# RHEL6 setup steps - nodes must have a "rhel6" label set (in lowercase) +############################################################################### +if [[ ${NODE_LABELS} == *rhel6* ]]; then + SCL_ON_RHEL6="scl enable mantidlibs" + ON_RHEL6=true +else + SCL_ON_RHEL6="eval" +fi + ############################################################################### # Check job requirements from the name ############################################################################### @@ -103,16 +113,6 @@ if [[ "$BUILDPKG" == true ]]; then fi fi -############################################################################### -# RHEL6 setup steps - nodes must have a "rhel6" label set (in lowercase) -############################################################################### -if [[ ${NODE_LABELS} == *rhel6* ]]; then - SCL_ON_RHEL6="scl enable mantidlibs" - ON_RHEL6=true -else - SCL_ON_RHEL6="eval" -fi - ############################################################################### # Create the build directory if it doesn't exist ############################################################################### @@ -169,7 +169,8 @@ $SCL_ON_RHEL6 "cmake --build . --target AllTests -- -j$BUILD_THREADS" # Run the tests ############################################################################### # Remove any Mantid.user.properties file -rm -f ~/.mantid/Mantid.user.properties +userprops=~/.mantid/Mantid.user.properties +rm -f $userprops $SCL_ON_RHEL6 "ctest -j$BUILD_THREADS --schedule-random --output-on-failure" ############################################################################### @@ -196,3 +197,16 @@ if [[ "$BUILDPKG" == true ]]; then $SCL_ON_RHEL6 "cpack --config CPackSourceConfig.cmake -D CPACK_PACKAGING_INSTALL_PREFIX=" fi fi + +############################################################################### +# Run the system tests on RHEL6 when doing a pull request build. Run +# from a package to have at least one Linux checks it install okay +############################################################################### +if [[ "${ON_RHEL6}" == true ]] && [[ ${JOB_NAME} == *pull_requests* ]]; then + PKGDIR=${WORKSPACE}/build + # Turn off usage reports and instrument downloading for the mantid call + # that creates the properties file + echo "UpdateInstrumentDefinitions.OnStartup = 0" > $userprops + echo "usagereports.enabled = 0" >> $userprops + python $WORKSPACE/Code/Mantid/Testing/SystemTests/scripts/InstallerTesting.py -o -d $PKGDIR +fi From 1a36b232e1d7fa13642a388baf0a8d65b4c4f496 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Thu, 12 Feb 2015 11:34:47 +0000 Subject: [PATCH 074/414] Key curves by legend name, use on JumpFit Refs #11036 --- .../Indirect/JumpFit.ui | 67 +++----- .../CustomInterfaces/src/Indirect/Elwin.cpp | 2 +- .../CustomInterfaces/src/Indirect/Fury.cpp | 2 +- .../src/Indirect/IndirectMoments.cpp | 2 +- .../src/Indirect/IndirectSymmetrise.cpp | 4 +- .../CustomInterfaces/src/Indirect/JumpFit.cpp | 33 ++-- .../CustomInterfaces/src/Indirect/MSDFit.cpp | 4 +- .../inc/MantidQtMantidWidgets/PreviewPlot.h | 10 +- .../MantidWidgets/src/PreviewPlot.cpp | 153 +++++++++--------- 9 files changed, 120 insertions(+), 157 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/JumpFit.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/JumpFit.ui index 31701866223b..40686a05197a 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/JumpFit.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/JumpFit.ui @@ -110,55 +110,18 @@
- - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Data - - - - - - - color: rgb(255, 0, 0); - - - Fit - - - - - - - color: rgb(0, 255, 0); - - - Diff - - - - - - + + + + 255 + 255 + 255 + + + + true + + @@ -233,6 +196,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp index 6dc0df914304..db1e27990a7c 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp @@ -359,7 +359,7 @@ namespace IDA try { - QPair range = m_uiForm.ppPlot->getCurveRange(ws); + QPair range = m_uiForm.ppPlot->getCurveRange("Sample"); m_rangeSelectors["ElwinIntegrationRange"]->setRange(range.first, range.second); } catch(std::invalid_argument & exc) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Fury.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Fury.cpp index 59fc186d63b8..a634b803255d 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Fury.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Fury.cpp @@ -259,7 +259,7 @@ namespace IDA try { - QPair range = m_uiForm.ppPlot->getCurveRange(workspace); + QPair range = m_uiForm.ppPlot->getCurveRange("Sample"); double rounded_min(range.first); double rounded_max(range.second); const std::string instrName(workspace->getInstrument()->getName()); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp index 947d1ca2c735..84fa7cc8429b 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp @@ -115,7 +115,7 @@ namespace CustomInterfaces m_uiForm.ppRawPlot->clear(); m_uiForm.ppRawPlot->addSpectrum("Raw", filename, 0); - QPair curveRange = m_uiForm.ppRawPlot->getCurveRange(filename); + QPair curveRange = m_uiForm.ppRawPlot->getCurveRange("Raw"); std::pair range = std::make_pair(curveRange.first, curveRange.second); setMiniPlotGuides("MomentsRangeSelector", m_properties["EMin"], m_properties["EMax"], range); setPlotRange("MomentsRangeSelector", m_properties["EMin"], m_properties["EMax"], range); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp index 2fa9508e7e80..f5ae4fecfcbc 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp @@ -206,7 +206,7 @@ namespace CustomInterfaces updateMiniPlots(); // Set the preview range to the maximum absolute X value - QPair axisRange = m_uiForm.ppRawPlot->getCurveRange(sampleWS); + QPair axisRange = m_uiForm.ppRawPlot->getCurveRange("Raw"); double symmRange = std::max(fabs(axisRange.first), fabs(axisRange.second)); // Set valid range for range selectors @@ -240,7 +240,7 @@ namespace CustomInterfaces m_uiForm.ppRawPlot->addSpectrum("Raw", input, spectrumIndex); // Match X axis range on preview plot - m_uiForm.ppPreviewPlot->setAxisRange(m_uiForm.ppRawPlot->getCurveRange(input), QwtPlot::xBottom); + m_uiForm.ppPreviewPlot->setAxisRange(m_uiForm.ppRawPlot->getCurveRange("Raw"), QwtPlot::xBottom); m_uiForm.ppPreviewPlot->replot(); } diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/JumpFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/JumpFit.cpp index 6a093dcd26df..4e708b5ffe1f 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/JumpFit.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/JumpFit.cpp @@ -18,15 +18,8 @@ namespace MantidQt { m_uiForm.setupUi(parent); - // Create the plot - m_plots["JumpFitPlot"] = new QwtPlot(m_parentWidget); - m_plots["JumpFitPlot"]->setCanvasBackground(Qt::white); - m_plots["JumpFitPlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); - m_plots["JumpFitPlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); - m_uiForm.plotSpace->addWidget(m_plots["JumpFitPlot"]); - // Create range selector - m_rangeSelectors["JumpFitQ"] = new MantidWidgets::RangeSelector(m_plots["JumpFitPlot"]); + m_rangeSelectors["JumpFitQ"] = new MantidWidgets::RangeSelector(m_uiForm.ppPlot); connect(m_rangeSelectors["JumpFitQ"], SIGNAL(selectionChangedLazy(double, double)), this, SLOT(qRangeChanged(double, double))); // Add the properties browser to the ui form @@ -179,19 +172,11 @@ namespace MantidQt QString specName = QString::fromStdString(axis->label(histIndex)); if(specName == "Calc") - { - plotMiniPlot(outputWorkspace, histIndex, "JumpFitPlot", specName); - m_curves[specName]->setPen(QColor(Qt::red)); - } + m_uiForm.ppPlot->addSpectrum("Fit", outputWorkspace, histIndex, Qt::red); if(specName == "Diff") - { - plotMiniPlot(outputWorkspace, histIndex, "JumpFitPlot", specName); - m_curves[specName]->setPen(QColor(Qt::green)); - } + m_uiForm.ppPlot->addSpectrum("Diff", outputWorkspace, histIndex, Qt::green); } - - replot("JumpFitPlot"); } /** @@ -236,10 +221,13 @@ namespace MantidQt m_uiForm.cbWidth->setEnabled(true); std::string currentWidth = m_uiForm.cbWidth->currentText().toStdString(); - plotMiniPlot(filename, m_spectraList[currentWidth], "JumpFitPlot", "RawPlotCurve"); - std::pair res; - std::pair range = getCurveRange("RawPlotCurve"); + m_uiForm.ppPlot->clear(); + m_uiForm.ppPlot->addSpectrum("Sample", filename, m_spectraList[currentWidth]); + + std::pair res; + QPair curveRange = m_uiForm.ppPlot->getCurveRange("Sample"); + std::pair range(curveRange.first, curveRange.second); // Use the values from the instrument parameter file if we can if(getInstrumentResolution(filename, res)) @@ -331,7 +319,8 @@ namespace MantidQt { if(validate()) { - plotMiniPlot(sampleName, m_spectraList[text.toStdString()], "JumpFitPlot", "RawPlotCurve"); + m_uiForm.ppPlot->clear(); + m_uiForm.ppPlot->addSpectrum("Sample", sampleName, m_spectraList[text.toStdString()]); } } } diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/MSDFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/MSDFit.cpp index 1717520f353e..f2eeb1051454 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/MSDFit.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/MSDFit.cpp @@ -146,7 +146,7 @@ namespace IDA auto ws = boost::dynamic_pointer_cast(groupWs->getItem(0)); // Remove the old fit - m_uiForm.ppPlot->removeSpectrumByCurveName("Fit"); + m_uiForm.ppPlot->removeSpectrum("Fit"); // Plot the new fit m_uiForm.ppPlot->addSpectrum("Fit", ws, 1, Qt::red); @@ -198,7 +198,7 @@ namespace IDA try { - QPair range = m_uiForm.ppPlot->getCurveRange(ws); + QPair range = m_uiForm.ppPlot->getCurveRange("Sample"); m_rangeSelectors["MSDRange"]->setRange(range.first, range.second); } catch(std::invalid_argument & exc) diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h index 9bb38e7e0e19..b54ccc0acbc3 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -71,18 +71,18 @@ namespace MantidWidgets void setAxisRange(QPair range, int axisID = QwtPlot::xBottom); QPair getCurveRange(const Mantid::API::MatrixWorkspace_sptr ws); - QPair getCurveRange(const QString & wsName); + QPair getCurveRange(const QString & curveName); void addSpectrum(const QString & curveName, const Mantid::API::MatrixWorkspace_sptr ws, const size_t specIndex = 0, const QColor & curveColour = QColor()); void addSpectrum(const QString & curveName, const QString & wsName, const size_t specIndex = 0, const QColor & curveColour = QColor()); void removeSpectrum(const Mantid::API::MatrixWorkspace_sptr ws); - void removeSpectrum(const QString & wsName); - void removeSpectrumByCurveName(const QString & name); + void removeSpectrum(const QString & curveName); signals: /// Signals that the plot should be refreshed void needToReplot(); + void needToHardReplot(); public slots: void showLegend(bool show); @@ -98,6 +98,7 @@ namespace MantidWidgets /// Holds information about a plot curve struct PlotCurveConfiguration { + Mantid::API::MatrixWorkspace_sptr ws; QwtPlotCurve *curve; QLabel *label; QColor colour; @@ -116,6 +117,7 @@ namespace MantidWidgets QList addOptionsToMenus(QString menuName, QActionGroup *group, QStringList items, QString defaultItem); QString getAxisType(int axisID); + QStringList getCurvesForWorkspace(const Mantid::API::MatrixWorkspace_sptr ws); private slots: void showContextMenu(QPoint position); @@ -136,7 +138,7 @@ namespace MantidWidgets friend class RangeSelector; /// Map of curve key to plot info - QMap m_curves; + QMap m_curves; /// Plot manipulation tools QwtPlotMagnifier *m_magnifyTool; diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index 25a1ebee34bc..61b7ce07d6fe 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -107,6 +107,7 @@ PreviewPlot::PreviewPlot(QWidget *parent, bool init) : API::MantidWidget(parent) m_contextMenu->addAction(m_showLegendAction); connect(this, SIGNAL(needToReplot()), this, SLOT(replot())); + connect(this, SIGNAL(needToHardReplot()), this, SLOT(hardReplot())); } @@ -181,36 +182,34 @@ void PreviewPlot::setAxisRange(QPair range, int axisID) */ QPair PreviewPlot::getCurveRange(const Mantid::API::MatrixWorkspace_sptr ws) { - if(!m_curves.contains(ws)) - throw std::runtime_error("Workspace not on preview plot."); + QStringList curveNames = getCurvesForWorkspace(ws); - size_t numPoints = m_curves[ws].curve->data().size(); + if(curveNames.size() == 0) + throw std::runtime_error("Curve for workspace not found."); - if(numPoints < 2) - return qMakePair(0.0, 0.0); - - double low = m_curves[ws].curve->data().x(0); - double high = m_curves[ws].curve->data().x(numPoints - 1); - - return qMakePair(low, high); + return getCurveRange(curveNames[0]); } /** * Gets the X range of a curve given its name. * - * @param wsName Name of workspace + * @param wsName Name of curve */ -QPair PreviewPlot::getCurveRange(const QString & wsName) +QPair PreviewPlot::getCurveRange(const QString & curveName) { - // Try to get a pointer from the name - std::string wsNameStr = wsName.toStdString(); - auto ws = AnalysisDataService::Instance().retrieveWS(wsName.toStdString()); + if(!m_curves.contains(curveName)) + throw std::runtime_error("Curve not on preview plot."); - if(!ws) - throw std::runtime_error(wsNameStr + " is not a MatrixWorkspace, not supported by PreviewPlot."); + size_t numPoints = m_curves[curveName].curve->data().size(); + + if(numPoints < 2) + return qMakePair(0.0, 0.0); - return getCurveRange(ws); + double low = m_curves[curveName].curve->data().x(0); + double high = m_curves[curveName].curve->data().x(numPoints - 1); + + return qMakePair(low, high); } @@ -225,6 +224,10 @@ QPair PreviewPlot::getCurveRange(const QString & wsName) void PreviewPlot::addSpectrum(const QString & curveName, const MatrixWorkspace_sptr ws, const size_t specIndex, const QColor & curveColour) { + // Remove the existing curve if it exists + if(m_curves.contains(curveName)) + removeSpectrum(curveName); + // Create the curve QwtPlotCurve * curve = addCurve(ws, specIndex, curveColour); @@ -238,10 +241,11 @@ void PreviewPlot::addSpectrum(const QString & curveName, const MatrixWorkspace_s label->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); m_uiForm.loLegend->addWidget(label); - m_curves[ws].curve = curve; - m_curves[ws].label = label; - m_curves[ws].colour = curveColour; - m_curves[ws].wsIndex = specIndex; + m_curves[curveName].ws = ws; + m_curves[curveName].curve = curve; + m_curves[curveName].label = label; + m_curves[curveName].colour = curveColour; + m_curves[curveName].wsIndex = specIndex; // Replot emit needToReplot(); @@ -257,7 +261,7 @@ void PreviewPlot::addSpectrum(const QString & curveName, const MatrixWorkspace_s * @param curveColour Colour of curve to plot */ void PreviewPlot::addSpectrum(const QString & curveName, const QString & wsName, - const size_t specIndex, const QColor & curveColour) + const size_t specIndex, const QColor & curveColour) { // Try to get a pointer from the name std::string wsNameStr = wsName.toStdString(); @@ -273,58 +277,40 @@ void PreviewPlot::addSpectrum(const QString & curveName, const QString & wsName, /** * Removes spectra from a gievn workspace from the plot given a pointer to it. * + * If multiple curves are plotted form the smae workspace then all wil lbe removed. + * * @param ws Pointer to workspace */ void PreviewPlot::removeSpectrum(const MatrixWorkspace_sptr ws) { - // Remove the curve object and legend label - if(m_curves.contains(ws)) - { - removeCurve(m_curves[ws].curve); - m_uiForm.loLegend->removeWidget(m_curves[ws].label); - delete m_curves[ws].label; - } + QStringList curveNames = getCurvesForWorkspace(ws); - // Get the curve from the map - auto it = m_curves.find(ws); - - // Remove the curve from the map - if(it != m_curves.end()) - m_curves.erase(it); + for(auto it = curveNames.begin(); it != curveNames.end(); ++it) + removeSpectrum(*it); } /** * Removes spectra from a gievn workspace from the plot given its name. * - * @param wsName Name of workspace + * @param wsName Name of curve */ -void PreviewPlot::removeSpectrum(const QString & wsName) +void PreviewPlot::removeSpectrum(const QString & curveName) { - // Try to get a pointer from the name - std::string wsNameStr = wsName.toStdString(); - auto ws = AnalysisDataService::Instance().retrieveWS(wsNameStr); - - if(!ws) - throw std::runtime_error(wsNameStr + " is not a MatrixWorkspace, not supported by PreviewPlot."); - - removeSpectrum(ws); -} - - -/** - * Removes a curve from the plot given its name (as displayed in the legend). - * - * @param name Name of curve - */ -void PreviewPlot::removeSpectrumByCurveName(const QString & name) -{ - for(auto it = m_curves.begin(); it != m_curves.end(); ++it) + // Remove the curve object and legend label + if(m_curves.contains(curveName)) { - QLabel *label = it.value().label; - if(label && label->text() == name) - removeSpectrum(it.key()); + removeCurve(m_curves[curveName].curve); + m_uiForm.loLegend->removeWidget(m_curves[curveName].label); + delete m_curves[curveName].label; } + + // Get the curve from the map + auto it = m_curves.find(curveName); + + // Remove the curve from the map + if(it != m_curves.end()) + m_curves.erase(it); } @@ -444,10 +430,13 @@ void PreviewPlot::replot() */ void PreviewPlot::hardReplot() { - QList keys = m_curves.keys(); + QStringList keys = m_curves.keys(); for(auto it = keys.begin(); it != keys.end(); ++it) - m_curves[*it].curve = addCurve(*it, m_curves[*it].wsIndex, m_curves[*it].colour); + { + removeCurve(m_curves[*it].curve); + m_curves[*it].curve = addCurve(m_curves[*it].ws, m_curves[*it].wsIndex, m_curves[*it].colour); + } replot(); } @@ -464,8 +453,8 @@ void PreviewPlot::handleRemoveEvent(WorkspacePreDeleteNotification_ptr pNf) { MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast(pNf->object()); - // Ignore non matrix worksapces and those not in the plot - if(!ws || !m_curves.contains(ws)) + // Ignore non matrix worksapces + if(!ws) return; // Remove the workspace @@ -486,14 +475,12 @@ void PreviewPlot::handleReplaceEvent(WorkspaceAfterReplaceNotification_ptr pNf) { MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast(pNf->object()); - // Ignore non matrix worksapces and those not in the plot - if(!ws || !m_curves.contains(ws)) + // Ignore non matrix worksapces + if(!ws) return; - // Replace the existing curve - m_curves[ws].curve = addCurve(ws, m_curves[ws].wsIndex, m_curves[ws].colour); - - emit needToReplot(); + if(getCurvesForWorkspace(ws).size() > 0) + emit needToHardReplot(); } @@ -516,10 +503,6 @@ QwtPlotCurve * PreviewPlot::addCurve(MatrixWorkspace_sptr ws, const size_t specI if(ws->readX(0).size() < 2) throw std::runtime_error("X axis is too small to generate a histogram plot."); - // Remove any existing curves - if(m_curves.contains(ws)) - removeCurve(m_curves[ws].curve); - // Convert X axis to squared if needed if(getAxisType(QwtPlot::xBottom) == "Squared") { @@ -626,6 +609,26 @@ QString PreviewPlot::getAxisType(int axisID) } +/** + * Gets a list of curve names that are plotted form the given workspace. + * + * @param Pointer to workspace + * @return List of curve names + */ +QStringList PreviewPlot::getCurvesForWorkspace(const MatrixWorkspace_sptr ws) +{ + QStringList curveNames; + + for(auto it = m_curves.begin(); it != m_curves.end(); ++it) + { + if(it.value().ws == ws) + curveNames << it.key(); + } + + return curveNames; +} + + /** * Handles displaying the context menu when a user right clicks on the plot. * @@ -708,5 +711,5 @@ void PreviewPlot::handleAxisTypeSelect() m_uiForm.plot->setAxisScaleEngine(QwtPlot::yLeft, yEngine); // Update the plot - hardReplot(); + emit needToHardReplot(); } From 941ce1532657ebbd2ec37dc35c01878c5288e5e5 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Thu, 12 Feb 2015 11:43:41 +0000 Subject: [PATCH 075/414] refs #11056. Fix exposing peak to python. Keep changes to setQLabFrame as expoesed to python instep with what's changed on the c++ side and test it. --- .../Mantid/Framework/DataObjects/test/PeakTest.h | 15 ++------------- .../mantid/api/src/Exports/IPeak.cpp | 13 +++++++++---- .../python/mantid/api/IPeaksWorkspaceTest.py | 16 ++++++++++++++++ 3 files changed, 27 insertions(+), 17 deletions(-) diff --git a/Code/Mantid/Framework/DataObjects/test/PeakTest.h b/Code/Mantid/Framework/DataObjects/test/PeakTest.h index ab61f6e678d8..638f299f8245 100644 --- a/Code/Mantid/Framework/DataObjects/test/PeakTest.h +++ b/Code/Mantid/Framework/DataObjects/test/PeakTest.h @@ -346,25 +346,14 @@ class PeakTest : public CxxTest::TestSuite V3D qLab = qLabDir * wavenumber_in_angstrom_times_tof_in_microsec; - - //Peak peak(minimalInstrument, 1 /* detector id */, x[0] /*wavelength*/); - - - Peak peak; // Everything will be default peak.setInstrument(minimalInstrument); // Can't do anything without the instrument peak.setQLabFrame(qLab); auto detector = peak.getDetector(); TSM_ASSERT("No detector", detector); - if(detector) - { - TS_ASSERT_EQUALS(1, detector->getID()); - TS_ASSERT_EQUALS(detectorPos, detector->getPos()); - } - - // Test that wavelengths aggree firstly. - //TS_ASSERT_EQUALS(x[0], peak.getWavelength()); + TS_ASSERT_EQUALS(1, detector->getID()); + TS_ASSERT_EQUALS(detectorPos, detector->getPos()); } /** Create peaks using Q in sample frame + a goniometer rotation matrix*/ diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp index c5d3eec3e73f..f88422894a47 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp @@ -6,9 +6,13 @@ using Mantid::API::IPeak; using namespace boost::python; namespace { -Mantid::Geometry::PeakShape_sptr getPeakShape(IPeak& peak) { - // Use clone to make a copy of the PeakShape. - return Mantid::Geometry::PeakShape_sptr(peak.getPeakShape().clone()); +Mantid::Geometry::PeakShape_sptr getPeakShape(IPeak &peak) { + // Use clone to make a copy of the PeakShape. + return Mantid::Geometry::PeakShape_sptr(peak.getPeakShape().clone()); +} +void setQLabFrame(IPeak &peak, Mantid::Kernel::V3D qLabFrame, double distance) { + // Set the qlab frame + return peak.setQLabFrame(qLabFrame, distance); } } @@ -38,7 +42,8 @@ void export_IPeak() "Using the instrument set in the peak, perform ray tracing to find the exact detector.") .def("getQSampleFrame", &IPeak::getQSampleFrame, "Return the Q change (of the lattice, k_i - k_f) for this peak." "The Q is in the Sample frame: the goniometer rotation WAS taken out. ") - .def("setQLabFrame", &IPeak::setQLabFrame, "Set the peak using the peak's position in reciprocal space, in the lab frame.") + .def("setQLabFrame", (void (IPeak::*)(Mantid::Kernel::V3D))&IPeak::setQLabFrame) + .def("setQLabFrame", setQLabFrame, "Set the peak using the peak's position in reciprocal space, in the lab frame.") .def("setQSampleFrame", &IPeak::setQSampleFrame, "Set the peak using the peak's position in reciprocal space, in the sample frame.") .def("setWavelength", &IPeak::setWavelength, "Set the incident wavelength of the neutron. Calculates the energy from this assuming elastic scattering.") .def("getWavelength", &IPeak::getWavelength, "Return the incident wavelength") diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py index 9726f2b928cd..c41d65e9e72a 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py @@ -51,6 +51,22 @@ def test_interface(self): # Peaks workspace will not be integrated by default. self.assertTrue(not pws.hasIntegratedPeaks()) + def test_peak_setQLab(self): + pws = WorkspaceCreationHelper.createPeaksWorkspace(1) + p = pws.getPeak(0) + try: + p.setQLabFrame(V3D(1,1,1)) + except Exception: + self.fail("Tried setQLabFrame with one V3D argument") + + try: + p.setQLabFrame(V3D(1,1,1), 1) + except Exception: + self.fail("Tried setQLabFrame with one V3D argument and a double distance") + + + + if __name__ == '__main__': unittest.main() From 9ade93ddf9a7e4d419291d3bfe65e5b3c326abac Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Thu, 12 Feb 2015 11:29:05 +0000 Subject: [PATCH 076/414] Remove screenshots from MantidPlot tests They proved confusing when running the build scripts as they looked like they had come from building the documentation and had gone to the wrong directory. Refs #10870 --- Code/Mantid/MantidPlot/test/MantidPlot1DPlotTest.py | 3 --- .../Mantid/MantidPlot/test/MantidPlotProxiesTest.py | 3 --- .../MantidPlot/test/MantidPlotSliceViewerTest.py | 13 ++++++------- 3 files changed, 6 insertions(+), 13 deletions(-) diff --git a/Code/Mantid/MantidPlot/test/MantidPlot1DPlotTest.py b/Code/Mantid/MantidPlot/test/MantidPlot1DPlotTest.py index 829047a78158..9f30dff27a0b 100644 --- a/Code/Mantid/MantidPlot/test/MantidPlot1DPlotTest.py +++ b/Code/Mantid/MantidPlot/test/MantidPlot1DPlotTest.py @@ -41,7 +41,6 @@ def tearDown(self): def test_plotSpectrum_errorBars(self): g = plotSpectrum("fake", 0, error_bars=True) - screenshot(g, "plotSpectrum_errorBars", "Call to plotSpectrum() of 1 spectrum, with error bars.") self.g = g def test_plotSpectrum_fromWorkspaceProxy(self): @@ -51,7 +50,6 @@ def test_plotSpectrum_fromWorkspaceProxy(self): def test_plotSpectrum_severalSpectra(self): g = plotSpectrum("fake", [0, 1]) - screenshot(g, "plotSpectrum_severalSpectra", "Call to plotSpectrum() of 2 spectra, no error bars.") self.g = g def test_Customized1DPlot(self): @@ -65,7 +63,6 @@ def test_Customized1DPlot(self): l.setTitleAlignment(QtCore.Qt.AlignLeft) l.setScale(2, 0.0, 3.0) l.setAntialiasing(True) - screenshot(g, "Customized1DPlot", "1D plot of a spectrum, with error bars, an orange line of width 2, a custom title in red Arial font, with X from 0 to 3") self.g = g def test_standard_plot_command(self): diff --git a/Code/Mantid/MantidPlot/test/MantidPlotProxiesTest.py b/Code/Mantid/MantidPlot/test/MantidPlotProxiesTest.py index 9c08fd1bcc6e..b1c355684955 100644 --- a/Code/Mantid/MantidPlot/test/MantidPlotProxiesTest.py +++ b/Code/Mantid/MantidPlot/test/MantidPlotProxiesTest.py @@ -121,7 +121,6 @@ def test_closing_MantidMatrix_plotGraph2D(self): mm = importMatrixWorkspace("fake", visible=True) g = mm.plotGraph2D() spec = g.activeLayer().spectrogram() - screenshot(g, "MantidMatrix.plotGraph2D", "Call to MantidMatrix.plotGraph2D() on a workspace.") self.try_closing(mm, "importMatrixWorkspace()") self.assertTrue(g._getHeldObject() is None, "Deleted graph safely when the parent MantidMatrix was deleted") self.assertTrue(spec._getHeldObject() is None, "Deleted spectrogram safely") @@ -135,13 +134,11 @@ def test_closing_MantidMatrix_plotGraph3D(self): def test_closing_getInstrumentView(self): iv = getInstrumentView("IRS26173") - screenshot(iv, "getInstrumentView", "Call to getInstrumentView() on a workspace.") self.try_closing(iv, "getInstrumentView()") def test_convertToWaterfall(self): g = plot(workspace("IRS26173"),(0,1,2,3,4)) convertToWaterfall(g) - screenshot(g, "convertToWaterfall", "Call to convertToWaterfall() on a workspace.") self.try_closing(g, "convertToWaterfall()") def test_dock_method_produces_docked_window_on_matrix(self): diff --git a/Code/Mantid/MantidPlot/test/MantidPlotSliceViewerTest.py b/Code/Mantid/MantidPlot/test/MantidPlotSliceViewerTest.py index 734da230cc4f..a3f7a0e3a8f7 100644 --- a/Code/Mantid/MantidPlot/test/MantidPlotSliceViewerTest.py +++ b/Code/Mantid/MantidPlot/test/MantidPlotSliceViewerTest.py @@ -41,7 +41,6 @@ def test_mouseMove(self): svw = plotSlice('uniform') svw.setSlicePoint(2, 2.5) moveMouseToCentre(svw._getHeldObject()) - screenshot(svw, "SliceViewer", "SliceViewer with mouse at center, showing coordinates.") def test_plotSlice_empty(self): """ Plot slice on an empty workspace """ @@ -68,7 +67,6 @@ def test_plot4D_workspace(self): svw.setSlicePoint(3, 7.5) self.assertAlmostEqual(svw.getSlicePoint(2), 2.5, 3) self.assertAlmostEqual(svw.getSlicePoint(3), 7.5, 3) - screenshot(svw, "SliceViewer_4D", "SliceViewer open to a 4D workspace; z=2.5, e=7.5.") svw.setXYDim("z", "e") self.assertEqual(svw.getDimX(), 2) self.assertEqual(svw.getDimY(), 3) @@ -114,10 +112,12 @@ def test_saveImage(self): dest = get_screenshot_dir() if not dest is None: filename = "SliceViewerSaveImage" - svw.saveImage(os.path.join(dest, filename+".png") ) - # Add to the HTML report - screenshot(None, filename, "SliceViewer: result of saveImage(). Should be only the 2D plot with a color bar (no GUI elements)", - png_exists=True) + filepath = os.path.join(dest, filename+".png") + svw.saveImage(filepath) + self.assertEquals(os.path.isfile(filepath), True, + "Screenshot was not written out as expected.") + if file_exists: + os.remove(filepath) def test_showLine(self): svw = plotSlice('uniform') @@ -133,7 +133,6 @@ def test_showLine(self): self.assertAlmostEqual(liner.getBinWidth(), 0.05, 3) # Width was set self.assertAlmostEqual(liner.getPlanarWidth(), 0.88, 3) - screenshot(svw, "SliceViewer_and_LineViewer", "SliceViewer with LineViewer open, showing line overlay and integrated line.") # Now turn it off svw.toggleLineMode(False) self.assertFalse( liner.isVisible(), "LineViewer was hidden") From e8354ad3233ca8cc5e5eff606c24c0d0ffcfbafd Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Thu, 12 Feb 2015 12:06:53 +0000 Subject: [PATCH 077/414] Move contents of TestingTools to Testing/Tools directory Refs #10870 --- Code/Mantid/Build/CMake/EmbeddedGTest.cmake | 4 +- Code/Mantid/Build/CMake/FindCxxTest.cmake | 4 +- Code/Mantid/Build/CMake/FindGMock.cmake | 4 +- Code/Mantid/Build/CMake/FindPyUnitTest.cmake | 8 +-- Code/Mantid/Framework/CMakeLists.txt | 4 +- .../Mantid/MantidPlot/test/mantidplottests.py | 2 +- .../Tools}/CMakeLists.txt | 0 .../Tools}/cxxtest/COPYING | 0 .../Tools}/cxxtest/README | 0 .../Tools}/cxxtest/TODO | 0 .../Tools}/cxxtest/Versions | 0 .../Tools}/cxxtest/build_tools/SCons/AUTHORS | 0 .../cxxtest/build_tools/SCons/cxxtest.py | 0 .../build_tools/SCons/test/default_env/README | 0 .../SCons/test/default_env/SConstruct | 0 .../SCons/test/default_env/TestDef.py | 0 .../SCons/test/empty_source_list/README | 0 .../SCons/test/empty_source_list/SConstruct | 0 .../SCons/test/empty_source_list/TestDef.py | 0 .../test/empty_source_list/requirement.hpp | 0 .../SCons/test/empty_source_list/test_bar.t.h | 0 .../SCons/test/empty_source_list/test_foo.t.h | 0 .../build_tools/SCons/test/eprouvette.py | 0 .../build_tools/SCons/test/expanding_#/README | 0 .../SCons/test/expanding_#/SConstruct | 0 .../SCons/test/expanding_#/TestDef.py | 0 .../build_tools/SCons/test/globbing/README | 0 .../SCons/test/globbing/SConstruct | 0 .../SCons/test/globbing/TestDef.py | 0 .../SCons/test/globbing/src/requirement.cpp | 0 .../SCons/test/globbing/src/requirement.h | 0 .../SCons/test/globbing/src/test_bar.t.h | 0 .../SCons/test/globbing/src/test_foo.t.h | 0 .../SCons/test/globbing_edmundo/README | 0 .../SCons/test/globbing_edmundo/SConstruct | 0 .../SCons/test/globbing_edmundo/TestDef.py | 0 .../SCons/test/globbing_edmundo/hello.cc | 0 .../SCons/test/globbing_edmundo/hello.hh | 0 .../SCons/test/globbing_edmundo/hellotest.t.h | 0 .../SCons/test/globbing_edmundo/main.cpp | 0 .../SCons/test/include_CCFLAGS/README | 0 .../SCons/test/include_CCFLAGS/SConstruct | 0 .../SCons/test/include_CCFLAGS/TestDef.py | 0 .../include_CCFLAGS/src/not-with-pedantic.h | 0 .../include_CCFLAGS/src/only_with_ansi.t.h | 0 .../SCons/test/include_CXXFLAGS/README | 0 .../SCons/test/include_CXXFLAGS/SConstruct | 0 .../SCons/test/include_CXXFLAGS/TestDef.py | 0 .../include_CXXFLAGS/src/not-with-pedantic.h | 0 .../SCons/test/multifile_tests/SConstruct | 0 .../SCons/test/multifile_tests/TestDef.py | 0 .../test/multifile_tests/src/requirement.cpp | 0 .../test/multifile_tests/src/requirement.h | 0 .../test/multifile_tests/src/test_bar.t.h | 0 .../test/multifile_tests/src/test_foo.t.h | 0 .../SCons/test/need_cpppath/SConstruct | 0 .../SCons/test/need_cpppath/TestDef.py | 0 .../SCons/test/need_cpppath/src/cpppath.t.h | 0 .../need_cpppath/src/cpppathdir/include.h | 0 .../test/nonstandard_cxxtest_dir/SConstruct | 0 .../test/nonstandard_cxxtest_dir/TestDef.py | 0 .../SCons/test/printer_propagation/SConstruct | 0 .../SCons/test/printer_propagation/TestDef.py | 0 .../printer_propagation/cxxtest/CrazyRunner.h | 0 .../test/printer_propagation/src/failtest.t.h | 0 .../SCons/test/recursive_sources/README | 0 .../SCons/test/recursive_sources/SConstruct | 0 .../SCons/test/recursive_sources/TestDef.py | 0 .../recursive_sources/src/requirement.cpp | 0 .../test/recursive_sources/src/requirement.h | 0 .../test/recursive_sources/src/test_bar.t.h | 0 .../test/recursive_sources/src/test_foo.t.h | 0 .../SCons/test/string_cpppath/SConstruct | 0 .../SCons/test/string_cpppath/TestDef.py | 0 .../SCons/test/string_cpppath/src/cpppath.t.h | 0 .../string_cpppath/src/cpppathdir/include.h | 0 .../SCons/test/target_syntax/SConstruct | 0 .../SCons/test/target_syntax/TestDef.py | 0 .../SCons/test/target_syntax/src/cpppath.t.h | 0 .../target_syntax/src/cpppathdir/include.h | 0 .../Tools}/cxxtest/cxxtest.spec | 0 .../Tools}/cxxtest/cxxtest/Descriptions.cpp | 0 .../Tools}/cxxtest/cxxtest/Descriptions.h | 0 .../cxxtest/cxxtest/DummyDescriptions.cpp | 0 .../cxxtest/cxxtest/DummyDescriptions.h | 0 .../Tools}/cxxtest/cxxtest/ErrorFormatter.h | 0 .../Tools}/cxxtest/cxxtest/ErrorPrinter.h | 0 .../Tools}/cxxtest/cxxtest/Flags.h | 0 .../Tools}/cxxtest/cxxtest/GlobalFixture.cpp | 0 .../Tools}/cxxtest/cxxtest/GlobalFixture.h | 0 .../Tools}/cxxtest/cxxtest/Gui.h | 0 .../Tools}/cxxtest/cxxtest/LinkedList.cpp | 0 .../Tools}/cxxtest/cxxtest/LinkedList.h | 0 .../Tools}/cxxtest/cxxtest/MantidFormatter.h | 0 .../Tools}/cxxtest/cxxtest/MantidPrinter.h | 0 .../Tools}/cxxtest/cxxtest/Mock.h | 0 .../Tools}/cxxtest/cxxtest/ParenPrinter.h | 0 .../Tools}/cxxtest/cxxtest/QtGui.h | 0 .../cxxtest/cxxtest/RealDescriptions.cpp | 0 .../Tools}/cxxtest/cxxtest/RealDescriptions.h | 0 .../Tools}/cxxtest/cxxtest/Root.cpp | 0 .../Tools}/cxxtest/cxxtest/SelfTest.h | 0 .../Tools}/cxxtest/cxxtest/StdHeaders.h | 0 .../Tools}/cxxtest/cxxtest/StdTestSuite.h | 0 .../Tools}/cxxtest/cxxtest/StdValueTraits.h | 0 .../Tools}/cxxtest/cxxtest/StdioFilePrinter.h | 0 .../Tools}/cxxtest/cxxtest/StdioPrinter.h | 0 .../Tools}/cxxtest/cxxtest/TeeListener.h | 0 .../Tools}/cxxtest/cxxtest/TestListener.h | 0 .../Tools}/cxxtest/cxxtest/TestMain.h | 0 .../Tools}/cxxtest/cxxtest/TestRunner.h | 0 .../Tools}/cxxtest/cxxtest/TestSuite.cpp | 0 .../Tools}/cxxtest/cxxtest/TestSuite.h | 0 .../Tools}/cxxtest/cxxtest/TestTracker.cpp | 0 .../Tools}/cxxtest/cxxtest/TestTracker.h | 0 .../Tools}/cxxtest/cxxtest/ValueTraits.cpp | 0 .../Tools}/cxxtest/cxxtest/ValueTraits.h | 0 .../Tools}/cxxtest/cxxtest/Win32Gui.h | 0 .../Tools}/cxxtest/cxxtest/WrappedTestSuite.h | 0 .../Tools}/cxxtest/cxxtest/X11Gui.h | 0 .../Tools}/cxxtest/cxxtest/XUnitPrinter.h | 0 .../Tools}/cxxtest/cxxtest/XmlFormatter.h | 0 .../Tools}/cxxtest/cxxtest/XmlPrinter.h | 0 .../Tools}/cxxtest/cxxtest/YesNoRunner.h | 0 .../Tools}/cxxtest/docs/.cvsignore | 0 .../Tools}/cxxtest/docs/Makefile | 0 .../Tools}/cxxtest/docs/convert.pl | 0 .../Tools}/cxxtest/docs/guide.texi | 0 .../Tools}/cxxtest/docs/qt.png | Bin .../Tools}/cxxtest/docs/qt2.png | Bin .../Tools}/cxxtest/docs/texinfo.tex | 0 .../Tools}/cxxtest/docs/win32.png | Bin .../Tools}/cxxtest/docs/x11.png | Bin .../Tools}/cxxtest/get_revision_from_cvs.pl | 0 .../Tools}/cxxtest/python/README.txt | 0 .../Tools}/cxxtest/python/cxxtest/__init__.py | 0 .../cxxtest/python/cxxtest/__release__.py | 0 .../cxxtest/python/cxxtest/cxxtest_misc.py | 0 .../cxxtest/python/cxxtest/cxxtest_parser.py | 0 .../cxxtest/python/cxxtest/cxxtestgen.py | 0 .../Tools}/cxxtest/python/ez_setup.py | 0 .../Tools}/cxxtest/python/scripts/cxxtestgen | 0 .../Tools}/cxxtest/python/setup.py | 0 .../Tools}/cxxtest/sample/.cvsignore | 0 .../Tools}/cxxtest/sample/Construct | 0 .../Tools}/cxxtest/sample/CreatedTest.h | 0 .../Tools}/cxxtest/sample/DeltaTest.h | 0 .../Tools}/cxxtest/sample/EnumTraits.h | 0 .../Tools}/cxxtest/sample/ExceptionTest.h | 0 .../Tools}/cxxtest/sample/FixtureTest.h | 0 .../Tools}/cxxtest/sample/Makefile.PL | 0 .../Tools}/cxxtest/sample/Makefile.bcc32 | 0 .../Tools}/cxxtest/sample/Makefile.msvc | 0 .../Tools}/cxxtest/sample/Makefile.unix | 0 .../Tools}/cxxtest/sample/MessageTest.h | 0 .../Tools}/cxxtest/sample/SCons/SConstruct | 0 .../cxxtest/sample/SCons/include/stack.h | 0 .../Tools}/cxxtest/sample/SCons/src/stack.c | 0 .../cxxtest/sample/SCons/tests/stack_test.h | 0 .../Tools}/cxxtest/sample/SimpleTest.h | 0 .../Tools}/cxxtest/sample/TraitsTest.h | 0 .../Tools}/cxxtest/sample/aborter.tpl | 0 .../Tools}/cxxtest/sample/file_printer.tpl | 0 .../cxxtest/sample/gui/GreenYellowRed.h | 0 .../Tools}/cxxtest/sample/mock/Dice.cpp | 0 .../Tools}/cxxtest/sample/mock/Dice.h | 0 .../Tools}/cxxtest/sample/mock/Makefile | 0 .../Tools}/cxxtest/sample/mock/MockStdlib.h | 0 .../Tools}/cxxtest/sample/mock/T/stdlib.h | 0 .../Tools}/cxxtest/sample/mock/TestDice.h | 0 .../cxxtest/sample/mock/mock_stdlib.cpp | 0 .../cxxtest/sample/mock/real_stdlib.cpp | 0 .../Tools}/cxxtest/sample/mock/roll.cpp | 0 .../cxxtest/sample/msvc/CxxTest_1_Run.dsp | 0 .../cxxtest/sample/msvc/CxxTest_2_Build.dsp | 0 .../sample/msvc/CxxTest_3_Generate.dsp | 0 .../cxxtest/sample/msvc/CxxTest_Workspace.dsw | 0 .../Tools}/cxxtest/sample/msvc/FixFiles.bat | 0 .../Tools}/cxxtest/sample/msvc/Makefile | 0 .../Tools}/cxxtest/sample/msvc/ReadMe.txt | 0 .../Tools}/cxxtest/sample/only.tpl | 0 .../Tools}/cxxtest/sample/parts/.cvsignore | 0 .../Tools}/cxxtest/sample/parts/Makefile.unix | 0 .../Tools}/cxxtest/sample/winddk/Makefile | 0 .../Tools}/cxxtest/sample/winddk/Makefile.inc | 0 .../Tools}/cxxtest/sample/winddk/RunTests.tpl | 0 .../Tools}/cxxtest/sample/winddk/SOURCES | 0 .../Tools}/cxxtest/sample/yes_no_runner.cpp | 0 .../Tools}/cxxtest/test/.cvsignore | 0 .../Tools}/cxxtest/test/AborterNoThrow.h | 0 .../Tools}/cxxtest/test/BadTest.h | 0 .../Tools}/cxxtest/test/Comments.h | 0 .../Tools}/cxxtest/test/DeepAbort.h | 0 .../Tools}/cxxtest/test/DefaultAbort.h | 0 .../Tools}/cxxtest/test/DefaultTraits.h | 0 .../Tools}/cxxtest/test/DoubleCall.h | 0 .../Tools}/cxxtest/test/DynamicAbort.h | 0 .../Tools}/cxxtest/test/DynamicMax.h | 0 .../Tools}/cxxtest/test/EmptySuite.h | 0 .../Tools}/cxxtest/test/Exceptions.h | 0 .../Tools}/cxxtest/test/Factor.h | 0 .../Tools}/cxxtest/test/ForceNoEh.h | 0 .../Tools}/cxxtest/test/GfSetUpFails.h | 0 .../Tools}/cxxtest/test/GfSetUpThrows.h | 0 .../Tools}/cxxtest/test/GfTearDownFails.h | 0 .../Tools}/cxxtest/test/GfTearDownThrows.h | 0 .../Tools}/cxxtest/test/GlobalFixtures.h | 0 .../Tools}/cxxtest/test/GoodSuite.h | 0 .../Tools}/cxxtest/test/GuiWait.h | 0 .../Tools}/cxxtest/test/HaveStd.h | 0 .../Tools}/cxxtest/test/IncludeTest.h | 0 .../Tools}/cxxtest/test/Int64.h | 0 .../Tools}/cxxtest/test/LessThanEquals.h | 0 .../Tools}/cxxtest/test/LongLong.h | 0 .../Tools}/cxxtest/test/LongTraits.h | 0 .../Tools}/cxxtest/test/Makefile | 0 .../Tools}/cxxtest/test/MaxDump.h | 0 .../Tools}/cxxtest/test/MockTest.h | 0 .../Tools}/cxxtest/test/NoEh.h | 0 .../Tools}/cxxtest/test/Part1.h | 0 .../Tools}/cxxtest/test/Part2.h | 0 .../Tools}/cxxtest/test/Relation.h | 0 .../Tools}/cxxtest/test/SameData.h | 0 .../Tools}/cxxtest/test/SameZero.h | 0 .../Tools}/cxxtest/test/SetUpWorldFails.h | 0 .../Tools}/cxxtest/test/SetUpWorldThrows.h | 0 .../Tools}/cxxtest/test/Something.h | 0 .../Tools}/cxxtest/test/StlTraits.h | 0 .../Tools}/cxxtest/test/TearDownWorldFails.h | 0 .../Tools}/cxxtest/test/TearDownWorldThrows.h | 0 .../Tools}/cxxtest/test/ThrowNoStd.h | 0 .../Tools}/cxxtest/test/ThrowNoStd.tpl | 0 .../Tools}/cxxtest/test/ThrowsAssert.h | 0 .../Tools}/cxxtest/test/TraitsTest.h | 0 .../Tools}/cxxtest/test/Tsm.h | 0 .../Tools}/cxxtest/test/UserTraits.h | 0 .../Tools}/cxxtest/test/UserTraits.tpl | 0 .../Tools}/cxxtest/test/VoidTraits.h | 0 .../Tools}/cxxtest/test/WideCharTest.h | 0 .../Tools}/cxxtest/test/WorldFixtures.h | 0 .../Tools}/cxxtest/test/abort.out | 0 .../Tools}/cxxtest/test/activate.tpl | 0 .../Tools}/cxxtest/test/anything.cpp | 0 .../Tools}/cxxtest/test/comments.out | 0 .../Tools}/cxxtest/test/cxxtest/DummyGui.h | 0 .../Tools}/cxxtest/test/default_abort.out | 0 .../Tools}/cxxtest/test/eh_normals.out | 0 .../Tools}/cxxtest/test/error.out | 0 .../Tools}/cxxtest/test/factor.out | 0 .../Tools}/cxxtest/test/fake/.cvsignore | 0 .../Tools}/cxxtest/test/fake/X11/Xlib.h | 0 .../Tools}/cxxtest/test/fake/X11/Xutil.h | 0 .../Tools}/cxxtest/test/fake/commctrl.h | 0 .../Tools}/cxxtest/test/fake/qapplication.h | 0 .../Tools}/cxxtest/test/fake/qglobal.h | 0 .../Tools}/cxxtest/test/fake/qlabel.h | 0 .../Tools}/cxxtest/test/fake/qlayout.h | 0 .../Tools}/cxxtest/test/fake/qmessagebox.h | 0 .../Tools}/cxxtest/test/fake/qpixmap.h | 0 .../Tools}/cxxtest/test/fake/qprogressbar.h | 0 .../Tools}/cxxtest/test/fake/qstatusbar.h | 0 .../Tools}/cxxtest/test/fake/qstring.h | 0 .../Tools}/cxxtest/test/fake/qwidget.h | 0 .../Tools}/cxxtest/test/fake/windows.h | 0 .../Tools}/cxxtest/test/gfsuf.out | 0 .../Tools}/cxxtest/test/gfsut.out | 0 .../Tools}/cxxtest/test/gftdf.out | 0 .../Tools}/cxxtest/test/gftdt.out | 0 .../Tools}/cxxtest/test/gfxs.out | 0 .../Tools}/cxxtest/test/good.out | 0 .../Tools}/cxxtest/test/gui.out | 0 .../Tools}/cxxtest/test/gui_paren.out | 0 .../Tools}/cxxtest/test/include.out | 0 .../Tools}/cxxtest/test/int64.cpp | 0 .../Tools}/cxxtest/test/int64.out | 0 .../Tools}/cxxtest/test/longlong.cpp | 0 .../Tools}/cxxtest/test/longlong.out | 0 .../Tools}/cxxtest/test/main.cpp | 0 .../Tools}/cxxtest/test/max.out | 0 .../Tools}/cxxtest/test/normal.out | 0 .../Tools}/cxxtest/test/paren.out | 0 .../Tools}/cxxtest/test/parts.out | 0 .../Tools}/cxxtest/test/preamble.out | 0 .../Tools}/cxxtest/test/preamble.tpl | 0 .../Tools}/cxxtest/test/runner.out | 0 .../Tools}/cxxtest/test/std.out | 0 .../Tools}/cxxtest/test/stl.out | 0 .../Tools}/cxxtest/test/stpltpl.cpp | 0 .../Tools}/cxxtest/test/suite.out | 0 .../Tools}/cxxtest/test/suite_test.out | 0 .../Tools}/cxxtest/test/suwf.out | 0 .../Tools}/cxxtest/test/suwt.out | 0 .../Tools}/cxxtest/test/tdwf.out | 0 .../Tools}/cxxtest/test/tdwt.out | 0 .../Tools}/cxxtest/test/test.pl | 0 .../Tools}/cxxtest/test/throw.out | 0 .../Tools}/cxxtest/test/tpltpl.cpp | 0 .../cxxtest/test/unit/LinkedList_test.t.h | 0 .../Tools}/cxxtest/test/unit/SConstruct | 0 .../Tools}/cxxtest/test/user.out | 0 .../Tools}/cxxtest/test/wchar.cpp | 0 .../Tools}/cxxtest/test/wchar.out | 0 .../Tools}/cxxtest/test/wildcard.out | 0 .../snippets/HtmlSnippet1.html | 0 .../www/cn-project-pages/snippets/page.xml | 0 .../Tools}/generatetestmain.py | 0 .../Tools}/gmock-1.6.0/CHANGES | 0 .../Tools}/gmock-1.6.0/CMakeLists.txt | 0 .../Tools}/gmock-1.6.0/CONTRIBUTORS | 0 .../Tools}/gmock-1.6.0/COPYING | 0 .../Tools}/gmock-1.6.0/Makefile.am | 0 .../Tools}/gmock-1.6.0/Makefile.in | 0 .../Tools}/gmock-1.6.0/README | 0 .../Tools}/gmock-1.6.0/aclocal.m4 | 0 .../Tools}/gmock-1.6.0/build-aux/config.guess | 0 .../Tools}/gmock-1.6.0/build-aux/config.h.in | 0 .../Tools}/gmock-1.6.0/build-aux/config.sub | 0 .../Tools}/gmock-1.6.0/build-aux/depcomp | 0 .../Tools}/gmock-1.6.0/build-aux/install-sh | 0 .../Tools}/gmock-1.6.0/build-aux/ltmain.sh | 0 .../Tools}/gmock-1.6.0/build-aux/missing | 0 .../Tools}/gmock-1.6.0/configure | 0 .../Tools}/gmock-1.6.0/configure.ac | 0 .../gmock-1.6.0/fused-src/gmock-gtest-all.cc | 0 .../gmock-1.6.0/fused-src/gmock/gmock.h | 0 .../gmock-1.6.0/fused-src/gmock_main.cc | 0 .../gmock-1.6.0/fused-src/gtest/gtest.h | 0 .../Tools}/gmock-1.6.0/gtest/CHANGES | 0 .../Tools}/gmock-1.6.0/gtest/CMakeLists.txt | 0 .../Tools}/gmock-1.6.0/gtest/CONTRIBUTORS | 0 .../Tools}/gmock-1.6.0/gtest/COPYING | 0 .../Tools}/gmock-1.6.0/gtest/Makefile.am | 0 .../Tools}/gmock-1.6.0/gtest/Makefile.in | 0 .../Tools}/gmock-1.6.0/gtest/README | 0 .../Tools}/gmock-1.6.0/gtest/aclocal.m4 | 0 .../gmock-1.6.0/gtest/build-aux/config.guess | 0 .../gmock-1.6.0/gtest/build-aux/config.h.in | 0 .../gmock-1.6.0/gtest/build-aux/config.sub | 0 .../gmock-1.6.0/gtest/build-aux/depcomp | 0 .../gmock-1.6.0/gtest/build-aux/install-sh | 0 .../gmock-1.6.0/gtest/build-aux/ltmain.sh | 0 .../gmock-1.6.0/gtest/build-aux/missing | 0 .../gtest/cmake/internal_utils.cmake | 0 .../gmock-1.6.0/gtest/codegear/gtest.cbproj | 0 .../gtest/codegear/gtest.groupproj | 0 .../gmock-1.6.0/gtest/codegear/gtest_all.cc | 0 .../gmock-1.6.0/gtest/codegear/gtest_link.cc | 0 .../gtest/codegear/gtest_main.cbproj | 0 .../gtest/codegear/gtest_unittest.cbproj | 0 .../Tools}/gmock-1.6.0/gtest/configure | 0 .../Tools}/gmock-1.6.0/gtest/configure.ac | 0 .../gtest/fused-src/gtest/gtest-all.cc | 0 .../gmock-1.6.0/gtest/fused-src/gtest/gtest.h | 0 .../gtest/fused-src/gtest/gtest_main.cc | 0 .../gtest/include/gtest/gtest-death-test.h | 0 .../gtest/include/gtest/gtest-message.h | 0 .../gtest/include/gtest/gtest-param-test.h | 0 .../include/gtest/gtest-param-test.h.pump | 0 .../gtest/include/gtest/gtest-printers.h | 0 .../gtest/include/gtest/gtest-spi.h | 0 .../gtest/include/gtest/gtest-test-part.h | 0 .../gtest/include/gtest/gtest-typed-test.h | 0 .../gmock-1.6.0/gtest/include/gtest/gtest.h | 0 .../gtest/include/gtest/gtest_pred_impl.h | 0 .../gtest/include/gtest/gtest_prod.h | 0 .../internal/gtest-death-test-internal.h | 0 .../include/gtest/internal/gtest-filepath.h | 0 .../include/gtest/internal/gtest-internal.h | 0 .../include/gtest/internal/gtest-linked_ptr.h | 0 .../internal/gtest-param-util-generated.h | 0 .../gtest-param-util-generated.h.pump | 0 .../include/gtest/internal/gtest-param-util.h | 0 .../gtest/include/gtest/internal/gtest-port.h | 0 .../include/gtest/internal/gtest-string.h | 0 .../include/gtest/internal/gtest-tuple.h | 0 .../include/gtest/internal/gtest-tuple.h.pump | 0 .../include/gtest/internal/gtest-type-util.h | 0 .../gtest/internal/gtest-type-util.h.pump | 0 .../gmock-1.6.0/gtest/m4/acx_pthread.m4 | 0 .../Tools}/gmock-1.6.0/gtest/m4/gtest.m4 | 0 .../Tools}/gmock-1.6.0/gtest/m4/libtool.m4 | 0 .../Tools}/gmock-1.6.0/gtest/m4/ltoptions.m4 | 0 .../Tools}/gmock-1.6.0/gtest/m4/ltsugar.m4 | 0 .../Tools}/gmock-1.6.0/gtest/m4/ltversion.m4 | 0 .../gmock-1.6.0/gtest/m4/lt~obsolete.m4 | 0 .../gmock-1.6.0/gtest/msvc/gtest-md.sln | 0 .../gmock-1.6.0/gtest/msvc/gtest-md.vcproj | 0 .../Tools}/gmock-1.6.0/gtest/msvc/gtest.sln | 0 .../gmock-1.6.0/gtest/msvc/gtest.vcproj | 0 .../gtest/msvc/gtest_main-md.vcproj | 0 .../gmock-1.6.0/gtest/msvc/gtest_main.vcproj | 0 .../gtest/msvc/gtest_prod_test-md.vcproj | 0 .../gtest/msvc/gtest_prod_test.vcproj | 0 .../gtest/msvc/gtest_unittest-md.vcproj | 0 .../gtest/msvc/gtest_unittest.vcproj | 0 .../gmock-1.6.0/gtest/samples/prime_tables.h | 0 .../gmock-1.6.0/gtest/samples/sample1.cc | 0 .../gmock-1.6.0/gtest/samples/sample1.h | 0 .../gtest/samples/sample10_unittest.cc | 0 .../gtest/samples/sample1_unittest.cc | 0 .../gmock-1.6.0/gtest/samples/sample2.cc | 0 .../gmock-1.6.0/gtest/samples/sample2.h | 0 .../gtest/samples/sample2_unittest.cc | 0 .../gmock-1.6.0/gtest/samples/sample3-inl.h | 0 .../gtest/samples/sample3_unittest.cc | 0 .../gmock-1.6.0/gtest/samples/sample4.cc | 0 .../gmock-1.6.0/gtest/samples/sample4.h | 0 .../gtest/samples/sample4_unittest.cc | 0 .../gtest/samples/sample5_unittest.cc | 0 .../gtest/samples/sample6_unittest.cc | 0 .../gtest/samples/sample7_unittest.cc | 0 .../gtest/samples/sample8_unittest.cc | 0 .../gtest/samples/sample9_unittest.cc | 0 .../gtest/scripts/fuse_gtest_files.py | 0 .../gtest/scripts/gen_gtest_pred_impl.py | 0 .../gmock-1.6.0/gtest/scripts/gtest-config.in | 0 .../Tools}/gmock-1.6.0/gtest/scripts/pump.py | 0 .../Tools}/gmock-1.6.0/gtest/src/gtest-all.cc | 0 .../gmock-1.6.0/gtest/src/gtest-death-test.cc | 0 .../gmock-1.6.0/gtest/src/gtest-filepath.cc | 0 .../gtest/src/gtest-internal-inl.h | 0 .../gmock-1.6.0/gtest/src/gtest-port.cc | 0 .../gmock-1.6.0/gtest/src/gtest-printers.cc | 0 .../gmock-1.6.0/gtest/src/gtest-test-part.cc | 0 .../gmock-1.6.0/gtest/src/gtest-typed-test.cc | 0 .../Tools}/gmock-1.6.0/gtest/src/gtest.cc | 0 .../gmock-1.6.0/gtest/src/gtest_main.cc | 0 .../gtest/test/gtest-death-test_ex_test.cc | 0 .../gtest/test/gtest-death-test_test.cc | 0 .../gtest/test/gtest-filepath_test.cc | 0 .../gtest/test/gtest-linked_ptr_test.cc | 0 .../gtest/test/gtest-listener_test.cc | 0 .../gtest/test/gtest-message_test.cc | 0 .../gtest/test/gtest-options_test.cc | 0 .../gtest/test/gtest-param-test2_test.cc | 0 .../gtest/test/gtest-param-test_test.cc | 0 .../gtest/test/gtest-param-test_test.h | 0 .../gmock-1.6.0/gtest/test/gtest-port_test.cc | 0 .../gtest/test/gtest-printers_test.cc | 0 .../gtest/test/gtest-test-part_test.cc | 0 .../gtest/test/gtest-tuple_test.cc | 0 .../gtest/test/gtest-typed-test2_test.cc | 0 .../gtest/test/gtest-typed-test_test.cc | 0 .../gtest/test/gtest-typed-test_test.h | 0 .../gtest/test/gtest-unittest-api_test.cc | 0 .../gmock-1.6.0/gtest/test/gtest_all_test.cc | 0 .../test/gtest_break_on_failure_unittest.py | 0 .../test/gtest_break_on_failure_unittest_.cc | 0 .../gtest/test/gtest_catch_exceptions_test.py | 0 .../test/gtest_catch_exceptions_test_.cc | 0 .../gtest/test/gtest_color_test.py | 0 .../gtest/test/gtest_color_test_.cc | 0 .../gtest/test/gtest_env_var_test.py | 0 .../gtest/test/gtest_env_var_test_.cc | 0 .../gtest/test/gtest_environment_test.cc | 0 .../gtest/test/gtest_filter_unittest.py | 0 .../gtest/test/gtest_filter_unittest_.cc | 0 .../gmock-1.6.0/gtest/test/gtest_help_test.py | 0 .../gtest/test/gtest_help_test_.cc | 0 .../gtest/test/gtest_list_tests_unittest.py | 0 .../gtest/test/gtest_list_tests_unittest_.cc | 0 .../gtest/test/gtest_main_unittest.cc | 0 .../gtest/test/gtest_no_test_unittest.cc | 0 .../gtest/test/gtest_output_test.py | 0 .../gtest/test/gtest_output_test_.cc | 0 .../test/gtest_output_test_golden_lin.txt | 0 .../gtest/test/gtest_pred_impl_unittest.cc | 0 .../gmock-1.6.0/gtest/test/gtest_prod_test.cc | 0 .../gtest/test/gtest_repeat_test.cc | 0 .../gtest/test/gtest_shuffle_test.py | 0 .../gtest/test/gtest_shuffle_test_.cc | 0 .../gtest/test/gtest_sole_header_test.cc | 0 .../gtest/test/gtest_stress_test.cc | 0 .../gtest/test/gtest_test_utils.py | 0 .../test/gtest_throw_on_failure_ex_test.cc | 0 .../gtest/test/gtest_throw_on_failure_test.py | 0 .../test/gtest_throw_on_failure_test_.cc | 0 .../gtest/test/gtest_uninitialized_test.py | 0 .../gtest/test/gtest_uninitialized_test_.cc | 0 .../gmock-1.6.0/gtest/test/gtest_unittest.cc | 0 .../gtest/test/gtest_xml_outfile1_test_.cc | 0 .../gtest/test/gtest_xml_outfile2_test_.cc | 0 .../gtest/test/gtest_xml_outfiles_test.py | 0 .../gtest/test/gtest_xml_output_unittest.py | 0 .../gtest/test/gtest_xml_output_unittest_.cc | 0 .../gtest/test/gtest_xml_test_utils.py | 0 .../gmock-1.6.0/gtest/test/production.cc | 0 .../gmock-1.6.0/gtest/test/production.h | 0 .../gtest/xcode/Config/DebugProject.xcconfig | 0 .../xcode/Config/FrameworkTarget.xcconfig | 0 .../gtest/xcode/Config/General.xcconfig | 0 .../xcode/Config/ReleaseProject.xcconfig | 0 .../xcode/Config/StaticLibraryTarget.xcconfig | 0 .../gtest/xcode/Config/TestTarget.xcconfig | 0 .../gtest/xcode/Resources/Info.plist | 0 .../xcode/Samples/FrameworkSample/Info.plist | 0 .../WidgetFramework.xcodeproj/project.pbxproj | 0 .../xcode/Samples/FrameworkSample/runtests.sh | 0 .../xcode/Samples/FrameworkSample/widget.cc | 0 .../xcode/Samples/FrameworkSample/widget.h | 0 .../Samples/FrameworkSample/widget_test.cc | 0 .../gtest/xcode/Scripts/runtests.sh | 0 .../gtest/xcode/Scripts/versiongenerate.py | 0 .../xcode/gtest.xcodeproj/project.pbxproj | 0 .../gmock-1.6.0/include/gmock/gmock-actions.h | 0 .../include/gmock/gmock-cardinalities.h | 0 .../include/gmock/gmock-generated-actions.h | 0 .../gmock/gmock-generated-actions.h.pump | 0 .../gmock/gmock-generated-function-mockers.h | 0 .../gmock-generated-function-mockers.h.pump | 0 .../include/gmock/gmock-generated-matchers.h | 0 .../gmock/gmock-generated-matchers.h.pump | 0 .../gmock/gmock-generated-nice-strict.h | 0 .../gmock/gmock-generated-nice-strict.h.pump | 0 .../include/gmock/gmock-matchers.h | 0 .../include/gmock/gmock-more-actions.h | 0 .../include/gmock/gmock-spec-builders.h | 0 .../Tools}/gmock-1.6.0/include/gmock/gmock.h | 0 .../internal/gmock-generated-internal-utils.h | 0 .../gmock-generated-internal-utils.h.pump | 0 .../gmock/internal/gmock-internal-utils.h | 0 .../include/gmock/internal/gmock-port.h | 0 .../Tools}/gmock-1.6.0/msvc/2005/gmock.sln | 0 .../Tools}/gmock-1.6.0/msvc/2005/gmock.vcproj | 0 .../msvc/2005/gmock_config.vsprops | 0 .../gmock-1.6.0/msvc/2005/gmock_main.vcproj | 0 .../gmock-1.6.0/msvc/2005/gmock_test.vcproj | 0 .../Tools}/gmock-1.6.0/msvc/2010/gmock.sln | 0 .../gmock-1.6.0/msvc/2010/gmock.vcxproj | 0 .../gmock-1.6.0/msvc/2010/gmock_config.props | 0 .../gmock-1.6.0/msvc/2010/gmock_main.vcxproj | 0 .../gmock-1.6.0/msvc/2010/gmock_test.vcxproj | 0 .../gmock-1.6.0/scripts/fuse_gmock_files.py | 0 .../gmock-1.6.0/scripts/generator/COPYING | 0 .../gmock-1.6.0/scripts/generator/README | 0 .../scripts/generator/README.cppclean | 0 .../scripts/generator/cpp/__init__.py | 0 .../gmock-1.6.0/scripts/generator/cpp/ast.py | 0 .../scripts/generator/cpp/gmock_class.py | 0 .../scripts/generator/cpp/keywords.py | 0 .../scripts/generator/cpp/tokenize.py | 0 .../scripts/generator/cpp/utils.py | 0 .../scripts/generator/gmock_gen.py | 0 .../gmock-1.6.0/scripts/gmock-config.in | 0 .../Tools}/gmock-1.6.0/src/gmock-all.cc | 0 .../gmock-1.6.0/src/gmock-cardinalities.cc | 0 .../gmock-1.6.0/src/gmock-internal-utils.cc | 0 .../Tools}/gmock-1.6.0/src/gmock-matchers.cc | 0 .../gmock-1.6.0/src/gmock-spec-builders.cc | 0 .../Tools}/gmock-1.6.0/src/gmock.cc | 0 .../Tools}/gmock-1.6.0/src/gmock_main.cc | 0 .../gmock-1.6.0/test/gmock-actions_test.cc | 0 .../test/gmock-cardinalities_test.cc | 0 .../test/gmock-generated-actions_test.cc | 0 .../gmock-generated-function-mockers_test.cc | 0 .../gmock-generated-internal-utils_test.cc | 0 .../test/gmock-generated-matchers_test.cc | 0 .../test/gmock-internal-utils_test.cc | 0 .../gmock-1.6.0/test/gmock-matchers_test.cc | 0 .../test/gmock-more-actions_test.cc | 0 .../test/gmock-nice-strict_test.cc | 0 .../gmock-1.6.0/test/gmock-port_test.cc | 0 .../test/gmock-spec-builders_test.cc | 0 .../Tools}/gmock-1.6.0/test/gmock_all_test.cc | 0 .../gmock-1.6.0/test/gmock_leak_test.py | 0 .../gmock-1.6.0/test/gmock_leak_test_.cc | 0 .../gmock-1.6.0/test/gmock_link2_test.cc | 0 .../gmock-1.6.0/test/gmock_link_test.cc | 0 .../Tools}/gmock-1.6.0/test/gmock_link_test.h | 0 .../gmock-1.6.0/test/gmock_output_test.py | 0 .../gmock-1.6.0/test/gmock_output_test_.cc | 0 .../test/gmock_output_test_golden.txt | 0 .../Tools}/gmock-1.6.0/test/gmock_test.cc | 0 .../gmock-1.6.0/test/gmock_test_utils.py | 0 .../Tools}/gmock-1.7.0/CHANGES | 0 .../Tools}/gmock-1.7.0/CMakeLists.txt | 0 .../Tools}/gmock-1.7.0/CONTRIBUTORS | 0 .../Tools}/gmock-1.7.0/LICENSE | 0 .../Tools}/gmock-1.7.0/Makefile.am | 0 .../Tools}/gmock-1.7.0/Makefile.in | 0 .../Tools}/gmock-1.7.0/README | 0 .../Tools}/gmock-1.7.0/aclocal.m4 | 0 .../Tools}/gmock-1.7.0/build-aux/config.guess | 0 .../Tools}/gmock-1.7.0/build-aux/config.h.in | 0 .../Tools}/gmock-1.7.0/build-aux/config.sub | 0 .../Tools}/gmock-1.7.0/build-aux/depcomp | 0 .../Tools}/gmock-1.7.0/build-aux/install-sh | 0 .../Tools}/gmock-1.7.0/build-aux/ltmain.sh | 0 .../Tools}/gmock-1.7.0/build-aux/missing | 0 .../Tools}/gmock-1.7.0/configure | 0 .../Tools}/gmock-1.7.0/configure.ac | 0 .../gmock-1.7.0/fused-src/gmock-gtest-all.cc | 0 .../gmock-1.7.0/fused-src/gmock/gmock.h | 0 .../gmock-1.7.0/fused-src/gmock_main.cc | 0 .../gmock-1.7.0/fused-src/gtest/gtest.h | 0 .../Tools}/gmock-1.7.0/gtest/CHANGES | 0 .../Tools}/gmock-1.7.0/gtest/CMakeLists.txt | 0 .../Tools}/gmock-1.7.0/gtest/CONTRIBUTORS | 0 .../Tools}/gmock-1.7.0/gtest/LICENSE | 0 .../Tools}/gmock-1.7.0/gtest/Makefile.am | 0 .../Tools}/gmock-1.7.0/gtest/Makefile.in | 0 .../Tools}/gmock-1.7.0/gtest/README | 0 .../Tools}/gmock-1.7.0/gtest/aclocal.m4 | 0 .../gmock-1.7.0/gtest/build-aux/config.guess | 0 .../gmock-1.7.0/gtest/build-aux/config.h.in | 0 .../gmock-1.7.0/gtest/build-aux/config.sub | 0 .../gmock-1.7.0/gtest/build-aux/depcomp | 0 .../gmock-1.7.0/gtest/build-aux/install-sh | 0 .../gmock-1.7.0/gtest/build-aux/ltmain.sh | 0 .../gmock-1.7.0/gtest/build-aux/missing | 0 .../gtest/cmake/internal_utils.cmake | 0 .../gmock-1.7.0/gtest/codegear/gtest.cbproj | 0 .../gtest/codegear/gtest.groupproj | 0 .../gmock-1.7.0/gtest/codegear/gtest_all.cc | 0 .../gmock-1.7.0/gtest/codegear/gtest_link.cc | 0 .../gtest/codegear/gtest_main.cbproj | 0 .../gtest/codegear/gtest_unittest.cbproj | 0 .../Tools}/gmock-1.7.0/gtest/configure | 0 .../Tools}/gmock-1.7.0/gtest/configure.ac | 0 .../gtest/fused-src/gtest/gtest-all.cc | 0 .../gmock-1.7.0/gtest/fused-src/gtest/gtest.h | 0 .../gtest/fused-src/gtest/gtest_main.cc | 0 .../gtest/include/gtest/gtest-death-test.h | 0 .../gtest/include/gtest/gtest-message.h | 0 .../gtest/include/gtest/gtest-param-test.h | 0 .../include/gtest/gtest-param-test.h.pump | 0 .../gtest/include/gtest/gtest-printers.h | 0 .../gtest/include/gtest/gtest-spi.h | 0 .../gtest/include/gtest/gtest-test-part.h | 0 .../gtest/include/gtest/gtest-typed-test.h | 0 .../gmock-1.7.0/gtest/include/gtest/gtest.h | 0 .../gtest/include/gtest/gtest_pred_impl.h | 0 .../gtest/include/gtest/gtest_prod.h | 0 .../internal/gtest-death-test-internal.h | 0 .../include/gtest/internal/gtest-filepath.h | 0 .../include/gtest/internal/gtest-internal.h | 0 .../include/gtest/internal/gtest-linked_ptr.h | 0 .../internal/gtest-param-util-generated.h | 0 .../gtest-param-util-generated.h.pump | 0 .../include/gtest/internal/gtest-param-util.h | 0 .../gtest/include/gtest/internal/gtest-port.h | 0 .../include/gtest/internal/gtest-string.h | 0 .../include/gtest/internal/gtest-tuple.h | 0 .../include/gtest/internal/gtest-tuple.h.pump | 0 .../include/gtest/internal/gtest-type-util.h | 0 .../gtest/internal/gtest-type-util.h.pump | 0 .../gmock-1.7.0/gtest/m4/acx_pthread.m4 | 0 .../Tools}/gmock-1.7.0/gtest/m4/gtest.m4 | 0 .../Tools}/gmock-1.7.0/gtest/m4/libtool.m4 | 0 .../Tools}/gmock-1.7.0/gtest/m4/ltoptions.m4 | 0 .../Tools}/gmock-1.7.0/gtest/m4/ltsugar.m4 | 0 .../Tools}/gmock-1.7.0/gtest/m4/ltversion.m4 | 0 .../gmock-1.7.0/gtest/m4/lt~obsolete.m4 | 0 .../gmock-1.7.0/gtest/samples/prime_tables.h | 0 .../gmock-1.7.0/gtest/samples/sample1.cc | 0 .../gmock-1.7.0/gtest/samples/sample1.h | 0 .../gtest/samples/sample10_unittest.cc | 0 .../gtest/samples/sample1_unittest.cc | 0 .../gmock-1.7.0/gtest/samples/sample2.cc | 0 .../gmock-1.7.0/gtest/samples/sample2.h | 0 .../gtest/samples/sample2_unittest.cc | 0 .../gmock-1.7.0/gtest/samples/sample3-inl.h | 0 .../gtest/samples/sample3_unittest.cc | 0 .../gmock-1.7.0/gtest/samples/sample4.cc | 0 .../gmock-1.7.0/gtest/samples/sample4.h | 0 .../gtest/samples/sample4_unittest.cc | 0 .../gtest/samples/sample5_unittest.cc | 0 .../gtest/samples/sample6_unittest.cc | 0 .../gtest/samples/sample7_unittest.cc | 0 .../gtest/samples/sample8_unittest.cc | 0 .../gtest/samples/sample9_unittest.cc | 0 .../gtest/scripts/fuse_gtest_files.py | 0 .../gtest/scripts/gen_gtest_pred_impl.py | 0 .../gmock-1.7.0/gtest/scripts/gtest-config.in | 0 .../Tools}/gmock-1.7.0/gtest/scripts/pump.py | 0 .../Tools}/gmock-1.7.0/gtest/src/gtest-all.cc | 0 .../gmock-1.7.0/gtest/src/gtest-death-test.cc | 0 .../gmock-1.7.0/gtest/src/gtest-filepath.cc | 0 .../gtest/src/gtest-internal-inl.h | 0 .../gmock-1.7.0/gtest/src/gtest-port.cc | 0 .../gmock-1.7.0/gtest/src/gtest-printers.cc | 0 .../gmock-1.7.0/gtest/src/gtest-test-part.cc | 0 .../gmock-1.7.0/gtest/src/gtest-typed-test.cc | 0 .../Tools}/gmock-1.7.0/gtest/src/gtest.cc | 0 .../gmock-1.7.0/gtest/src/gtest_main.cc | 0 .../gtest/test/gtest-death-test_ex_test.cc | 0 .../gtest/test/gtest-death-test_test.cc | 0 .../gtest/test/gtest-filepath_test.cc | 0 .../gtest/test/gtest-linked_ptr_test.cc | 0 .../gtest/test/gtest-listener_test.cc | 0 .../gtest/test/gtest-message_test.cc | 0 .../gtest/test/gtest-options_test.cc | 0 .../gtest/test/gtest-param-test2_test.cc | 0 .../gtest/test/gtest-param-test_test.cc | 0 .../gtest/test/gtest-param-test_test.h | 0 .../gmock-1.7.0/gtest/test/gtest-port_test.cc | 0 .../gtest/test/gtest-printers_test.cc | 0 .../gtest/test/gtest-test-part_test.cc | 0 .../gtest/test/gtest-tuple_test.cc | 0 .../gtest/test/gtest-typed-test2_test.cc | 0 .../gtest/test/gtest-typed-test_test.cc | 0 .../gtest/test/gtest-typed-test_test.h | 0 .../gtest/test/gtest-unittest-api_test.cc | 0 .../gmock-1.7.0/gtest/test/gtest_all_test.cc | 0 .../test/gtest_break_on_failure_unittest.py | 0 .../test/gtest_break_on_failure_unittest_.cc | 0 .../gtest/test/gtest_catch_exceptions_test.py | 0 .../test/gtest_catch_exceptions_test_.cc | 0 .../gtest/test/gtest_color_test.py | 0 .../gtest/test/gtest_color_test_.cc | 0 .../gtest/test/gtest_env_var_test.py | 0 .../gtest/test/gtest_env_var_test_.cc | 0 .../gtest/test/gtest_environment_test.cc | 0 .../gtest/test/gtest_filter_unittest.py | 0 .../gtest/test/gtest_filter_unittest_.cc | 0 .../gmock-1.7.0/gtest/test/gtest_help_test.py | 0 .../gtest/test/gtest_help_test_.cc | 0 .../gtest/test/gtest_list_tests_unittest.py | 0 .../gtest/test/gtest_list_tests_unittest_.cc | 0 .../gtest/test/gtest_main_unittest.cc | 0 .../gtest/test/gtest_no_test_unittest.cc | 0 .../gtest/test/gtest_output_test.py | 0 .../gtest/test/gtest_output_test_.cc | 0 .../test/gtest_output_test_golden_lin.txt | 0 .../gtest/test/gtest_pred_impl_unittest.cc | 0 .../gtest/test/gtest_premature_exit_test.cc | 0 .../gmock-1.7.0/gtest/test/gtest_prod_test.cc | 0 .../gtest/test/gtest_repeat_test.cc | 0 .../gtest/test/gtest_shuffle_test.py | 0 .../gtest/test/gtest_shuffle_test_.cc | 0 .../gtest/test/gtest_sole_header_test.cc | 0 .../gtest/test/gtest_stress_test.cc | 0 .../gtest/test/gtest_test_utils.py | 0 .../test/gtest_throw_on_failure_ex_test.cc | 0 .../gtest/test/gtest_throw_on_failure_test.py | 0 .../test/gtest_throw_on_failure_test_.cc | 0 .../gtest/test/gtest_uninitialized_test.py | 0 .../gtest/test/gtest_uninitialized_test_.cc | 0 .../gmock-1.7.0/gtest/test/gtest_unittest.cc | 0 .../gtest/test/gtest_xml_outfile1_test_.cc | 0 .../gtest/test/gtest_xml_outfile2_test_.cc | 0 .../gtest/test/gtest_xml_outfiles_test.py | 0 .../gtest/test/gtest_xml_output_unittest.py | 0 .../gtest/test/gtest_xml_output_unittest_.cc | 0 .../gtest/test/gtest_xml_test_utils.py | 0 .../gmock-1.7.0/gtest/test/production.cc | 0 .../gmock-1.7.0/gtest/test/production.h | 0 .../gtest/xcode/Config/DebugProject.xcconfig | 0 .../xcode/Config/FrameworkTarget.xcconfig | 0 .../gtest/xcode/Config/General.xcconfig | 0 .../xcode/Config/ReleaseProject.xcconfig | 0 .../xcode/Config/StaticLibraryTarget.xcconfig | 0 .../gtest/xcode/Config/TestTarget.xcconfig | 0 .../gtest/xcode/Resources/Info.plist | 0 .../xcode/Samples/FrameworkSample/Info.plist | 0 .../WidgetFramework.xcodeproj/project.pbxproj | 0 .../xcode/Samples/FrameworkSample/runtests.sh | 0 .../xcode/Samples/FrameworkSample/widget.cc | 0 .../xcode/Samples/FrameworkSample/widget.h | 0 .../Samples/FrameworkSample/widget_test.cc | 0 .../gtest/xcode/Scripts/runtests.sh | 0 .../gtest/xcode/Scripts/versiongenerate.py | 0 .../xcode/gtest.xcodeproj/project.pbxproj | 0 .../gmock-1.7.0/include/gmock/gmock-actions.h | 0 .../include/gmock/gmock-cardinalities.h | 0 .../include/gmock/gmock-generated-actions.h | 0 .../gmock/gmock-generated-actions.h.pump | 0 .../gmock/gmock-generated-function-mockers.h | 0 .../gmock-generated-function-mockers.h.pump | 0 .../include/gmock/gmock-generated-matchers.h | 0 .../gmock/gmock-generated-matchers.h.pump | 0 .../gmock/gmock-generated-nice-strict.h | 0 .../gmock/gmock-generated-nice-strict.h.pump | 0 .../include/gmock/gmock-matchers.h | 0 .../include/gmock/gmock-more-actions.h | 0 .../include/gmock/gmock-more-matchers.h | 0 .../include/gmock/gmock-spec-builders.h | 0 .../Tools}/gmock-1.7.0/include/gmock/gmock.h | 0 .../internal/gmock-generated-internal-utils.h | 0 .../gmock-generated-internal-utils.h.pump | 0 .../gmock/internal/gmock-internal-utils.h | 0 .../include/gmock/internal/gmock-port.h | 0 .../msvc/2005/gmock_config.vsprops | 0 .../gmock-1.7.0/msvc/2010/gmock_config.props | 0 .../gmock-1.7.0/scripts/fuse_gmock_files.py | 0 .../gmock-1.7.0/scripts/generator/LICENSE | 0 .../gmock-1.7.0/scripts/generator/README | 0 .../scripts/generator/README.cppclean | 0 .../scripts/generator/cpp/__init__.py | 0 .../gmock-1.7.0/scripts/generator/cpp/ast.py | 0 .../scripts/generator/cpp/gmock_class.py | 0 .../scripts/generator/cpp/keywords.py | 0 .../scripts/generator/cpp/tokenize.py | 0 .../scripts/generator/cpp/utils.py | 0 .../scripts/generator/gmock_gen.py | 0 .../gmock-1.7.0/scripts/gmock-config.in | 0 .../Tools}/gmock-1.7.0/src/gmock-all.cc | 0 .../gmock-1.7.0/src/gmock-cardinalities.cc | 0 .../gmock-1.7.0/src/gmock-internal-utils.cc | 0 .../Tools}/gmock-1.7.0/src/gmock-matchers.cc | 0 .../gmock-1.7.0/src/gmock-spec-builders.cc | 0 .../Tools}/gmock-1.7.0/src/gmock.cc | 0 .../Tools}/gmock-1.7.0/src/gmock_main.cc | 0 .../gmock-1.7.0/test/gmock-actions_test.cc | 0 .../test/gmock-cardinalities_test.cc | 0 .../test/gmock-generated-actions_test.cc | 0 .../gmock-generated-function-mockers_test.cc | 0 .../gmock-generated-internal-utils_test.cc | 0 .../test/gmock-generated-matchers_test.cc | 0 .../test/gmock-internal-utils_test.cc | 0 .../gmock-1.7.0/test/gmock-matchers_test.cc | 0 .../test/gmock-more-actions_test.cc | 0 .../test/gmock-nice-strict_test.cc | 0 .../gmock-1.7.0/test/gmock-port_test.cc | 0 .../test/gmock-spec-builders_test.cc | 0 .../Tools}/gmock-1.7.0/test/gmock_all_test.cc | 0 .../Tools}/gmock-1.7.0/test/gmock_ex_test.cc | 0 .../gmock-1.7.0/test/gmock_leak_test.py | 0 .../gmock-1.7.0/test/gmock_leak_test_.cc | 0 .../gmock-1.7.0/test/gmock_link2_test.cc | 0 .../gmock-1.7.0/test/gmock_link_test.cc | 0 .../Tools}/gmock-1.7.0/test/gmock_link_test.h | 0 .../gmock-1.7.0/test/gmock_output_test.py | 0 .../gmock-1.7.0/test/gmock_output_test_.cc | 0 .../test/gmock_output_test_golden.txt | 0 .../gmock-1.7.0/test/gmock_stress_test.cc | 0 .../Tools}/gmock-1.7.0/test/gmock_test.cc | 0 .../gmock-1.7.0/test/gmock_test_utils.py | 0 .../Tools}/pyunit_gen/pyunit_gen.py | 0 .../Tools}/unittest-xml-reporting/LICENSE | 0 .../Tools}/unittest-xml-reporting/MANIFEST.in | 0 .../Tools}/unittest-xml-reporting/README.rst | 0 .../Tools}/unittest-xml-reporting/fabfile.py | 0 .../Tools}/unittest-xml-reporting/setup.py | 0 .../src/xmlrunner/__init__.py | 0 .../src/xmlrunner/extra/__init__.py | 0 .../src/xmlrunner/extra/djangotestrunner.py | 0 .../src/xmlrunner/tests/__init__.py | 0 .../tests/fixtures/errord_test_case.xml | 0 .../tests/fixtures/failed_test_case.xml | 0 .../tests/fixtures/mixed_test_case.xml | 0 .../tests/fixtures/successful_test_case.xml | 0 .../src/xmlrunner/tests/testsuite.py | 0 .../src/xmlrunner/tests/testsuite_cases.py | 0 Code/Mantid/Vates/VatesAPI/test/runTests.sh | 55 ------------------ 845 files changed, 12 insertions(+), 69 deletions(-) rename Code/Mantid/{TestingTools => Testing/Tools}/CMakeLists.txt (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/COPYING (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/TODO (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/Versions (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/AUTHORS (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/cxxtest.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/default_env/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/default_env/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/default_env/TestDef.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/empty_source_list/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/empty_source_list/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/empty_source_list/TestDef.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/empty_source_list/requirement.hpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/empty_source_list/test_bar.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/empty_source_list/test_foo.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/eprouvette.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/expanding_#/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/expanding_#/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/expanding_#/TestDef.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/globbing/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/globbing/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/globbing/TestDef.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/globbing/src/requirement.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/globbing/src/requirement.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/globbing/src/test_bar.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/globbing/src/test_foo.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/globbing_edmundo/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/globbing_edmundo/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/globbing_edmundo/TestDef.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.hh (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/globbing_edmundo/hellotest.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/globbing_edmundo/main.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/include_CCFLAGS/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/include_CCFLAGS/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/include_CCFLAGS/TestDef.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/not-with-pedantic.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/only_with_ansi.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/include_CXXFLAGS/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/include_CXXFLAGS/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/include_CXXFLAGS/TestDef.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/include_CXXFLAGS/src/not-with-pedantic.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/multifile_tests/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/multifile_tests/TestDef.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/multifile_tests/src/test_bar.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/multifile_tests/src/test_foo.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/need_cpppath/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/need_cpppath/TestDef.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppath.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppathdir/include.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/TestDef.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/printer_propagation/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/printer_propagation/TestDef.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/printer_propagation/cxxtest/CrazyRunner.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/printer_propagation/src/failtest.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/recursive_sources/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/recursive_sources/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/recursive_sources/TestDef.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/recursive_sources/src/test_bar.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/recursive_sources/src/test_foo.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/string_cpppath/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/string_cpppath/TestDef.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppath.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppathdir/include.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/target_syntax/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/target_syntax/TestDef.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/target_syntax/src/cpppath.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/build_tools/SCons/test/target_syntax/src/cpppathdir/include.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest.spec (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/Descriptions.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/Descriptions.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/DummyDescriptions.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/DummyDescriptions.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/ErrorFormatter.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/ErrorPrinter.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/Flags.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/GlobalFixture.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/GlobalFixture.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/Gui.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/LinkedList.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/LinkedList.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/MantidFormatter.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/MantidPrinter.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/Mock.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/ParenPrinter.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/QtGui.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/RealDescriptions.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/RealDescriptions.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/Root.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/SelfTest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/StdHeaders.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/StdTestSuite.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/StdValueTraits.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/StdioFilePrinter.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/StdioPrinter.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/TeeListener.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/TestListener.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/TestMain.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/TestRunner.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/TestSuite.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/TestSuite.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/TestTracker.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/TestTracker.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/ValueTraits.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/ValueTraits.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/Win32Gui.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/WrappedTestSuite.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/X11Gui.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/XUnitPrinter.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/XmlFormatter.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/XmlPrinter.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/cxxtest/YesNoRunner.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/docs/.cvsignore (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/docs/Makefile (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/docs/convert.pl (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/docs/guide.texi (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/docs/qt.png (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/docs/qt2.png (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/docs/texinfo.tex (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/docs/win32.png (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/docs/x11.png (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/get_revision_from_cvs.pl (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/python/README.txt (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/python/cxxtest/__init__.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/python/cxxtest/__release__.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/python/cxxtest/cxxtest_misc.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/python/cxxtest/cxxtest_parser.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/python/cxxtest/cxxtestgen.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/python/ez_setup.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/python/scripts/cxxtestgen (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/python/setup.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/.cvsignore (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/Construct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/CreatedTest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/DeltaTest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/EnumTraits.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/ExceptionTest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/FixtureTest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/Makefile.PL (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/Makefile.bcc32 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/Makefile.msvc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/Makefile.unix (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/MessageTest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/SCons/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/SCons/include/stack.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/SCons/src/stack.c (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/SCons/tests/stack_test.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/SimpleTest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/TraitsTest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/aborter.tpl (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/file_printer.tpl (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/gui/GreenYellowRed.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/mock/Dice.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/mock/Dice.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/mock/Makefile (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/mock/MockStdlib.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/mock/T/stdlib.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/mock/TestDice.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/mock/mock_stdlib.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/mock/real_stdlib.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/mock/roll.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/msvc/CxxTest_1_Run.dsp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/msvc/CxxTest_2_Build.dsp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/msvc/CxxTest_3_Generate.dsp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/msvc/CxxTest_Workspace.dsw (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/msvc/FixFiles.bat (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/msvc/Makefile (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/msvc/ReadMe.txt (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/only.tpl (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/parts/.cvsignore (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/parts/Makefile.unix (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/winddk/Makefile (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/winddk/Makefile.inc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/winddk/RunTests.tpl (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/winddk/SOURCES (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/sample/yes_no_runner.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/.cvsignore (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/AborterNoThrow.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/BadTest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/Comments.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/DeepAbort.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/DefaultAbort.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/DefaultTraits.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/DoubleCall.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/DynamicAbort.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/DynamicMax.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/EmptySuite.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/Exceptions.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/Factor.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/ForceNoEh.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/GfSetUpFails.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/GfSetUpThrows.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/GfTearDownFails.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/GfTearDownThrows.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/GlobalFixtures.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/GoodSuite.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/GuiWait.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/HaveStd.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/IncludeTest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/Int64.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/LessThanEquals.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/LongLong.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/LongTraits.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/Makefile (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/MaxDump.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/MockTest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/NoEh.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/Part1.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/Part2.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/Relation.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/SameData.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/SameZero.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/SetUpWorldFails.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/SetUpWorldThrows.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/Something.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/StlTraits.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/TearDownWorldFails.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/TearDownWorldThrows.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/ThrowNoStd.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/ThrowNoStd.tpl (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/ThrowsAssert.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/TraitsTest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/Tsm.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/UserTraits.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/UserTraits.tpl (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/VoidTraits.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/WideCharTest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/WorldFixtures.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/abort.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/activate.tpl (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/anything.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/comments.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/cxxtest/DummyGui.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/default_abort.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/eh_normals.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/error.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/factor.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/.cvsignore (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/X11/Xlib.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/X11/Xutil.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/commctrl.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/qapplication.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/qglobal.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/qlabel.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/qlayout.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/qmessagebox.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/qpixmap.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/qprogressbar.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/qstatusbar.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/qstring.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/qwidget.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/fake/windows.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/gfsuf.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/gfsut.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/gftdf.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/gftdt.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/gfxs.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/good.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/gui.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/gui_paren.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/include.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/int64.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/int64.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/longlong.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/longlong.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/main.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/max.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/normal.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/paren.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/parts.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/preamble.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/preamble.tpl (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/runner.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/std.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/stl.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/stpltpl.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/suite.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/suite_test.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/suwf.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/suwt.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/tdwf.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/tdwt.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/test.pl (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/throw.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/tpltpl.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/unit/LinkedList_test.t.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/unit/SConstruct (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/user.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/wchar.cpp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/wchar.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/test/wildcard.out (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/www/cn-project-pages/snippets/HtmlSnippet1.html (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/cxxtest/www/cn-project-pages/snippets/page.xml (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/generatetestmain.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/CHANGES (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/CMakeLists.txt (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/CONTRIBUTORS (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/COPYING (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/Makefile.am (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/Makefile.in (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/aclocal.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/build-aux/config.guess (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/build-aux/config.h.in (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/build-aux/config.sub (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/build-aux/depcomp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/build-aux/install-sh (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/build-aux/ltmain.sh (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/build-aux/missing (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/configure (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/configure.ac (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/fused-src/gmock-gtest-all.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/fused-src/gmock/gmock.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/fused-src/gmock_main.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/fused-src/gtest/gtest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/CHANGES (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/CMakeLists.txt (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/CONTRIBUTORS (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/COPYING (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/Makefile.am (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/Makefile.in (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/aclocal.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/build-aux/config.guess (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/build-aux/config.h.in (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/build-aux/config.sub (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/build-aux/depcomp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/build-aux/install-sh (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/build-aux/ltmain.sh (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/build-aux/missing (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/cmake/internal_utils.cmake (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/codegear/gtest.cbproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/codegear/gtest.groupproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/codegear/gtest_all.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/codegear/gtest_link.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/codegear/gtest_main.cbproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/codegear/gtest_unittest.cbproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/configure (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/configure.ac (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/fused-src/gtest/gtest-all.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/fused-src/gtest/gtest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/fused-src/gtest/gtest_main.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/gtest-death-test.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/gtest-message.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/gtest-printers.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/gtest-spi.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/gtest-test-part.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/gtest-typed-test.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/gtest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/gtest_pred_impl.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/gtest_prod.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/internal/gtest-death-test-internal.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/internal/gtest-filepath.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/internal/gtest-internal.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/internal/gtest-linked_ptr.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/internal/gtest-port.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/internal/gtest-string.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/m4/acx_pthread.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/m4/gtest.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/m4/libtool.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/m4/ltoptions.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/m4/ltsugar.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/m4/ltversion.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/m4/lt~obsolete.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/msvc/gtest-md.sln (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/msvc/gtest-md.vcproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/msvc/gtest.sln (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/msvc/gtest.vcproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/msvc/gtest_main-md.vcproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/msvc/gtest_main.vcproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/msvc/gtest_prod_test-md.vcproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/msvc/gtest_prod_test.vcproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/msvc/gtest_unittest-md.vcproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/msvc/gtest_unittest.vcproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/prime_tables.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample1.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample1.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample10_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample1_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample2.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample2.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample2_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample3-inl.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample3_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample4.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample4.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample4_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample5_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample6_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample7_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample8_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/samples/sample9_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/scripts/fuse_gtest_files.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/scripts/gen_gtest_pred_impl.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/scripts/gtest-config.in (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/scripts/pump.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/src/gtest-all.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/src/gtest-death-test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/src/gtest-filepath.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/src/gtest-internal-inl.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/src/gtest-port.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/src/gtest-printers.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/src/gtest-test-part.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/src/gtest-typed-test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/src/gtest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/src/gtest_main.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-death-test_ex_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-death-test_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-filepath_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-linked_ptr_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-listener_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-message_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-options_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-param-test2_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-param-test_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-param-test_test.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-port_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-printers_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-test-part_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-tuple_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-typed-test2_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-typed-test_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-typed-test_test.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest-unittest-api_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_all_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_color_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_color_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_env_var_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_env_var_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_environment_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_filter_unittest.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_filter_unittest_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_help_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_help_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_list_tests_unittest.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_list_tests_unittest_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_main_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_no_test_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_output_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_output_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_output_test_golden_lin.txt (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_pred_impl_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_prod_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_repeat_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_shuffle_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_shuffle_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_sole_header_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_stress_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_test_utils.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_throw_on_failure_ex_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_uninitialized_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_uninitialized_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_xml_outfile1_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_xml_outfile2_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_xml_outfiles_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_xml_output_unittest.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_xml_output_unittest_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/gtest_xml_test_utils.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/production.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/test/production.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Config/DebugProject.xcconfig (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Config/FrameworkTarget.xcconfig (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Config/General.xcconfig (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Config/ReleaseProject.xcconfig (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Config/TestTarget.xcconfig (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Resources/Info.plist (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/Info.plist (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/runtests.sh (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Scripts/runtests.sh (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/Scripts/versiongenerate.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/gtest/xcode/gtest.xcodeproj/project.pbxproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/gmock-actions.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/gmock-cardinalities.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/gmock-generated-actions.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/gmock-generated-actions.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/gmock-generated-matchers.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/gmock-generated-matchers.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/gmock-matchers.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/gmock-more-actions.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/gmock-spec-builders.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/gmock.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/internal/gmock-internal-utils.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/include/gmock/internal/gmock-port.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/msvc/2005/gmock.sln (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/msvc/2005/gmock.vcproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/msvc/2005/gmock_config.vsprops (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/msvc/2005/gmock_main.vcproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/msvc/2005/gmock_test.vcproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/msvc/2010/gmock.sln (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/msvc/2010/gmock.vcxproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/msvc/2010/gmock_config.props (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/msvc/2010/gmock_main.vcxproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/msvc/2010/gmock_test.vcxproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/scripts/fuse_gmock_files.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/scripts/generator/COPYING (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/scripts/generator/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/scripts/generator/README.cppclean (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/scripts/generator/cpp/__init__.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/scripts/generator/cpp/ast.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/scripts/generator/cpp/gmock_class.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/scripts/generator/cpp/keywords.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/scripts/generator/cpp/tokenize.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/scripts/generator/cpp/utils.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/scripts/generator/gmock_gen.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/scripts/gmock-config.in (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/src/gmock-all.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/src/gmock-cardinalities.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/src/gmock-internal-utils.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/src/gmock-matchers.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/src/gmock-spec-builders.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/src/gmock.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/src/gmock_main.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock-actions_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock-cardinalities_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock-generated-actions_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock-generated-function-mockers_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock-generated-internal-utils_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock-generated-matchers_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock-internal-utils_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock-matchers_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock-more-actions_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock-nice-strict_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock-port_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock-spec-builders_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock_all_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock_leak_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock_leak_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock_link2_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock_link_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock_link_test.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock_output_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock_output_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock_output_test_golden.txt (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.6.0/test/gmock_test_utils.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/CHANGES (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/CMakeLists.txt (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/CONTRIBUTORS (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/LICENSE (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/Makefile.am (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/Makefile.in (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/aclocal.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/build-aux/config.guess (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/build-aux/config.h.in (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/build-aux/config.sub (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/build-aux/depcomp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/build-aux/install-sh (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/build-aux/ltmain.sh (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/build-aux/missing (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/configure (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/configure.ac (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/fused-src/gmock-gtest-all.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/fused-src/gmock/gmock.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/fused-src/gmock_main.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/fused-src/gtest/gtest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/CHANGES (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/CMakeLists.txt (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/CONTRIBUTORS (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/LICENSE (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/Makefile.am (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/Makefile.in (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/aclocal.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/build-aux/config.guess (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/build-aux/config.h.in (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/build-aux/config.sub (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/build-aux/depcomp (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/build-aux/install-sh (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/build-aux/ltmain.sh (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/build-aux/missing (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/cmake/internal_utils.cmake (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/codegear/gtest.cbproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/codegear/gtest.groupproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/codegear/gtest_all.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/codegear/gtest_link.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/codegear/gtest_main.cbproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/codegear/gtest_unittest.cbproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/configure (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/configure.ac (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/fused-src/gtest/gtest-all.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/fused-src/gtest/gtest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/fused-src/gtest/gtest_main.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/gtest-death-test.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/gtest-message.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/gtest-printers.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/gtest-spi.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/gtest-test-part.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/gtest-typed-test.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/gtest.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/gtest_pred_impl.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/gtest_prod.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/internal/gtest-death-test-internal.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/internal/gtest-filepath.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/internal/gtest-internal.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/internal/gtest-linked_ptr.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/internal/gtest-port.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/internal/gtest-string.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/m4/acx_pthread.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/m4/gtest.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/m4/libtool.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/m4/ltoptions.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/m4/ltsugar.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/m4/ltversion.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/m4/lt~obsolete.m4 (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/prime_tables.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample1.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample1.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample10_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample1_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample2.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample2.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample2_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample3-inl.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample3_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample4.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample4.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample4_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample5_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample6_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample7_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample8_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/samples/sample9_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/scripts/fuse_gtest_files.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/scripts/gen_gtest_pred_impl.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/scripts/gtest-config.in (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/scripts/pump.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/src/gtest-all.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/src/gtest-death-test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/src/gtest-filepath.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/src/gtest-internal-inl.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/src/gtest-port.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/src/gtest-printers.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/src/gtest-test-part.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/src/gtest-typed-test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/src/gtest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/src/gtest_main.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-death-test_ex_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-death-test_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-filepath_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-linked_ptr_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-listener_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-message_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-options_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-param-test2_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-param-test_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-param-test_test.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-port_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-printers_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-test-part_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-tuple_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-typed-test2_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-typed-test_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-typed-test_test.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest-unittest-api_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_all_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_color_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_color_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_env_var_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_env_var_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_environment_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_filter_unittest.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_filter_unittest_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_help_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_help_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_list_tests_unittest.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_list_tests_unittest_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_main_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_no_test_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_output_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_output_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_output_test_golden_lin.txt (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_pred_impl_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_premature_exit_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_prod_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_repeat_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_shuffle_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_shuffle_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_sole_header_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_stress_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_test_utils.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_throw_on_failure_ex_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_uninitialized_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_uninitialized_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_unittest.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_xml_outfile1_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_xml_outfile2_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_xml_outfiles_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_xml_output_unittest.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_xml_output_unittest_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/gtest_xml_test_utils.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/production.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/test/production.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Config/DebugProject.xcconfig (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Config/FrameworkTarget.xcconfig (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Config/General.xcconfig (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Config/ReleaseProject.xcconfig (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Config/TestTarget.xcconfig (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Resources/Info.plist (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/Info.plist (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/runtests.sh (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Scripts/runtests.sh (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/Scripts/versiongenerate.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/gtest/xcode/gtest.xcodeproj/project.pbxproj (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock-actions.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock-cardinalities.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock-generated-actions.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock-generated-actions.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock-generated-matchers.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock-generated-matchers.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock-matchers.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock-more-actions.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock-more-matchers.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock-spec-builders.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/gmock.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h.pump (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/internal/gmock-internal-utils.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/include/gmock/internal/gmock-port.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/msvc/2005/gmock_config.vsprops (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/msvc/2010/gmock_config.props (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/scripts/fuse_gmock_files.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/scripts/generator/LICENSE (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/scripts/generator/README (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/scripts/generator/README.cppclean (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/scripts/generator/cpp/__init__.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/scripts/generator/cpp/ast.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/scripts/generator/cpp/gmock_class.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/scripts/generator/cpp/keywords.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/scripts/generator/cpp/tokenize.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/scripts/generator/cpp/utils.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/scripts/generator/gmock_gen.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/scripts/gmock-config.in (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/src/gmock-all.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/src/gmock-cardinalities.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/src/gmock-internal-utils.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/src/gmock-matchers.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/src/gmock-spec-builders.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/src/gmock.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/src/gmock_main.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock-actions_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock-cardinalities_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock-generated-actions_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock-generated-function-mockers_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock-generated-internal-utils_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock-generated-matchers_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock-internal-utils_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock-matchers_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock-more-actions_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock-nice-strict_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock-port_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock-spec-builders_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock_all_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock_ex_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock_leak_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock_leak_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock_link2_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock_link_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock_link_test.h (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock_output_test.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock_output_test_.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock_output_test_golden.txt (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock_stress_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock_test.cc (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/gmock-1.7.0/test/gmock_test_utils.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/pyunit_gen/pyunit_gen.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/LICENSE (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/MANIFEST.in (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/README.rst (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/fabfile.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/setup.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/src/xmlrunner/__init__.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/src/xmlrunner/extra/__init__.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/src/xmlrunner/extra/djangotestrunner.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/src/xmlrunner/tests/__init__.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/src/xmlrunner/tests/fixtures/errord_test_case.xml (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/src/xmlrunner/tests/fixtures/failed_test_case.xml (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/src/xmlrunner/tests/fixtures/mixed_test_case.xml (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/src/xmlrunner/tests/fixtures/successful_test_case.xml (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/src/xmlrunner/tests/testsuite.py (100%) rename Code/Mantid/{TestingTools => Testing/Tools}/unittest-xml-reporting/src/xmlrunner/tests/testsuite_cases.py (100%) delete mode 100755 Code/Mantid/Vates/VatesAPI/test/runTests.sh diff --git a/Code/Mantid/Build/CMake/EmbeddedGTest.cmake b/Code/Mantid/Build/CMake/EmbeddedGTest.cmake index 25e55227cd58..545837105cc1 100644 --- a/Code/Mantid/Build/CMake/EmbeddedGTest.cmake +++ b/Code/Mantid/Build/CMake/EmbeddedGTest.cmake @@ -3,8 +3,8 @@ # GTEST_FOUND If false, do not try to use Google Test find_path ( GTEST_INCLUDE_DIR gtest/gtest.h - PATHS ${PROJECT_SOURCE_DIR}/TestingTools/gmock-${GMOCK_VERSION}/gtest/include - ${PROJECT_SOURCE_DIR}/../TestingTools/gmock-${GMOCK_VERSION}/gtest/include + PATHS ${PROJECT_SOURCE_DIR}/Testing/Tools/gmock-${GMOCK_VERSION}/gtest/include + ${PROJECT_SOURCE_DIR}/../Testing/Tools/gmock-${GMOCK_VERSION}/gtest/include NO_DEFAULT_PATH ) # handle the QUIETLY and REQUIRED arguments and set GTEST_FOUND to TRUE if diff --git a/Code/Mantid/Build/CMake/FindCxxTest.cmake b/Code/Mantid/Build/CMake/FindCxxTest.cmake index cc9a5cb40c3b..8aaeadbb37fd 100644 --- a/Code/Mantid/Build/CMake/FindCxxTest.cmake +++ b/Code/Mantid/Build/CMake/FindCxxTest.cmake @@ -194,8 +194,8 @@ endmacro(CXXTEST_ADD_TEST) #============================================================= find_path(CXXTEST_INCLUDE_DIR cxxtest/TestSuite.h - PATHS ${PROJECT_SOURCE_DIR}/TestingTools/cxxtest - ${PROJECT_SOURCE_DIR}/../TestingTools/cxxtest ) + PATHS ${PROJECT_SOURCE_DIR}/Testing/Tools/cxxtest + ${PROJECT_SOURCE_DIR}/../Testing/Tools/cxxtest ) find_program(CXXTEST_TESTGEN_EXECUTABLE python/scripts/cxxtestgen PATHS ${CXXTEST_INCLUDE_DIR}) diff --git a/Code/Mantid/Build/CMake/FindGMock.cmake b/Code/Mantid/Build/CMake/FindGMock.cmake index e540e5a18af2..a611ce2fb73d 100644 --- a/Code/Mantid/Build/CMake/FindGMock.cmake +++ b/Code/Mantid/Build/CMake/FindGMock.cmake @@ -17,8 +17,8 @@ ENDIF() set (GMOCK_VERSION ${GMOCK_VERSION} CACHE INTERNAL "") find_path ( GMOCK_INCLUDE_DIR gmock/gmock.h - PATHS ${PROJECT_SOURCE_DIR}/TestingTools/gmock-${GMOCK_VERSION}/include - ${PROJECT_SOURCE_DIR}/../TestingTools/gmock-${GMOCK_VERSION}/include + PATHS ${PROJECT_SOURCE_DIR}/Testing/Tools/gmock-${GMOCK_VERSION}/include + ${PROJECT_SOURCE_DIR}/../Testing/Tools/gmock-${GMOCK_VERSION}/include NO_DEFAULT_PATH ) SET(GMOCK_LIB gmock) diff --git a/Code/Mantid/Build/CMake/FindPyUnitTest.cmake b/Code/Mantid/Build/CMake/FindPyUnitTest.cmake index 893cb5b392a5..bd6c3661633b 100644 --- a/Code/Mantid/Build/CMake/FindPyUnitTest.cmake +++ b/Code/Mantid/Build/CMake/FindPyUnitTest.cmake @@ -59,13 +59,13 @@ endmacro ( PYUNITTEST_ADD_TEST ) # find the driver script find_program ( PYUNITTEST_GEN_EXEC pyunit_gen.py - PATHS ${PROJECT_SOURCE_DIR}/TestingTools/pyunit_gen - ${PROJECT_SOURCE_DIR}/../TestingTools/pyunit_gen ) + PATHS ${PROJECT_SOURCE_DIR}/Testing/Tools/pyunit_gen + ${PROJECT_SOURCE_DIR}/../Testing/Tools/pyunit_gen ) # determine where the xmlrunner lives find_path ( PYUNITTEST_XMLRUNNER xmlrunner/__init__.py - PATHS ${PROJECT_SOURCE_DIR}/TestingTools/unittest-xml-reporting/src/ - ${PROJECT_SOURCE_DIR}/../TestingTools/unittest-xml-reporting/src/ ) + PATHS ${PROJECT_SOURCE_DIR}/Testing/Tools/unittest-xml-reporting/src/ + ${PROJECT_SOURCE_DIR}/../Testing/Tools/unittest-xml-reporting/src/ ) # let people know whether or not it was found if (PYUNITTEST_GEN_EXEC) diff --git a/Code/Mantid/Framework/CMakeLists.txt b/Code/Mantid/Framework/CMakeLists.txt index 03c5ab5792d2..78e6fd797eaa 100644 --- a/Code/Mantid/Framework/CMakeLists.txt +++ b/Code/Mantid/Framework/CMakeLists.txt @@ -121,9 +121,7 @@ endif () # Unit test helper packages if ( CXXTEST_FOUND ) add_subdirectory ( UserAlgorithms ) - # This needs to be here so that a Framework-only build will work. -# add_subdirectory ( ../TestingTools ${${CMAKE_PROJECT_NAME}_BINARY_DIR}/TestingTools/gmock-${GMOCK_VERSION} ) - add_subdirectory ( ../TestingTools ${${CMAKE_PROJECT_NAME}_BINARY_DIR}/TestingTools ) + add_subdirectory ( ../Testing/Tools ${${CMAKE_PROJECT_NAME}_BINARY_DIR}/Testing/Tools ) endif () add_subdirectory (MDAlgorithms) diff --git a/Code/Mantid/MantidPlot/test/mantidplottests.py b/Code/Mantid/MantidPlot/test/mantidplottests.py index 39d59919da8f..f5b14b0c5dba 100644 --- a/Code/Mantid/MantidPlot/test/mantidplottests.py +++ b/Code/Mantid/MantidPlot/test/mantidplottests.py @@ -46,7 +46,7 @@ def runTests(classname): if src is None: runner = unittest.TextTestRunner() else: - sys.path.append( os.path.join(src, "TestingTools/unittest-xml-reporting/src") ) + sys.path.append( os.path.join(src, "Testing", "Tools", "unittest-xml-reporting", "src") ) import xmlrunner runner = xmlrunner.XMLTestRunner(output='Testing') diff --git a/Code/Mantid/TestingTools/CMakeLists.txt b/Code/Mantid/Testing/Tools/CMakeLists.txt similarity index 100% rename from Code/Mantid/TestingTools/CMakeLists.txt rename to Code/Mantid/Testing/Tools/CMakeLists.txt diff --git a/Code/Mantid/TestingTools/cxxtest/COPYING b/Code/Mantid/Testing/Tools/cxxtest/COPYING similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/COPYING rename to Code/Mantid/Testing/Tools/cxxtest/COPYING diff --git a/Code/Mantid/TestingTools/cxxtest/README b/Code/Mantid/Testing/Tools/cxxtest/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/README rename to Code/Mantid/Testing/Tools/cxxtest/README diff --git a/Code/Mantid/TestingTools/cxxtest/TODO b/Code/Mantid/Testing/Tools/cxxtest/TODO similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/TODO rename to Code/Mantid/Testing/Tools/cxxtest/TODO diff --git a/Code/Mantid/TestingTools/cxxtest/Versions b/Code/Mantid/Testing/Tools/cxxtest/Versions similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/Versions rename to Code/Mantid/Testing/Tools/cxxtest/Versions diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/AUTHORS b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/AUTHORS similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/AUTHORS rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/AUTHORS diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/cxxtest.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/cxxtest.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/cxxtest.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/cxxtest.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/default_env/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/default_env/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/default_env/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/default_env/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/default_env/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/default_env/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/default_env/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/default_env/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/default_env/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/default_env/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/default_env/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/default_env/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/requirement.hpp b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/requirement.hpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/requirement.hpp rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/requirement.hpp diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/test_bar.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/test_bar.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/test_bar.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/test_bar.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/test_foo.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/test_foo.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/test_foo.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/test_foo.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/eprouvette.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/eprouvette.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/eprouvette.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/eprouvette.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/expanding_#/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/expanding_#/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/expanding_#/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/expanding_#/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/expanding_#/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/expanding_#/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/expanding_#/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/expanding_#/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/expanding_#/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/expanding_#/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/expanding_#/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/expanding_#/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/requirement.cpp b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/requirement.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/requirement.cpp rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/requirement.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/requirement.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/requirement.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/requirement.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/requirement.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/test_bar.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/test_bar.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/test_bar.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/test_bar.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/test_foo.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/test_foo.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/test_foo.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/test_foo.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.cc b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.cc similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.cc rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.cc diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.hh b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.hh similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.hh rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.hh diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/hellotest.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/hellotest.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/hellotest.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/hellotest.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/main.cpp b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/main.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/main.cpp rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/main.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/not-with-pedantic.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/not-with-pedantic.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/not-with-pedantic.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/not-with-pedantic.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/only_with_ansi.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/only_with_ansi.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/only_with_ansi.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/only_with_ansi.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/src/not-with-pedantic.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/src/not-with-pedantic.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/src/not-with-pedantic.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/src/not-with-pedantic.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.cpp b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.cpp rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_bar.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_bar.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_bar.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_bar.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_foo.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_foo.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_foo.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_foo.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppath.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppath.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppath.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppath.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppathdir/include.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppathdir/include.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppathdir/include.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppathdir/include.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/cxxtest/CrazyRunner.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/cxxtest/CrazyRunner.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/cxxtest/CrazyRunner.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/cxxtest/CrazyRunner.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/src/failtest.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/src/failtest.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/src/failtest.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/src/failtest.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.cpp b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.cpp rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_bar.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_bar.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_bar.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_bar.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_foo.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_foo.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_foo.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_foo.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppath.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppath.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppath.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppath.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppathdir/include.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppathdir/include.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppathdir/include.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppathdir/include.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppath.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppath.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppath.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppath.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppathdir/include.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppathdir/include.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppathdir/include.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppathdir/include.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest.spec b/Code/Mantid/Testing/Tools/cxxtest/cxxtest.spec similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest.spec rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest.spec diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/Descriptions.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/Descriptions.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/Descriptions.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/Descriptions.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/Descriptions.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/Descriptions.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/Descriptions.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/Descriptions.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/DummyDescriptions.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/DummyDescriptions.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/DummyDescriptions.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/DummyDescriptions.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/DummyDescriptions.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/DummyDescriptions.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/DummyDescriptions.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/DummyDescriptions.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/ErrorFormatter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/ErrorFormatter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/ErrorFormatter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/ErrorFormatter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/ErrorPrinter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/ErrorPrinter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/ErrorPrinter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/ErrorPrinter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/Flags.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/Flags.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/Flags.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/Flags.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/GlobalFixture.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/GlobalFixture.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/GlobalFixture.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/GlobalFixture.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/GlobalFixture.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/GlobalFixture.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/GlobalFixture.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/GlobalFixture.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/Gui.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/Gui.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/Gui.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/Gui.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/LinkedList.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/LinkedList.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/LinkedList.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/LinkedList.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/LinkedList.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/LinkedList.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/LinkedList.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/LinkedList.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/MantidFormatter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/MantidFormatter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/MantidFormatter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/MantidFormatter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/MantidPrinter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/MantidPrinter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/MantidPrinter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/MantidPrinter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/Mock.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/Mock.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/Mock.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/Mock.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/ParenPrinter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/ParenPrinter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/ParenPrinter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/ParenPrinter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/QtGui.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/QtGui.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/QtGui.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/QtGui.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/RealDescriptions.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/RealDescriptions.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/RealDescriptions.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/RealDescriptions.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/RealDescriptions.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/RealDescriptions.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/RealDescriptions.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/RealDescriptions.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/Root.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/Root.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/Root.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/Root.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/SelfTest.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/SelfTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/SelfTest.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/SelfTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/StdHeaders.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdHeaders.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/StdHeaders.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdHeaders.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/StdTestSuite.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdTestSuite.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/StdTestSuite.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdTestSuite.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/StdValueTraits.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdValueTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/StdValueTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdValueTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/StdioFilePrinter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdioFilePrinter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/StdioFilePrinter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdioFilePrinter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/StdioPrinter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdioPrinter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/StdioPrinter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdioPrinter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TeeListener.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TeeListener.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TeeListener.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TeeListener.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TestListener.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestListener.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TestListener.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestListener.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TestMain.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestMain.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TestMain.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestMain.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TestRunner.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestRunner.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TestRunner.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestRunner.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TestSuite.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestSuite.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TestSuite.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestSuite.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TestSuite.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestSuite.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TestSuite.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestSuite.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TestTracker.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestTracker.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TestTracker.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestTracker.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TestTracker.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestTracker.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TestTracker.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestTracker.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/ValueTraits.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/ValueTraits.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/ValueTraits.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/ValueTraits.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/ValueTraits.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/ValueTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/ValueTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/ValueTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/Win32Gui.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/Win32Gui.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/Win32Gui.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/Win32Gui.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/WrappedTestSuite.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/WrappedTestSuite.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/WrappedTestSuite.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/WrappedTestSuite.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/X11Gui.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/X11Gui.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/X11Gui.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/X11Gui.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/XUnitPrinter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/XUnitPrinter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/XUnitPrinter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/XUnitPrinter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/XmlFormatter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/XmlFormatter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/XmlFormatter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/XmlFormatter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/XmlPrinter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/XmlPrinter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/XmlPrinter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/XmlPrinter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/YesNoRunner.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/YesNoRunner.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/YesNoRunner.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/YesNoRunner.h diff --git a/Code/Mantid/TestingTools/cxxtest/docs/.cvsignore b/Code/Mantid/Testing/Tools/cxxtest/docs/.cvsignore similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/.cvsignore rename to Code/Mantid/Testing/Tools/cxxtest/docs/.cvsignore diff --git a/Code/Mantid/TestingTools/cxxtest/docs/Makefile b/Code/Mantid/Testing/Tools/cxxtest/docs/Makefile similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/Makefile rename to Code/Mantid/Testing/Tools/cxxtest/docs/Makefile diff --git a/Code/Mantid/TestingTools/cxxtest/docs/convert.pl b/Code/Mantid/Testing/Tools/cxxtest/docs/convert.pl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/convert.pl rename to Code/Mantid/Testing/Tools/cxxtest/docs/convert.pl diff --git a/Code/Mantid/TestingTools/cxxtest/docs/guide.texi b/Code/Mantid/Testing/Tools/cxxtest/docs/guide.texi similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/guide.texi rename to Code/Mantid/Testing/Tools/cxxtest/docs/guide.texi diff --git a/Code/Mantid/TestingTools/cxxtest/docs/qt.png b/Code/Mantid/Testing/Tools/cxxtest/docs/qt.png similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/qt.png rename to Code/Mantid/Testing/Tools/cxxtest/docs/qt.png diff --git a/Code/Mantid/TestingTools/cxxtest/docs/qt2.png b/Code/Mantid/Testing/Tools/cxxtest/docs/qt2.png similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/qt2.png rename to Code/Mantid/Testing/Tools/cxxtest/docs/qt2.png diff --git a/Code/Mantid/TestingTools/cxxtest/docs/texinfo.tex b/Code/Mantid/Testing/Tools/cxxtest/docs/texinfo.tex similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/texinfo.tex rename to Code/Mantid/Testing/Tools/cxxtest/docs/texinfo.tex diff --git a/Code/Mantid/TestingTools/cxxtest/docs/win32.png b/Code/Mantid/Testing/Tools/cxxtest/docs/win32.png similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/win32.png rename to Code/Mantid/Testing/Tools/cxxtest/docs/win32.png diff --git a/Code/Mantid/TestingTools/cxxtest/docs/x11.png b/Code/Mantid/Testing/Tools/cxxtest/docs/x11.png similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/x11.png rename to Code/Mantid/Testing/Tools/cxxtest/docs/x11.png diff --git a/Code/Mantid/TestingTools/cxxtest/get_revision_from_cvs.pl b/Code/Mantid/Testing/Tools/cxxtest/get_revision_from_cvs.pl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/get_revision_from_cvs.pl rename to Code/Mantid/Testing/Tools/cxxtest/get_revision_from_cvs.pl diff --git a/Code/Mantid/TestingTools/cxxtest/python/README.txt b/Code/Mantid/Testing/Tools/cxxtest/python/README.txt similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/README.txt rename to Code/Mantid/Testing/Tools/cxxtest/python/README.txt diff --git a/Code/Mantid/TestingTools/cxxtest/python/cxxtest/__init__.py b/Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/__init__.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/cxxtest/__init__.py rename to Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/__init__.py diff --git a/Code/Mantid/TestingTools/cxxtest/python/cxxtest/__release__.py b/Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/__release__.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/cxxtest/__release__.py rename to Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/__release__.py diff --git a/Code/Mantid/TestingTools/cxxtest/python/cxxtest/cxxtest_misc.py b/Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/cxxtest_misc.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/cxxtest/cxxtest_misc.py rename to Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/cxxtest_misc.py diff --git a/Code/Mantid/TestingTools/cxxtest/python/cxxtest/cxxtest_parser.py b/Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/cxxtest_parser.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/cxxtest/cxxtest_parser.py rename to Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/cxxtest_parser.py diff --git a/Code/Mantid/TestingTools/cxxtest/python/cxxtest/cxxtestgen.py b/Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/cxxtestgen.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/cxxtest/cxxtestgen.py rename to Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/cxxtestgen.py diff --git a/Code/Mantid/TestingTools/cxxtest/python/ez_setup.py b/Code/Mantid/Testing/Tools/cxxtest/python/ez_setup.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/ez_setup.py rename to Code/Mantid/Testing/Tools/cxxtest/python/ez_setup.py diff --git a/Code/Mantid/TestingTools/cxxtest/python/scripts/cxxtestgen b/Code/Mantid/Testing/Tools/cxxtest/python/scripts/cxxtestgen similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/scripts/cxxtestgen rename to Code/Mantid/Testing/Tools/cxxtest/python/scripts/cxxtestgen diff --git a/Code/Mantid/TestingTools/cxxtest/python/setup.py b/Code/Mantid/Testing/Tools/cxxtest/python/setup.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/setup.py rename to Code/Mantid/Testing/Tools/cxxtest/python/setup.py diff --git a/Code/Mantid/TestingTools/cxxtest/sample/.cvsignore b/Code/Mantid/Testing/Tools/cxxtest/sample/.cvsignore similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/.cvsignore rename to Code/Mantid/Testing/Tools/cxxtest/sample/.cvsignore diff --git a/Code/Mantid/TestingTools/cxxtest/sample/Construct b/Code/Mantid/Testing/Tools/cxxtest/sample/Construct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/Construct rename to Code/Mantid/Testing/Tools/cxxtest/sample/Construct diff --git a/Code/Mantid/TestingTools/cxxtest/sample/CreatedTest.h b/Code/Mantid/Testing/Tools/cxxtest/sample/CreatedTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/CreatedTest.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/CreatedTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/DeltaTest.h b/Code/Mantid/Testing/Tools/cxxtest/sample/DeltaTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/DeltaTest.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/DeltaTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/EnumTraits.h b/Code/Mantid/Testing/Tools/cxxtest/sample/EnumTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/EnumTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/EnumTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/ExceptionTest.h b/Code/Mantid/Testing/Tools/cxxtest/sample/ExceptionTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/ExceptionTest.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/ExceptionTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/FixtureTest.h b/Code/Mantid/Testing/Tools/cxxtest/sample/FixtureTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/FixtureTest.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/FixtureTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/Makefile.PL b/Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.PL similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/Makefile.PL rename to Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.PL diff --git a/Code/Mantid/TestingTools/cxxtest/sample/Makefile.bcc32 b/Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.bcc32 similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/Makefile.bcc32 rename to Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.bcc32 diff --git a/Code/Mantid/TestingTools/cxxtest/sample/Makefile.msvc b/Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.msvc similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/Makefile.msvc rename to Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.msvc diff --git a/Code/Mantid/TestingTools/cxxtest/sample/Makefile.unix b/Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.unix similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/Makefile.unix rename to Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.unix diff --git a/Code/Mantid/TestingTools/cxxtest/sample/MessageTest.h b/Code/Mantid/Testing/Tools/cxxtest/sample/MessageTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/MessageTest.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/MessageTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/SCons/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/sample/SCons/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/SCons/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/sample/SCons/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/sample/SCons/include/stack.h b/Code/Mantid/Testing/Tools/cxxtest/sample/SCons/include/stack.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/SCons/include/stack.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/SCons/include/stack.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/SCons/src/stack.c b/Code/Mantid/Testing/Tools/cxxtest/sample/SCons/src/stack.c similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/SCons/src/stack.c rename to Code/Mantid/Testing/Tools/cxxtest/sample/SCons/src/stack.c diff --git a/Code/Mantid/TestingTools/cxxtest/sample/SCons/tests/stack_test.h b/Code/Mantid/Testing/Tools/cxxtest/sample/SCons/tests/stack_test.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/SCons/tests/stack_test.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/SCons/tests/stack_test.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/SimpleTest.h b/Code/Mantid/Testing/Tools/cxxtest/sample/SimpleTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/SimpleTest.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/SimpleTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/TraitsTest.h b/Code/Mantid/Testing/Tools/cxxtest/sample/TraitsTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/TraitsTest.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/TraitsTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/aborter.tpl b/Code/Mantid/Testing/Tools/cxxtest/sample/aborter.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/aborter.tpl rename to Code/Mantid/Testing/Tools/cxxtest/sample/aborter.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/sample/file_printer.tpl b/Code/Mantid/Testing/Tools/cxxtest/sample/file_printer.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/file_printer.tpl rename to Code/Mantid/Testing/Tools/cxxtest/sample/file_printer.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/sample/gui/GreenYellowRed.h b/Code/Mantid/Testing/Tools/cxxtest/sample/gui/GreenYellowRed.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/gui/GreenYellowRed.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/gui/GreenYellowRed.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/Dice.cpp b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/Dice.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/Dice.cpp rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/Dice.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/Dice.h b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/Dice.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/Dice.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/Dice.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/Makefile b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/Makefile similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/Makefile rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/Makefile diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/MockStdlib.h b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/MockStdlib.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/MockStdlib.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/MockStdlib.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/T/stdlib.h b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/T/stdlib.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/T/stdlib.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/T/stdlib.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/TestDice.h b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/TestDice.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/TestDice.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/TestDice.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/mock_stdlib.cpp b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/mock_stdlib.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/mock_stdlib.cpp rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/mock_stdlib.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/real_stdlib.cpp b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/real_stdlib.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/real_stdlib.cpp rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/real_stdlib.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/roll.cpp b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/roll.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/roll.cpp rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/roll.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_1_Run.dsp b/Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_1_Run.dsp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_1_Run.dsp rename to Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_1_Run.dsp diff --git a/Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_2_Build.dsp b/Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_2_Build.dsp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_2_Build.dsp rename to Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_2_Build.dsp diff --git a/Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_3_Generate.dsp b/Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_3_Generate.dsp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_3_Generate.dsp rename to Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_3_Generate.dsp diff --git a/Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_Workspace.dsw b/Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_Workspace.dsw similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_Workspace.dsw rename to Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_Workspace.dsw diff --git a/Code/Mantid/TestingTools/cxxtest/sample/msvc/FixFiles.bat b/Code/Mantid/Testing/Tools/cxxtest/sample/msvc/FixFiles.bat similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/msvc/FixFiles.bat rename to Code/Mantid/Testing/Tools/cxxtest/sample/msvc/FixFiles.bat diff --git a/Code/Mantid/TestingTools/cxxtest/sample/msvc/Makefile b/Code/Mantid/Testing/Tools/cxxtest/sample/msvc/Makefile similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/msvc/Makefile rename to Code/Mantid/Testing/Tools/cxxtest/sample/msvc/Makefile diff --git a/Code/Mantid/TestingTools/cxxtest/sample/msvc/ReadMe.txt b/Code/Mantid/Testing/Tools/cxxtest/sample/msvc/ReadMe.txt similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/msvc/ReadMe.txt rename to Code/Mantid/Testing/Tools/cxxtest/sample/msvc/ReadMe.txt diff --git a/Code/Mantid/TestingTools/cxxtest/sample/only.tpl b/Code/Mantid/Testing/Tools/cxxtest/sample/only.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/only.tpl rename to Code/Mantid/Testing/Tools/cxxtest/sample/only.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/sample/parts/.cvsignore b/Code/Mantid/Testing/Tools/cxxtest/sample/parts/.cvsignore similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/parts/.cvsignore rename to Code/Mantid/Testing/Tools/cxxtest/sample/parts/.cvsignore diff --git a/Code/Mantid/TestingTools/cxxtest/sample/parts/Makefile.unix b/Code/Mantid/Testing/Tools/cxxtest/sample/parts/Makefile.unix similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/parts/Makefile.unix rename to Code/Mantid/Testing/Tools/cxxtest/sample/parts/Makefile.unix diff --git a/Code/Mantid/TestingTools/cxxtest/sample/winddk/Makefile b/Code/Mantid/Testing/Tools/cxxtest/sample/winddk/Makefile similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/winddk/Makefile rename to Code/Mantid/Testing/Tools/cxxtest/sample/winddk/Makefile diff --git a/Code/Mantid/TestingTools/cxxtest/sample/winddk/Makefile.inc b/Code/Mantid/Testing/Tools/cxxtest/sample/winddk/Makefile.inc similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/winddk/Makefile.inc rename to Code/Mantid/Testing/Tools/cxxtest/sample/winddk/Makefile.inc diff --git a/Code/Mantid/TestingTools/cxxtest/sample/winddk/RunTests.tpl b/Code/Mantid/Testing/Tools/cxxtest/sample/winddk/RunTests.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/winddk/RunTests.tpl rename to Code/Mantid/Testing/Tools/cxxtest/sample/winddk/RunTests.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/sample/winddk/SOURCES b/Code/Mantid/Testing/Tools/cxxtest/sample/winddk/SOURCES similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/winddk/SOURCES rename to Code/Mantid/Testing/Tools/cxxtest/sample/winddk/SOURCES diff --git a/Code/Mantid/TestingTools/cxxtest/sample/yes_no_runner.cpp b/Code/Mantid/Testing/Tools/cxxtest/sample/yes_no_runner.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/yes_no_runner.cpp rename to Code/Mantid/Testing/Tools/cxxtest/sample/yes_no_runner.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/.cvsignore b/Code/Mantid/Testing/Tools/cxxtest/test/.cvsignore similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/.cvsignore rename to Code/Mantid/Testing/Tools/cxxtest/test/.cvsignore diff --git a/Code/Mantid/TestingTools/cxxtest/test/AborterNoThrow.h b/Code/Mantid/Testing/Tools/cxxtest/test/AborterNoThrow.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/AborterNoThrow.h rename to Code/Mantid/Testing/Tools/cxxtest/test/AborterNoThrow.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/BadTest.h b/Code/Mantid/Testing/Tools/cxxtest/test/BadTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/BadTest.h rename to Code/Mantid/Testing/Tools/cxxtest/test/BadTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Comments.h b/Code/Mantid/Testing/Tools/cxxtest/test/Comments.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Comments.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Comments.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/DeepAbort.h b/Code/Mantid/Testing/Tools/cxxtest/test/DeepAbort.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/DeepAbort.h rename to Code/Mantid/Testing/Tools/cxxtest/test/DeepAbort.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/DefaultAbort.h b/Code/Mantid/Testing/Tools/cxxtest/test/DefaultAbort.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/DefaultAbort.h rename to Code/Mantid/Testing/Tools/cxxtest/test/DefaultAbort.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/DefaultTraits.h b/Code/Mantid/Testing/Tools/cxxtest/test/DefaultTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/DefaultTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/test/DefaultTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/DoubleCall.h b/Code/Mantid/Testing/Tools/cxxtest/test/DoubleCall.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/DoubleCall.h rename to Code/Mantid/Testing/Tools/cxxtest/test/DoubleCall.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/DynamicAbort.h b/Code/Mantid/Testing/Tools/cxxtest/test/DynamicAbort.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/DynamicAbort.h rename to Code/Mantid/Testing/Tools/cxxtest/test/DynamicAbort.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/DynamicMax.h b/Code/Mantid/Testing/Tools/cxxtest/test/DynamicMax.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/DynamicMax.h rename to Code/Mantid/Testing/Tools/cxxtest/test/DynamicMax.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/EmptySuite.h b/Code/Mantid/Testing/Tools/cxxtest/test/EmptySuite.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/EmptySuite.h rename to Code/Mantid/Testing/Tools/cxxtest/test/EmptySuite.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Exceptions.h b/Code/Mantid/Testing/Tools/cxxtest/test/Exceptions.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Exceptions.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Exceptions.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Factor.h b/Code/Mantid/Testing/Tools/cxxtest/test/Factor.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Factor.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Factor.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/ForceNoEh.h b/Code/Mantid/Testing/Tools/cxxtest/test/ForceNoEh.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/ForceNoEh.h rename to Code/Mantid/Testing/Tools/cxxtest/test/ForceNoEh.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/GfSetUpFails.h b/Code/Mantid/Testing/Tools/cxxtest/test/GfSetUpFails.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/GfSetUpFails.h rename to Code/Mantid/Testing/Tools/cxxtest/test/GfSetUpFails.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/GfSetUpThrows.h b/Code/Mantid/Testing/Tools/cxxtest/test/GfSetUpThrows.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/GfSetUpThrows.h rename to Code/Mantid/Testing/Tools/cxxtest/test/GfSetUpThrows.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/GfTearDownFails.h b/Code/Mantid/Testing/Tools/cxxtest/test/GfTearDownFails.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/GfTearDownFails.h rename to Code/Mantid/Testing/Tools/cxxtest/test/GfTearDownFails.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/GfTearDownThrows.h b/Code/Mantid/Testing/Tools/cxxtest/test/GfTearDownThrows.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/GfTearDownThrows.h rename to Code/Mantid/Testing/Tools/cxxtest/test/GfTearDownThrows.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/GlobalFixtures.h b/Code/Mantid/Testing/Tools/cxxtest/test/GlobalFixtures.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/GlobalFixtures.h rename to Code/Mantid/Testing/Tools/cxxtest/test/GlobalFixtures.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/GoodSuite.h b/Code/Mantid/Testing/Tools/cxxtest/test/GoodSuite.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/GoodSuite.h rename to Code/Mantid/Testing/Tools/cxxtest/test/GoodSuite.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/GuiWait.h b/Code/Mantid/Testing/Tools/cxxtest/test/GuiWait.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/GuiWait.h rename to Code/Mantid/Testing/Tools/cxxtest/test/GuiWait.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/HaveStd.h b/Code/Mantid/Testing/Tools/cxxtest/test/HaveStd.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/HaveStd.h rename to Code/Mantid/Testing/Tools/cxxtest/test/HaveStd.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/IncludeTest.h b/Code/Mantid/Testing/Tools/cxxtest/test/IncludeTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/IncludeTest.h rename to Code/Mantid/Testing/Tools/cxxtest/test/IncludeTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Int64.h b/Code/Mantid/Testing/Tools/cxxtest/test/Int64.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Int64.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Int64.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/LessThanEquals.h b/Code/Mantid/Testing/Tools/cxxtest/test/LessThanEquals.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/LessThanEquals.h rename to Code/Mantid/Testing/Tools/cxxtest/test/LessThanEquals.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/LongLong.h b/Code/Mantid/Testing/Tools/cxxtest/test/LongLong.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/LongLong.h rename to Code/Mantid/Testing/Tools/cxxtest/test/LongLong.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/LongTraits.h b/Code/Mantid/Testing/Tools/cxxtest/test/LongTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/LongTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/test/LongTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Makefile b/Code/Mantid/Testing/Tools/cxxtest/test/Makefile similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Makefile rename to Code/Mantid/Testing/Tools/cxxtest/test/Makefile diff --git a/Code/Mantid/TestingTools/cxxtest/test/MaxDump.h b/Code/Mantid/Testing/Tools/cxxtest/test/MaxDump.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/MaxDump.h rename to Code/Mantid/Testing/Tools/cxxtest/test/MaxDump.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/MockTest.h b/Code/Mantid/Testing/Tools/cxxtest/test/MockTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/MockTest.h rename to Code/Mantid/Testing/Tools/cxxtest/test/MockTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/NoEh.h b/Code/Mantid/Testing/Tools/cxxtest/test/NoEh.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/NoEh.h rename to Code/Mantid/Testing/Tools/cxxtest/test/NoEh.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Part1.h b/Code/Mantid/Testing/Tools/cxxtest/test/Part1.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Part1.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Part1.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Part2.h b/Code/Mantid/Testing/Tools/cxxtest/test/Part2.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Part2.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Part2.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Relation.h b/Code/Mantid/Testing/Tools/cxxtest/test/Relation.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Relation.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Relation.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/SameData.h b/Code/Mantid/Testing/Tools/cxxtest/test/SameData.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/SameData.h rename to Code/Mantid/Testing/Tools/cxxtest/test/SameData.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/SameZero.h b/Code/Mantid/Testing/Tools/cxxtest/test/SameZero.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/SameZero.h rename to Code/Mantid/Testing/Tools/cxxtest/test/SameZero.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/SetUpWorldFails.h b/Code/Mantid/Testing/Tools/cxxtest/test/SetUpWorldFails.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/SetUpWorldFails.h rename to Code/Mantid/Testing/Tools/cxxtest/test/SetUpWorldFails.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/SetUpWorldThrows.h b/Code/Mantid/Testing/Tools/cxxtest/test/SetUpWorldThrows.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/SetUpWorldThrows.h rename to Code/Mantid/Testing/Tools/cxxtest/test/SetUpWorldThrows.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Something.h b/Code/Mantid/Testing/Tools/cxxtest/test/Something.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Something.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Something.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/StlTraits.h b/Code/Mantid/Testing/Tools/cxxtest/test/StlTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/StlTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/test/StlTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/TearDownWorldFails.h b/Code/Mantid/Testing/Tools/cxxtest/test/TearDownWorldFails.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/TearDownWorldFails.h rename to Code/Mantid/Testing/Tools/cxxtest/test/TearDownWorldFails.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/TearDownWorldThrows.h b/Code/Mantid/Testing/Tools/cxxtest/test/TearDownWorldThrows.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/TearDownWorldThrows.h rename to Code/Mantid/Testing/Tools/cxxtest/test/TearDownWorldThrows.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/ThrowNoStd.h b/Code/Mantid/Testing/Tools/cxxtest/test/ThrowNoStd.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/ThrowNoStd.h rename to Code/Mantid/Testing/Tools/cxxtest/test/ThrowNoStd.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/ThrowNoStd.tpl b/Code/Mantid/Testing/Tools/cxxtest/test/ThrowNoStd.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/ThrowNoStd.tpl rename to Code/Mantid/Testing/Tools/cxxtest/test/ThrowNoStd.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/test/ThrowsAssert.h b/Code/Mantid/Testing/Tools/cxxtest/test/ThrowsAssert.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/ThrowsAssert.h rename to Code/Mantid/Testing/Tools/cxxtest/test/ThrowsAssert.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/TraitsTest.h b/Code/Mantid/Testing/Tools/cxxtest/test/TraitsTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/TraitsTest.h rename to Code/Mantid/Testing/Tools/cxxtest/test/TraitsTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Tsm.h b/Code/Mantid/Testing/Tools/cxxtest/test/Tsm.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Tsm.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Tsm.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/UserTraits.h b/Code/Mantid/Testing/Tools/cxxtest/test/UserTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/UserTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/test/UserTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/UserTraits.tpl b/Code/Mantid/Testing/Tools/cxxtest/test/UserTraits.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/UserTraits.tpl rename to Code/Mantid/Testing/Tools/cxxtest/test/UserTraits.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/test/VoidTraits.h b/Code/Mantid/Testing/Tools/cxxtest/test/VoidTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/VoidTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/test/VoidTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/WideCharTest.h b/Code/Mantid/Testing/Tools/cxxtest/test/WideCharTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/WideCharTest.h rename to Code/Mantid/Testing/Tools/cxxtest/test/WideCharTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/WorldFixtures.h b/Code/Mantid/Testing/Tools/cxxtest/test/WorldFixtures.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/WorldFixtures.h rename to Code/Mantid/Testing/Tools/cxxtest/test/WorldFixtures.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/abort.out b/Code/Mantid/Testing/Tools/cxxtest/test/abort.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/abort.out rename to Code/Mantid/Testing/Tools/cxxtest/test/abort.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/activate.tpl b/Code/Mantid/Testing/Tools/cxxtest/test/activate.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/activate.tpl rename to Code/Mantid/Testing/Tools/cxxtest/test/activate.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/test/anything.cpp b/Code/Mantid/Testing/Tools/cxxtest/test/anything.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/anything.cpp rename to Code/Mantid/Testing/Tools/cxxtest/test/anything.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/comments.out b/Code/Mantid/Testing/Tools/cxxtest/test/comments.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/comments.out rename to Code/Mantid/Testing/Tools/cxxtest/test/comments.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/cxxtest/DummyGui.h b/Code/Mantid/Testing/Tools/cxxtest/test/cxxtest/DummyGui.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/cxxtest/DummyGui.h rename to Code/Mantid/Testing/Tools/cxxtest/test/cxxtest/DummyGui.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/default_abort.out b/Code/Mantid/Testing/Tools/cxxtest/test/default_abort.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/default_abort.out rename to Code/Mantid/Testing/Tools/cxxtest/test/default_abort.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/eh_normals.out b/Code/Mantid/Testing/Tools/cxxtest/test/eh_normals.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/eh_normals.out rename to Code/Mantid/Testing/Tools/cxxtest/test/eh_normals.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/error.out b/Code/Mantid/Testing/Tools/cxxtest/test/error.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/error.out rename to Code/Mantid/Testing/Tools/cxxtest/test/error.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/factor.out b/Code/Mantid/Testing/Tools/cxxtest/test/factor.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/factor.out rename to Code/Mantid/Testing/Tools/cxxtest/test/factor.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/.cvsignore b/Code/Mantid/Testing/Tools/cxxtest/test/fake/.cvsignore similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/.cvsignore rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/.cvsignore diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/X11/Xlib.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/X11/Xlib.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/X11/Xlib.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/X11/Xlib.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/X11/Xutil.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/X11/Xutil.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/X11/Xutil.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/X11/Xutil.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/commctrl.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/commctrl.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/commctrl.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/commctrl.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qapplication.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qapplication.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qapplication.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qapplication.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qglobal.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qglobal.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qglobal.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qglobal.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qlabel.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qlabel.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qlabel.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qlabel.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qlayout.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qlayout.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qlayout.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qlayout.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qmessagebox.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qmessagebox.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qmessagebox.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qmessagebox.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qpixmap.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qpixmap.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qpixmap.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qpixmap.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qprogressbar.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qprogressbar.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qprogressbar.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qprogressbar.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qstatusbar.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qstatusbar.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qstatusbar.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qstatusbar.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qstring.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qstring.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qstring.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qstring.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qwidget.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qwidget.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qwidget.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qwidget.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/windows.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/windows.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/windows.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/windows.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/gfsuf.out b/Code/Mantid/Testing/Tools/cxxtest/test/gfsuf.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/gfsuf.out rename to Code/Mantid/Testing/Tools/cxxtest/test/gfsuf.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/gfsut.out b/Code/Mantid/Testing/Tools/cxxtest/test/gfsut.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/gfsut.out rename to Code/Mantid/Testing/Tools/cxxtest/test/gfsut.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/gftdf.out b/Code/Mantid/Testing/Tools/cxxtest/test/gftdf.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/gftdf.out rename to Code/Mantid/Testing/Tools/cxxtest/test/gftdf.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/gftdt.out b/Code/Mantid/Testing/Tools/cxxtest/test/gftdt.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/gftdt.out rename to Code/Mantid/Testing/Tools/cxxtest/test/gftdt.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/gfxs.out b/Code/Mantid/Testing/Tools/cxxtest/test/gfxs.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/gfxs.out rename to Code/Mantid/Testing/Tools/cxxtest/test/gfxs.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/good.out b/Code/Mantid/Testing/Tools/cxxtest/test/good.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/good.out rename to Code/Mantid/Testing/Tools/cxxtest/test/good.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/gui.out b/Code/Mantid/Testing/Tools/cxxtest/test/gui.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/gui.out rename to Code/Mantid/Testing/Tools/cxxtest/test/gui.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/gui_paren.out b/Code/Mantid/Testing/Tools/cxxtest/test/gui_paren.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/gui_paren.out rename to Code/Mantid/Testing/Tools/cxxtest/test/gui_paren.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/include.out b/Code/Mantid/Testing/Tools/cxxtest/test/include.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/include.out rename to Code/Mantid/Testing/Tools/cxxtest/test/include.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/int64.cpp b/Code/Mantid/Testing/Tools/cxxtest/test/int64.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/int64.cpp rename to Code/Mantid/Testing/Tools/cxxtest/test/int64.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/int64.out b/Code/Mantid/Testing/Tools/cxxtest/test/int64.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/int64.out rename to Code/Mantid/Testing/Tools/cxxtest/test/int64.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/longlong.cpp b/Code/Mantid/Testing/Tools/cxxtest/test/longlong.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/longlong.cpp rename to Code/Mantid/Testing/Tools/cxxtest/test/longlong.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/longlong.out b/Code/Mantid/Testing/Tools/cxxtest/test/longlong.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/longlong.out rename to Code/Mantid/Testing/Tools/cxxtest/test/longlong.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/main.cpp b/Code/Mantid/Testing/Tools/cxxtest/test/main.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/main.cpp rename to Code/Mantid/Testing/Tools/cxxtest/test/main.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/max.out b/Code/Mantid/Testing/Tools/cxxtest/test/max.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/max.out rename to Code/Mantid/Testing/Tools/cxxtest/test/max.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/normal.out b/Code/Mantid/Testing/Tools/cxxtest/test/normal.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/normal.out rename to Code/Mantid/Testing/Tools/cxxtest/test/normal.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/paren.out b/Code/Mantid/Testing/Tools/cxxtest/test/paren.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/paren.out rename to Code/Mantid/Testing/Tools/cxxtest/test/paren.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/parts.out b/Code/Mantid/Testing/Tools/cxxtest/test/parts.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/parts.out rename to Code/Mantid/Testing/Tools/cxxtest/test/parts.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/preamble.out b/Code/Mantid/Testing/Tools/cxxtest/test/preamble.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/preamble.out rename to Code/Mantid/Testing/Tools/cxxtest/test/preamble.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/preamble.tpl b/Code/Mantid/Testing/Tools/cxxtest/test/preamble.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/preamble.tpl rename to Code/Mantid/Testing/Tools/cxxtest/test/preamble.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/test/runner.out b/Code/Mantid/Testing/Tools/cxxtest/test/runner.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/runner.out rename to Code/Mantid/Testing/Tools/cxxtest/test/runner.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/std.out b/Code/Mantid/Testing/Tools/cxxtest/test/std.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/std.out rename to Code/Mantid/Testing/Tools/cxxtest/test/std.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/stl.out b/Code/Mantid/Testing/Tools/cxxtest/test/stl.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/stl.out rename to Code/Mantid/Testing/Tools/cxxtest/test/stl.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/stpltpl.cpp b/Code/Mantid/Testing/Tools/cxxtest/test/stpltpl.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/stpltpl.cpp rename to Code/Mantid/Testing/Tools/cxxtest/test/stpltpl.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/suite.out b/Code/Mantid/Testing/Tools/cxxtest/test/suite.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/suite.out rename to Code/Mantid/Testing/Tools/cxxtest/test/suite.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/suite_test.out b/Code/Mantid/Testing/Tools/cxxtest/test/suite_test.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/suite_test.out rename to Code/Mantid/Testing/Tools/cxxtest/test/suite_test.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/suwf.out b/Code/Mantid/Testing/Tools/cxxtest/test/suwf.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/suwf.out rename to Code/Mantid/Testing/Tools/cxxtest/test/suwf.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/suwt.out b/Code/Mantid/Testing/Tools/cxxtest/test/suwt.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/suwt.out rename to Code/Mantid/Testing/Tools/cxxtest/test/suwt.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/tdwf.out b/Code/Mantid/Testing/Tools/cxxtest/test/tdwf.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/tdwf.out rename to Code/Mantid/Testing/Tools/cxxtest/test/tdwf.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/tdwt.out b/Code/Mantid/Testing/Tools/cxxtest/test/tdwt.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/tdwt.out rename to Code/Mantid/Testing/Tools/cxxtest/test/tdwt.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/test.pl b/Code/Mantid/Testing/Tools/cxxtest/test/test.pl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/test.pl rename to Code/Mantid/Testing/Tools/cxxtest/test/test.pl diff --git a/Code/Mantid/TestingTools/cxxtest/test/throw.out b/Code/Mantid/Testing/Tools/cxxtest/test/throw.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/throw.out rename to Code/Mantid/Testing/Tools/cxxtest/test/throw.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/tpltpl.cpp b/Code/Mantid/Testing/Tools/cxxtest/test/tpltpl.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/tpltpl.cpp rename to Code/Mantid/Testing/Tools/cxxtest/test/tpltpl.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/unit/LinkedList_test.t.h b/Code/Mantid/Testing/Tools/cxxtest/test/unit/LinkedList_test.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/unit/LinkedList_test.t.h rename to Code/Mantid/Testing/Tools/cxxtest/test/unit/LinkedList_test.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/unit/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/test/unit/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/unit/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/test/unit/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/test/user.out b/Code/Mantid/Testing/Tools/cxxtest/test/user.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/user.out rename to Code/Mantid/Testing/Tools/cxxtest/test/user.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/wchar.cpp b/Code/Mantid/Testing/Tools/cxxtest/test/wchar.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/wchar.cpp rename to Code/Mantid/Testing/Tools/cxxtest/test/wchar.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/wchar.out b/Code/Mantid/Testing/Tools/cxxtest/test/wchar.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/wchar.out rename to Code/Mantid/Testing/Tools/cxxtest/test/wchar.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/wildcard.out b/Code/Mantid/Testing/Tools/cxxtest/test/wildcard.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/wildcard.out rename to Code/Mantid/Testing/Tools/cxxtest/test/wildcard.out diff --git a/Code/Mantid/TestingTools/cxxtest/www/cn-project-pages/snippets/HtmlSnippet1.html b/Code/Mantid/Testing/Tools/cxxtest/www/cn-project-pages/snippets/HtmlSnippet1.html similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/www/cn-project-pages/snippets/HtmlSnippet1.html rename to Code/Mantid/Testing/Tools/cxxtest/www/cn-project-pages/snippets/HtmlSnippet1.html diff --git a/Code/Mantid/TestingTools/cxxtest/www/cn-project-pages/snippets/page.xml b/Code/Mantid/Testing/Tools/cxxtest/www/cn-project-pages/snippets/page.xml similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/www/cn-project-pages/snippets/page.xml rename to Code/Mantid/Testing/Tools/cxxtest/www/cn-project-pages/snippets/page.xml diff --git a/Code/Mantid/TestingTools/generatetestmain.py b/Code/Mantid/Testing/Tools/generatetestmain.py similarity index 100% rename from Code/Mantid/TestingTools/generatetestmain.py rename to Code/Mantid/Testing/Tools/generatetestmain.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/CHANGES b/Code/Mantid/Testing/Tools/gmock-1.6.0/CHANGES similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/CHANGES rename to Code/Mantid/Testing/Tools/gmock-1.6.0/CHANGES diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/CMakeLists.txt b/Code/Mantid/Testing/Tools/gmock-1.6.0/CMakeLists.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/CMakeLists.txt rename to Code/Mantid/Testing/Tools/gmock-1.6.0/CMakeLists.txt diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/CONTRIBUTORS b/Code/Mantid/Testing/Tools/gmock-1.6.0/CONTRIBUTORS similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/CONTRIBUTORS rename to Code/Mantid/Testing/Tools/gmock-1.6.0/CONTRIBUTORS diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/COPYING b/Code/Mantid/Testing/Tools/gmock-1.6.0/COPYING similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/COPYING rename to Code/Mantid/Testing/Tools/gmock-1.6.0/COPYING diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/Makefile.am b/Code/Mantid/Testing/Tools/gmock-1.6.0/Makefile.am similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/Makefile.am rename to Code/Mantid/Testing/Tools/gmock-1.6.0/Makefile.am diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/Makefile.in b/Code/Mantid/Testing/Tools/gmock-1.6.0/Makefile.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/Makefile.in rename to Code/Mantid/Testing/Tools/gmock-1.6.0/Makefile.in diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/README b/Code/Mantid/Testing/Tools/gmock-1.6.0/README similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/README rename to Code/Mantid/Testing/Tools/gmock-1.6.0/README diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/aclocal.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/aclocal.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/aclocal.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/aclocal.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/build-aux/config.guess b/Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/config.guess similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/build-aux/config.guess rename to Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/config.guess diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/build-aux/config.h.in b/Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/config.h.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/build-aux/config.h.in rename to Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/config.h.in diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/build-aux/config.sub b/Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/config.sub similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/build-aux/config.sub rename to Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/config.sub diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/build-aux/depcomp b/Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/depcomp similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/build-aux/depcomp rename to Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/depcomp diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/build-aux/install-sh b/Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/install-sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/build-aux/install-sh rename to Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/install-sh diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/build-aux/ltmain.sh b/Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/ltmain.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/build-aux/ltmain.sh rename to Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/ltmain.sh diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/build-aux/missing b/Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/missing similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/build-aux/missing rename to Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/missing diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/configure b/Code/Mantid/Testing/Tools/gmock-1.6.0/configure similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/configure rename to Code/Mantid/Testing/Tools/gmock-1.6.0/configure diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/configure.ac b/Code/Mantid/Testing/Tools/gmock-1.6.0/configure.ac similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/configure.ac rename to Code/Mantid/Testing/Tools/gmock-1.6.0/configure.ac diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gmock-gtest-all.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gmock-gtest-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gmock-gtest-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gmock-gtest-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gmock/gmock.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gmock/gmock.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gmock/gmock.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gmock/gmock.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gmock_main.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gmock_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gmock_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gmock_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gtest/gtest.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gtest/gtest.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gtest/gtest.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gtest/gtest.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/CHANGES b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/CHANGES similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/CHANGES rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/CHANGES diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/CMakeLists.txt b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/CMakeLists.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/CMakeLists.txt rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/CMakeLists.txt diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/CONTRIBUTORS b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/CONTRIBUTORS similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/CONTRIBUTORS rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/CONTRIBUTORS diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/COPYING b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/COPYING similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/COPYING rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/COPYING diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/Makefile.am b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/Makefile.am similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/Makefile.am rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/Makefile.am diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/Makefile.in b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/Makefile.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/Makefile.in rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/Makefile.in diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/README b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/README similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/README rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/README diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/aclocal.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/aclocal.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/aclocal.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/aclocal.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/config.guess b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/config.guess similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/config.guess rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/config.guess diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/config.h.in b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/config.h.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/config.h.in rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/config.h.in diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/config.sub b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/config.sub similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/config.sub rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/config.sub diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/depcomp b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/depcomp similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/depcomp rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/depcomp diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/install-sh b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/install-sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/install-sh rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/install-sh diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/ltmain.sh b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/ltmain.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/ltmain.sh rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/ltmain.sh diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/missing b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/missing similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/missing rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/missing diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/cmake/internal_utils.cmake b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/cmake/internal_utils.cmake similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/cmake/internal_utils.cmake rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/cmake/internal_utils.cmake diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest.cbproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest.cbproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest.cbproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest.cbproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest.groupproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest.groupproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest.groupproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest.groupproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_all.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_all.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_link.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_link.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_link.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_link.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_main.cbproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_main.cbproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_main.cbproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_main.cbproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_unittest.cbproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_unittest.cbproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_unittest.cbproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_unittest.cbproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/configure b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/configure similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/configure rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/configure diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/configure.ac b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/configure.ac similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/configure.ac rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/configure.ac diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/fused-src/gtest/gtest-all.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/fused-src/gtest/gtest-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/fused-src/gtest/gtest-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/fused-src/gtest/gtest-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/fused-src/gtest/gtest.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/fused-src/gtest/gtest.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/fused-src/gtest/gtest.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/fused-src/gtest/gtest.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/fused-src/gtest/gtest_main.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/fused-src/gtest/gtest_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/fused-src/gtest/gtest_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/fused-src/gtest/gtest_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-death-test.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-death-test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-death-test.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-death-test.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-message.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-message.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-message.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-message.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-printers.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-printers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-printers.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-printers.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-spi.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-spi.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-spi.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-spi.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-test-part.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-test-part.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-test-part.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-test-part.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-typed-test.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-typed-test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-typed-test.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-typed-test.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest_pred_impl.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest_pred_impl.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest_pred_impl.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest_pred_impl.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest_prod.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest_prod.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest_prod.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest_prod.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-death-test-internal.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-death-test-internal.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-death-test-internal.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-death-test-internal.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-filepath.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-filepath.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-filepath.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-filepath.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-internal.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-internal.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-internal.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-internal.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-linked_ptr.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-linked_ptr.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-linked_ptr.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-linked_ptr.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-port.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-port.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-port.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-port.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-string.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-string.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-string.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-string.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/acx_pthread.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/acx_pthread.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/acx_pthread.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/acx_pthread.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/gtest.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/gtest.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/gtest.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/gtest.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/libtool.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/libtool.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/libtool.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/libtool.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/ltoptions.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/ltoptions.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/ltoptions.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/ltoptions.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/ltsugar.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/ltsugar.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/ltsugar.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/ltsugar.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/ltversion.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/ltversion.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/ltversion.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/ltversion.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/lt~obsolete.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/lt~obsolete.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/lt~obsolete.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/lt~obsolete.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest-md.sln b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest-md.sln similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest-md.sln rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest-md.sln diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest-md.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest-md.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest-md.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest-md.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest.sln b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest.sln similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest.sln rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest.sln diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_main-md.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_main-md.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_main-md.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_main-md.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_main.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_main.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_main.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_main.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_prod_test-md.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_prod_test-md.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_prod_test-md.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_prod_test-md.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_prod_test.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_prod_test.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_prod_test.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_prod_test.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_unittest-md.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_unittest-md.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_unittest-md.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_unittest-md.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_unittest.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_unittest.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_unittest.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_unittest.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/prime_tables.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/prime_tables.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/prime_tables.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/prime_tables.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample1.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample1.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample1.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample1.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample1.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample1.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample1.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample1.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample10_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample10_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample10_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample10_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample1_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample1_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample1_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample1_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample2.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample2.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample2.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample2.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample2.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample2.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample2.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample2.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample2_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample2_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample2_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample2_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample3-inl.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample3-inl.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample3-inl.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample3-inl.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample3_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample3_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample3_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample3_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample4.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample4.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample4.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample4.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample4.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample4.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample4.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample4.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample4_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample4_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample4_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample4_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample5_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample5_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample5_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample5_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample6_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample6_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample6_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample6_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample7_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample7_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample7_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample7_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample8_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample8_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample8_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample8_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample9_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample9_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample9_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample9_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/fuse_gtest_files.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/fuse_gtest_files.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/fuse_gtest_files.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/fuse_gtest_files.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/gen_gtest_pred_impl.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/gen_gtest_pred_impl.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/gen_gtest_pred_impl.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/gen_gtest_pred_impl.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/gtest-config.in b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/gtest-config.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/gtest-config.in rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/gtest-config.in diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/pump.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/pump.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/pump.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/pump.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-all.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-death-test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-death-test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-death-test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-death-test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-filepath.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-filepath.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-filepath.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-filepath.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-internal-inl.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-internal-inl.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-internal-inl.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-internal-inl.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-port.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-port.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-port.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-port.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-printers.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-printers.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-printers.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-printers.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-test-part.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-test-part.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-test-part.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-test-part.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-typed-test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-typed-test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-typed-test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-typed-test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest_main.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-death-test_ex_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-death-test_ex_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-death-test_ex_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-death-test_ex_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-death-test_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-death-test_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-death-test_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-death-test_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-filepath_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-filepath_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-filepath_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-filepath_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-linked_ptr_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-linked_ptr_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-linked_ptr_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-linked_ptr_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-listener_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-listener_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-listener_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-listener_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-message_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-message_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-message_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-message_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-options_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-options_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-options_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-options_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-param-test2_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-param-test2_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-param-test2_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-param-test2_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-param-test_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-param-test_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-param-test_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-param-test_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-param-test_test.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-param-test_test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-param-test_test.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-param-test_test.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-port_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-port_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-port_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-port_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-printers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-printers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-printers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-printers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-test-part_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-test-part_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-test-part_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-test-part_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-tuple_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-tuple_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-tuple_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-tuple_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-typed-test2_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-typed-test2_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-typed-test2_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-typed-test2_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-typed-test_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-typed-test_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-typed-test_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-typed-test_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-typed-test_test.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-typed-test_test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-typed-test_test.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-typed-test_test.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-unittest-api_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-unittest-api_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-unittest-api_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-unittest-api_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_all_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_all_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_all_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_all_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_color_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_color_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_color_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_color_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_color_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_color_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_color_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_color_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_env_var_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_env_var_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_env_var_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_env_var_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_env_var_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_env_var_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_env_var_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_env_var_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_environment_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_environment_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_environment_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_environment_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_filter_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_filter_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_filter_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_filter_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_filter_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_filter_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_filter_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_filter_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_help_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_help_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_help_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_help_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_help_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_help_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_help_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_help_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_main_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_main_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_main_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_main_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_no_test_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_no_test_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_no_test_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_no_test_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_output_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_output_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_output_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_output_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_output_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_output_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_output_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_output_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_output_test_golden_lin.txt b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_output_test_golden_lin.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_output_test_golden_lin.txt rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_output_test_golden_lin.txt diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_pred_impl_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_pred_impl_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_pred_impl_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_pred_impl_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_prod_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_prod_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_prod_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_prod_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_repeat_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_repeat_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_repeat_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_repeat_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_shuffle_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_shuffle_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_shuffle_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_shuffle_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_shuffle_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_shuffle_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_shuffle_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_shuffle_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_sole_header_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_sole_header_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_sole_header_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_sole_header_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_stress_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_stress_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_stress_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_stress_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_test_utils.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_test_utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_test_utils.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_test_utils.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_ex_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_ex_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_ex_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_ex_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_uninitialized_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_uninitialized_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_uninitialized_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_uninitialized_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_uninitialized_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_uninitialized_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_uninitialized_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_uninitialized_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_outfile1_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_outfile1_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_outfile1_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_outfile1_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_outfile2_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_outfile2_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_outfile2_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_outfile2_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_outfiles_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_outfiles_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_outfiles_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_outfiles_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_test_utils.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_test_utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_test_utils.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_test_utils.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/production.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/production.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/production.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/production.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/production.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/production.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/production.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/production.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/DebugProject.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/DebugProject.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/DebugProject.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/DebugProject.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/FrameworkTarget.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/FrameworkTarget.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/FrameworkTarget.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/FrameworkTarget.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/General.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/General.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/General.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/General.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/ReleaseProject.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/ReleaseProject.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/ReleaseProject.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/ReleaseProject.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/TestTarget.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/TestTarget.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/TestTarget.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/TestTarget.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Resources/Info.plist b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Resources/Info.plist similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Resources/Info.plist rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Resources/Info.plist diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/Info.plist b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/Info.plist similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/Info.plist rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/Info.plist diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/runtests.sh b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/runtests.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/runtests.sh rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/runtests.sh diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Scripts/runtests.sh b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Scripts/runtests.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Scripts/runtests.sh rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Scripts/runtests.sh diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Scripts/versiongenerate.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Scripts/versiongenerate.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Scripts/versiongenerate.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Scripts/versiongenerate.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/gtest.xcodeproj/project.pbxproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/gtest.xcodeproj/project.pbxproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/gtest.xcodeproj/project.pbxproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/gtest.xcodeproj/project.pbxproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-actions.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-actions.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-actions.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-actions.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-cardinalities.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-cardinalities.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-cardinalities.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-cardinalities.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-actions.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-actions.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-actions.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-actions.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-actions.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-actions.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-actions.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-actions.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-matchers.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-matchers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-matchers.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-matchers.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-more-actions.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-more-actions.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-more-actions.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-more-actions.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-spec-builders.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-spec-builders.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-spec-builders.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-spec-builders.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-internal-utils.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-internal-utils.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-internal-utils.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-internal-utils.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-port.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-port.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-port.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-port.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock.sln b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock.sln similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock.sln rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock.sln diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock_config.vsprops b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock_config.vsprops similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock_config.vsprops rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock_config.vsprops diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock_main.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock_main.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock_main.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock_main.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock_test.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock_test.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock_test.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock_test.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock.sln b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock.sln similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock.sln rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock.sln diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock.vcxproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock.vcxproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock.vcxproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock.vcxproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock_config.props b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock_config.props similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock_config.props rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock_config.props diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock_main.vcxproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock_main.vcxproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock_main.vcxproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock_main.vcxproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock_test.vcxproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock_test.vcxproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock_test.vcxproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock_test.vcxproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/fuse_gmock_files.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/fuse_gmock_files.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/fuse_gmock_files.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/fuse_gmock_files.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/COPYING b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/COPYING similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/COPYING rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/COPYING diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/README b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/README similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/README rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/README diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/README.cppclean b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/README.cppclean similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/README.cppclean rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/README.cppclean diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/__init__.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/__init__.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/__init__.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/__init__.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/ast.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/ast.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/ast.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/ast.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/gmock_class.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/gmock_class.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/gmock_class.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/gmock_class.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/keywords.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/keywords.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/keywords.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/keywords.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/tokenize.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/tokenize.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/tokenize.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/tokenize.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/utils.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/utils.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/utils.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/gmock_gen.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/gmock_gen.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/gmock_gen.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/gmock_gen.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/gmock-config.in b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/gmock-config.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/gmock-config.in rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/gmock-config.in diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-all.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-cardinalities.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-cardinalities.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-cardinalities.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-cardinalities.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-internal-utils.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-internal-utils.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-internal-utils.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-internal-utils.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-matchers.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-matchers.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-matchers.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-matchers.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-spec-builders.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-spec-builders.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-spec-builders.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-spec-builders.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/src/gmock.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/src/gmock.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/src/gmock_main.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/src/gmock_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-actions_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-actions_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-actions_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-actions_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-cardinalities_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-cardinalities_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-cardinalities_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-cardinalities_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-actions_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-actions_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-actions_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-actions_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-function-mockers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-function-mockers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-function-mockers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-function-mockers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-internal-utils_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-internal-utils_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-internal-utils_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-internal-utils_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-matchers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-matchers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-matchers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-matchers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-internal-utils_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-internal-utils_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-internal-utils_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-internal-utils_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-matchers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-matchers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-matchers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-matchers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-more-actions_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-more-actions_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-more-actions_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-more-actions_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-nice-strict_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-nice-strict_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-nice-strict_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-nice-strict_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-port_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-port_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-port_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-port_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-spec-builders_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-spec-builders_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-spec-builders_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-spec-builders_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_all_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_all_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_all_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_all_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_leak_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_leak_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_leak_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_leak_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_leak_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_leak_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_leak_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_leak_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_link2_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_link2_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_link2_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_link2_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_link_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_link_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_link_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_link_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_link_test.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_link_test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_link_test.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_link_test.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_output_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_output_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_output_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_output_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_output_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_output_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_output_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_output_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_output_test_golden.txt b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_output_test_golden.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_output_test_golden.txt rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_output_test_golden.txt diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_test_utils.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_test_utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_test_utils.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_test_utils.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/CHANGES b/Code/Mantid/Testing/Tools/gmock-1.7.0/CHANGES similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/CHANGES rename to Code/Mantid/Testing/Tools/gmock-1.7.0/CHANGES diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/CMakeLists.txt b/Code/Mantid/Testing/Tools/gmock-1.7.0/CMakeLists.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/CMakeLists.txt rename to Code/Mantid/Testing/Tools/gmock-1.7.0/CMakeLists.txt diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/CONTRIBUTORS b/Code/Mantid/Testing/Tools/gmock-1.7.0/CONTRIBUTORS similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/CONTRIBUTORS rename to Code/Mantid/Testing/Tools/gmock-1.7.0/CONTRIBUTORS diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/LICENSE b/Code/Mantid/Testing/Tools/gmock-1.7.0/LICENSE similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/LICENSE rename to Code/Mantid/Testing/Tools/gmock-1.7.0/LICENSE diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/Makefile.am b/Code/Mantid/Testing/Tools/gmock-1.7.0/Makefile.am similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/Makefile.am rename to Code/Mantid/Testing/Tools/gmock-1.7.0/Makefile.am diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/Makefile.in b/Code/Mantid/Testing/Tools/gmock-1.7.0/Makefile.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/Makefile.in rename to Code/Mantid/Testing/Tools/gmock-1.7.0/Makefile.in diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/README b/Code/Mantid/Testing/Tools/gmock-1.7.0/README similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/README rename to Code/Mantid/Testing/Tools/gmock-1.7.0/README diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/aclocal.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/aclocal.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/aclocal.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/aclocal.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/build-aux/config.guess b/Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/config.guess similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/build-aux/config.guess rename to Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/config.guess diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/build-aux/config.h.in b/Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/config.h.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/build-aux/config.h.in rename to Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/config.h.in diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/build-aux/config.sub b/Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/config.sub similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/build-aux/config.sub rename to Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/config.sub diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/build-aux/depcomp b/Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/depcomp similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/build-aux/depcomp rename to Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/depcomp diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/build-aux/install-sh b/Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/install-sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/build-aux/install-sh rename to Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/install-sh diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/build-aux/ltmain.sh b/Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/ltmain.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/build-aux/ltmain.sh rename to Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/ltmain.sh diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/build-aux/missing b/Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/missing similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/build-aux/missing rename to Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/missing diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/configure b/Code/Mantid/Testing/Tools/gmock-1.7.0/configure similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/configure rename to Code/Mantid/Testing/Tools/gmock-1.7.0/configure diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/configure.ac b/Code/Mantid/Testing/Tools/gmock-1.7.0/configure.ac similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/configure.ac rename to Code/Mantid/Testing/Tools/gmock-1.7.0/configure.ac diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gmock-gtest-all.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gmock-gtest-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gmock-gtest-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gmock-gtest-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gmock/gmock.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gmock/gmock.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gmock/gmock.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gmock/gmock.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gmock_main.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gmock_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gmock_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gmock_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gtest/gtest.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gtest/gtest.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gtest/gtest.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gtest/gtest.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/CHANGES b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/CHANGES similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/CHANGES rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/CHANGES diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/CMakeLists.txt b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/CMakeLists.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/CMakeLists.txt rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/CMakeLists.txt diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/CONTRIBUTORS b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/CONTRIBUTORS similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/CONTRIBUTORS rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/CONTRIBUTORS diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/LICENSE b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/LICENSE similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/LICENSE rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/LICENSE diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/Makefile.am b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/Makefile.am similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/Makefile.am rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/Makefile.am diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/Makefile.in b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/Makefile.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/Makefile.in rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/Makefile.in diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/README b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/README similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/README rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/README diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/aclocal.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/aclocal.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/aclocal.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/aclocal.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/config.guess b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/config.guess similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/config.guess rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/config.guess diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/config.h.in b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/config.h.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/config.h.in rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/config.h.in diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/config.sub b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/config.sub similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/config.sub rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/config.sub diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/depcomp b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/depcomp similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/depcomp rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/depcomp diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/install-sh b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/install-sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/install-sh rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/install-sh diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/ltmain.sh b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/ltmain.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/ltmain.sh rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/ltmain.sh diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/missing b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/missing similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/missing rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/missing diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/cmake/internal_utils.cmake b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/cmake/internal_utils.cmake similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/cmake/internal_utils.cmake rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/cmake/internal_utils.cmake diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest.cbproj b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest.cbproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest.cbproj rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest.cbproj diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest.groupproj b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest.groupproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest.groupproj rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest.groupproj diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_all.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_all.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_link.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_link.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_link.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_link.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_main.cbproj b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_main.cbproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_main.cbproj rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_main.cbproj diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_unittest.cbproj b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_unittest.cbproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_unittest.cbproj rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_unittest.cbproj diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/configure b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/configure similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/configure rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/configure diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/configure.ac b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/configure.ac similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/configure.ac rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/configure.ac diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/fused-src/gtest/gtest-all.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/fused-src/gtest/gtest-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/fused-src/gtest/gtest-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/fused-src/gtest/gtest-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/fused-src/gtest/gtest.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/fused-src/gtest/gtest.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/fused-src/gtest/gtest.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/fused-src/gtest/gtest.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/fused-src/gtest/gtest_main.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/fused-src/gtest/gtest_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/fused-src/gtest/gtest_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/fused-src/gtest/gtest_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-death-test.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-death-test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-death-test.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-death-test.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-message.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-message.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-message.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-message.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-printers.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-printers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-printers.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-printers.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-spi.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-spi.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-spi.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-spi.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-test-part.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-test-part.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-test-part.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-test-part.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-typed-test.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-typed-test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-typed-test.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-typed-test.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest_pred_impl.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest_pred_impl.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest_pred_impl.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest_pred_impl.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest_prod.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest_prod.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest_prod.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest_prod.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-death-test-internal.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-death-test-internal.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-death-test-internal.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-death-test-internal.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-filepath.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-filepath.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-filepath.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-filepath.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-internal.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-internal.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-internal.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-internal.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-linked_ptr.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-linked_ptr.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-linked_ptr.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-linked_ptr.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-port.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-port.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-port.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-port.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-string.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-string.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-string.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-string.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/acx_pthread.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/acx_pthread.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/acx_pthread.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/acx_pthread.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/gtest.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/gtest.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/gtest.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/gtest.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/libtool.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/libtool.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/libtool.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/libtool.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/ltoptions.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/ltoptions.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/ltoptions.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/ltoptions.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/ltsugar.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/ltsugar.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/ltsugar.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/ltsugar.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/ltversion.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/ltversion.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/ltversion.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/ltversion.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/lt~obsolete.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/lt~obsolete.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/lt~obsolete.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/lt~obsolete.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/prime_tables.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/prime_tables.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/prime_tables.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/prime_tables.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample1.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample1.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample1.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample1.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample1.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample1.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample1.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample1.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample10_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample10_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample10_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample10_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample1_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample1_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample1_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample1_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample2.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample2.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample2.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample2.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample2.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample2.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample2.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample2.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample2_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample2_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample2_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample2_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample3-inl.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample3-inl.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample3-inl.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample3-inl.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample3_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample3_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample3_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample3_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample4.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample4.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample4.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample4.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample4.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample4.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample4.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample4.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample4_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample4_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample4_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample4_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample5_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample5_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample5_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample5_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample6_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample6_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample6_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample6_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample7_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample7_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample7_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample7_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample8_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample8_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample8_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample8_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample9_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample9_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample9_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample9_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/fuse_gtest_files.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/fuse_gtest_files.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/fuse_gtest_files.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/fuse_gtest_files.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/gen_gtest_pred_impl.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/gen_gtest_pred_impl.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/gen_gtest_pred_impl.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/gen_gtest_pred_impl.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/gtest-config.in b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/gtest-config.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/gtest-config.in rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/gtest-config.in diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/pump.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/pump.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/pump.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/pump.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-all.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-death-test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-death-test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-death-test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-death-test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-filepath.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-filepath.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-filepath.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-filepath.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-internal-inl.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-internal-inl.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-internal-inl.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-internal-inl.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-port.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-port.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-port.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-port.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-printers.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-printers.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-printers.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-printers.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-test-part.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-test-part.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-test-part.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-test-part.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-typed-test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-typed-test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-typed-test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-typed-test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest_main.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-death-test_ex_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-death-test_ex_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-death-test_ex_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-death-test_ex_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-death-test_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-death-test_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-death-test_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-death-test_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-filepath_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-filepath_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-filepath_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-filepath_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-linked_ptr_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-linked_ptr_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-linked_ptr_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-linked_ptr_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-listener_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-listener_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-listener_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-listener_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-message_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-message_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-message_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-message_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-options_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-options_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-options_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-options_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-param-test2_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-param-test2_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-param-test2_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-param-test2_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-param-test_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-param-test_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-param-test_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-param-test_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-param-test_test.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-param-test_test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-param-test_test.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-param-test_test.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-port_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-port_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-port_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-port_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-printers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-printers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-printers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-printers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-test-part_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-test-part_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-test-part_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-test-part_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-tuple_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-tuple_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-tuple_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-tuple_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-typed-test2_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-typed-test2_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-typed-test2_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-typed-test2_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-typed-test_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-typed-test_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-typed-test_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-typed-test_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-typed-test_test.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-typed-test_test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-typed-test_test.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-typed-test_test.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-unittest-api_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-unittest-api_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-unittest-api_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-unittest-api_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_all_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_all_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_all_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_all_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_color_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_color_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_color_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_color_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_color_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_color_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_color_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_color_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_env_var_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_env_var_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_env_var_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_env_var_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_env_var_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_env_var_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_env_var_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_env_var_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_environment_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_environment_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_environment_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_environment_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_filter_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_filter_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_filter_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_filter_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_filter_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_filter_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_filter_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_filter_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_help_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_help_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_help_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_help_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_help_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_help_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_help_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_help_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_main_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_main_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_main_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_main_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_no_test_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_no_test_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_no_test_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_no_test_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_output_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_output_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_output_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_output_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_output_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_output_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_output_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_output_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_output_test_golden_lin.txt b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_output_test_golden_lin.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_output_test_golden_lin.txt rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_output_test_golden_lin.txt diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_pred_impl_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_pred_impl_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_pred_impl_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_pred_impl_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_premature_exit_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_premature_exit_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_premature_exit_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_premature_exit_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_prod_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_prod_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_prod_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_prod_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_repeat_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_repeat_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_repeat_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_repeat_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_shuffle_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_shuffle_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_shuffle_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_shuffle_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_shuffle_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_shuffle_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_shuffle_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_shuffle_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_sole_header_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_sole_header_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_sole_header_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_sole_header_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_stress_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_stress_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_stress_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_stress_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_test_utils.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_test_utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_test_utils.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_test_utils.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_ex_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_ex_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_ex_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_ex_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_uninitialized_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_uninitialized_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_uninitialized_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_uninitialized_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_uninitialized_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_uninitialized_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_uninitialized_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_uninitialized_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_outfile1_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_outfile1_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_outfile1_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_outfile1_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_outfile2_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_outfile2_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_outfile2_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_outfile2_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_outfiles_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_outfiles_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_outfiles_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_outfiles_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_test_utils.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_test_utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_test_utils.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_test_utils.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/production.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/production.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/production.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/production.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/production.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/production.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/production.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/production.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/DebugProject.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/DebugProject.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/DebugProject.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/DebugProject.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/FrameworkTarget.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/FrameworkTarget.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/FrameworkTarget.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/FrameworkTarget.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/General.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/General.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/General.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/General.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/ReleaseProject.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/ReleaseProject.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/ReleaseProject.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/ReleaseProject.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/TestTarget.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/TestTarget.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/TestTarget.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/TestTarget.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Resources/Info.plist b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Resources/Info.plist similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Resources/Info.plist rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Resources/Info.plist diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/Info.plist b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/Info.plist similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/Info.plist rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/Info.plist diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/runtests.sh b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/runtests.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/runtests.sh rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/runtests.sh diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Scripts/runtests.sh b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Scripts/runtests.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Scripts/runtests.sh rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Scripts/runtests.sh diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Scripts/versiongenerate.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Scripts/versiongenerate.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Scripts/versiongenerate.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Scripts/versiongenerate.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/gtest.xcodeproj/project.pbxproj b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/gtest.xcodeproj/project.pbxproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/gtest.xcodeproj/project.pbxproj rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/gtest.xcodeproj/project.pbxproj diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-actions.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-actions.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-actions.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-actions.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-cardinalities.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-cardinalities.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-cardinalities.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-cardinalities.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-actions.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-actions.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-actions.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-actions.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-actions.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-actions.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-actions.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-actions.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-matchers.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-matchers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-matchers.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-matchers.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-more-actions.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-more-actions.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-more-actions.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-more-actions.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-more-matchers.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-more-matchers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-more-matchers.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-more-matchers.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-spec-builders.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-spec-builders.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-spec-builders.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-spec-builders.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-internal-utils.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-internal-utils.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-internal-utils.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-internal-utils.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-port.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-port.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-port.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-port.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/msvc/2005/gmock_config.vsprops b/Code/Mantid/Testing/Tools/gmock-1.7.0/msvc/2005/gmock_config.vsprops similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/msvc/2005/gmock_config.vsprops rename to Code/Mantid/Testing/Tools/gmock-1.7.0/msvc/2005/gmock_config.vsprops diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/msvc/2010/gmock_config.props b/Code/Mantid/Testing/Tools/gmock-1.7.0/msvc/2010/gmock_config.props similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/msvc/2010/gmock_config.props rename to Code/Mantid/Testing/Tools/gmock-1.7.0/msvc/2010/gmock_config.props diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/fuse_gmock_files.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/fuse_gmock_files.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/fuse_gmock_files.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/fuse_gmock_files.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/LICENSE b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/LICENSE similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/LICENSE rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/LICENSE diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/README b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/README similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/README rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/README diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/README.cppclean b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/README.cppclean similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/README.cppclean rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/README.cppclean diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/__init__.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/__init__.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/__init__.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/__init__.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/ast.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/ast.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/ast.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/ast.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/gmock_class.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/gmock_class.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/gmock_class.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/gmock_class.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/keywords.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/keywords.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/keywords.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/keywords.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/tokenize.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/tokenize.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/tokenize.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/tokenize.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/utils.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/utils.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/utils.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/gmock_gen.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/gmock_gen.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/gmock_gen.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/gmock_gen.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/gmock-config.in b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/gmock-config.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/gmock-config.in rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/gmock-config.in diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-all.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-cardinalities.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-cardinalities.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-cardinalities.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-cardinalities.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-internal-utils.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-internal-utils.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-internal-utils.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-internal-utils.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-matchers.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-matchers.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-matchers.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-matchers.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-spec-builders.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-spec-builders.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-spec-builders.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-spec-builders.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/src/gmock.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/src/gmock.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/src/gmock_main.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/src/gmock_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-actions_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-actions_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-actions_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-actions_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-cardinalities_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-cardinalities_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-cardinalities_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-cardinalities_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-actions_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-actions_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-actions_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-actions_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-function-mockers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-function-mockers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-function-mockers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-function-mockers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-internal-utils_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-internal-utils_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-internal-utils_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-internal-utils_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-matchers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-matchers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-matchers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-matchers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-internal-utils_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-internal-utils_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-internal-utils_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-internal-utils_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-matchers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-matchers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-matchers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-matchers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-more-actions_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-more-actions_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-more-actions_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-more-actions_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-nice-strict_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-nice-strict_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-nice-strict_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-nice-strict_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-port_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-port_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-port_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-port_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-spec-builders_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-spec-builders_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-spec-builders_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-spec-builders_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_all_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_all_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_all_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_all_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_ex_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_ex_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_ex_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_ex_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_leak_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_leak_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_leak_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_leak_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_leak_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_leak_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_leak_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_leak_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_link2_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_link2_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_link2_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_link2_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_link_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_link_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_link_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_link_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_link_test.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_link_test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_link_test.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_link_test.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_output_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_output_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_output_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_output_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_output_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_output_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_output_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_output_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_output_test_golden.txt b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_output_test_golden.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_output_test_golden.txt rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_output_test_golden.txt diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_stress_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_stress_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_stress_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_stress_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_test_utils.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_test_utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_test_utils.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_test_utils.py diff --git a/Code/Mantid/TestingTools/pyunit_gen/pyunit_gen.py b/Code/Mantid/Testing/Tools/pyunit_gen/pyunit_gen.py similarity index 100% rename from Code/Mantid/TestingTools/pyunit_gen/pyunit_gen.py rename to Code/Mantid/Testing/Tools/pyunit_gen/pyunit_gen.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/LICENSE b/Code/Mantid/Testing/Tools/unittest-xml-reporting/LICENSE similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/LICENSE rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/LICENSE diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/MANIFEST.in b/Code/Mantid/Testing/Tools/unittest-xml-reporting/MANIFEST.in similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/MANIFEST.in rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/MANIFEST.in diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/README.rst b/Code/Mantid/Testing/Tools/unittest-xml-reporting/README.rst similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/README.rst rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/README.rst diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/fabfile.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/fabfile.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/fabfile.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/fabfile.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/setup.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/setup.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/setup.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/setup.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/__init__.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/__init__.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/__init__.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/__init__.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/extra/__init__.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/extra/__init__.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/extra/__init__.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/extra/__init__.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/extra/djangotestrunner.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/extra/djangotestrunner.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/extra/djangotestrunner.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/extra/djangotestrunner.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/__init__.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/__init__.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/__init__.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/__init__.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/errord_test_case.xml b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/errord_test_case.xml similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/errord_test_case.xml rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/errord_test_case.xml diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/failed_test_case.xml b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/failed_test_case.xml similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/failed_test_case.xml rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/failed_test_case.xml diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/mixed_test_case.xml b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/mixed_test_case.xml similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/mixed_test_case.xml rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/mixed_test_case.xml diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/successful_test_case.xml b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/successful_test_case.xml similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/successful_test_case.xml rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/successful_test_case.xml diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/testsuite.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/testsuite.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/testsuite.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/testsuite.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/testsuite_cases.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/testsuite_cases.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/testsuite_cases.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/testsuite_cases.py diff --git a/Code/Mantid/Vates/VatesAPI/test/runTests.sh b/Code/Mantid/Vates/VatesAPI/test/runTests.sh deleted file mode 100755 index b223a9bad41b..000000000000 --- a/Code/Mantid/Vates/VatesAPI/test/runTests.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/bin/bash -# Simple script to build and run the tests. -# Will run all tests in the directory if no arguments are supplied, -# or alternatively just the test files given as arguments. -# -# You will need to have the directories containing the Mantid -# .so libraries in your LD_LIBRARY_PATH environment variable -# -# Author: Owen Arnold 02/12/2010 -# - -# Clean up any old executable -rm -rf runner.* - -echo "Generating the source file from the test header files..." -# Chaining all tests together can have effects that you don't think of -# - it's always a good idea to run your new/changed test on its own -test_files="" -if [ $# -eq 0 ]; then - test_files=*.h -else - test_files=$* -fi - -cxxtestgen=../../../../Third_Party/src/cxxtest/cxxtestgen.py -python $cxxtestgen --runner=MantidPrinter -o runner.cpp $test_files - - -echo "Compiling the test executable..." - -#TODO set path properly -mantid_libpath=~/workspace/MantidDebug/bin -#TODO set path properly -vtk_libpath=/usr/local/2.1.1/linux-x86_64/lib -#TODO set path properly -gmock_libpath=../../../TestingTools/lib/ubuntu-10.10 - -g++ -O0 -g3 -DBOOST_DATE_TIME_POSIX_TIME_STD_CONFIG -o runner.exe runner.cpp -I../../../Framework/Kernel/inc -I../../../Framework/MDAlgorithms/inc -I../../../Framework/API/inc -I../inc/VisitPlugins -I/usr/local/2.1.1/linux-x86_64/include/vtk/include/vtk-5.0 -I../../../Framework/Geometry/inc -I ../inc \ - -I ../../../../Third_Party/src/cxxtest -I ../../../../Third_Party/include -I ../../../TestingTools/include -L$vtk_libpath -L$mantid_libpath -L$gmock_libpath -lvtkCommon -lvtkFiltering -lMantidKernel -lMantidGeometry -lMantidAPI -lboost_date_time-mt -lgmock -lMantidMDAlgorithms -lMantidDataObjects -lMantidVisitPresenters -lhdf5 -Wno-deprecated - -echo - -echo "Running the tests..." -ln ../../../Framework/Build/Tests/*.properties . -LD_LIBRARY_PATH=$vtk_libpath:$mantid_libpath:$LD_LIBRARY_PATH ./runner.exe -#valgrind --leak-check=full --show-reachable=yes --track-origins=yes ~/mantid/Code/Vates/VisitPresenters/test/runner.exe -echo - -# Remove the generated files to ensure that they're not inadvertently run -# when something in the chain has failed. -echo "Cleaning up..." -rm -f *.properties -rm -f *Test.log -rm -f *.so -echo "Done." From 2a9667a336d6511d163267fe5cc3b78972026c4c Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Thu, 12 Feb 2015 13:24:38 +0000 Subject: [PATCH 078/414] Implement new plot widget on bayes interfaces Refs #11036 --- .../Indirect/Quasi.ui | 66 ++++++++----------- .../Indirect/ResNorm.ui | 48 +++++++------- .../Indirect/Stretch.ui | 19 +++++- .../CustomInterfaces/src/Indirect/Quasi.cpp | 30 +++------ .../CustomInterfaces/src/Indirect/ResNorm.cpp | 32 +++------ .../CustomInterfaces/src/Indirect/Stretch.cpp | 13 ++-- 6 files changed, 91 insertions(+), 117 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Quasi.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Quasi.ui index 053f3108129b..03c3c1913ab0 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Quasi.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Quasi.ui @@ -24,7 +24,7 @@ - + 0 @@ -56,14 +56,14 @@ - + 0 0 - + true @@ -80,7 +80,7 @@ _sqw.nxs - + false @@ -137,14 +137,14 @@ - + false - + .dat @@ -214,7 +214,7 @@ - + false @@ -224,7 +224,7 @@ 0 - + false @@ -237,7 +237,7 @@ _ResNorm.nxs - + false @@ -268,7 +268,18 @@ - + + + true + + + + 255 + 255 + 255 + + + @@ -281,7 +292,7 @@ - + 0 @@ -299,33 +310,6 @@ - - - - Data - - - - - - - Fit - - - color: rgb(255, 0, 0); - - - - - - - Diff - - - color: rgb(0, 255, 0); - - - @@ -442,6 +426,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ResNorm.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ResNorm.ui index e4c4685232ee..a28014bef735 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ResNorm.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ResNorm.ui @@ -27,14 +27,14 @@
- + 0 0 - + true @@ -52,7 +52,7 @@ _sqw.nxs - + false @@ -65,14 +65,14 @@ - + 0 0 - + true @@ -102,7 +102,18 @@ - + + + true + + + + 255 + 255 + 255 + + + @@ -115,7 +126,7 @@ - + 0 @@ -133,23 +144,6 @@ - - - - Vanadium - - - - - - - Fit - - - color: rgb(255, 0, 0); - - - @@ -260,6 +254,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Stretch.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Stretch.ui index da7af34497c8..7c986a625b71 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Stretch.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Stretch.ui @@ -170,7 +170,18 @@ - + + + + 255 + 255 + 255 + + + + true + + @@ -272,6 +283,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp index e70b4d3310fe..c93d79c5b4fd 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp @@ -14,15 +14,8 @@ namespace MantidQt { m_uiForm.setupUi(parent); - // Create the plot - m_plots["QuasiPlot"] = new QwtPlot(m_parentWidget); - m_plots["QuasiPlot"]->setCanvasBackground(Qt::white); - m_plots["QuasiPlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); - m_plots["QuasiPlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); - m_uiForm.plotSpace->addWidget(m_plots["QuasiPlot"]); - // Create range selector - m_rangeSelectors["QuasiERange"] = new MantidWidgets::RangeSelector(m_plots["QuasiPlot"]); + m_rangeSelectors["QuasiERange"] = new MantidWidgets::RangeSelector(m_uiForm.ppPlot); connect(m_rangeSelectors["QuasiERange"], SIGNAL(minValueChanged(double)), this, SLOT(minValueChanged(double))); connect(m_rangeSelectors["QuasiERange"], SIGNAL(maxValueChanged(double)), this, SLOT(maxValueChanged(double))); @@ -215,8 +208,10 @@ namespace MantidQt if(!m_uiForm.dsSample->isValid()) return; + m_uiForm.ppPlot->clear(); + QString sampleName = m_uiForm.dsSample->getCurrentDataName(); - plotMiniPlot(sampleName, m_previewSpec, "QuasiPlot", "RawPlotCurve"); + m_uiForm.ppPlot->addSpectrum("Sample", sampleName, m_previewSpec); // Update fit plot QString program = m_uiForm.cbProgram->currentText(); @@ -252,19 +247,11 @@ namespace MantidQt QString specName = QString::fromStdString(axis->label(histIndex)); if(specName.contains("fit")) - { - plotMiniPlot(outputWorkspace, histIndex, "QuasiPlot", specName); - m_curves[specName]->setPen(QColor(Qt::red)); - } + m_uiForm.ppPlot->addSpectrum(specName, outputWorkspace, histIndex, Qt::red); if(specName.contains("diff")) - { - plotMiniPlot(outputWorkspace, histIndex, "QuasiPlot", specName); - m_curves[specName]->setPen(QColor(Qt::green)); - } + m_uiForm.ppPlot->addSpectrum(specName, outputWorkspace, histIndex, Qt::green); } - - replot("QuasiPlot"); } /** @@ -278,10 +265,9 @@ namespace MantidQt MatrixWorkspace_sptr inWs = AnalysisDataService::Instance().retrieveWS(filename.toStdString()); int numHist = static_cast(inWs->getNumberHistograms()) - 1; m_uiForm.spPreviewSpectrum->setMaximum(numHist); - removeAllCurves(); - replot("QuasiPlot"); updateMiniPlot(); - std::pair range = getCurveRange("RawPlotCurve"); + QPair curveRange = m_uiForm.ppPlot->getCurveRange("Sample"); + std::pair range(curveRange.first, curveRange.second); setMiniPlotGuides("QuasiERange", m_properties["EMin"], m_properties["EMax"], range); setPlotRange("QuasiERange", m_properties["EMin"], m_properties["EMax"], range); } diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ResNorm.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ResNorm.cpp index a9ccfd47614b..72c9be7a05d8 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ResNorm.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ResNorm.cpp @@ -13,15 +13,8 @@ namespace MantidQt { m_uiForm.setupUi(parent); - // Create the plot - m_plots["ResNormPlot"] = new QwtPlot(m_parentWidget); - m_plots["ResNormPlot"]->setCanvasBackground(Qt::white); - m_plots["ResNormPlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); - m_plots["ResNormPlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); - m_uiForm.plotSpace->addWidget(m_plots["ResNormPlot"]); - // Create range selector - m_rangeSelectors["ResNormERange"] = new MantidWidgets::RangeSelector(m_plots["ResNormPlot"]); + m_rangeSelectors["ResNormERange"] = new MantidWidgets::RangeSelector(m_uiForm.ppPlot); connect(m_rangeSelectors["ResNormERange"], SIGNAL(minValueChanged(double)), this, SLOT(minValueChanged(double))); connect(m_rangeSelectors["ResNormERange"], SIGNAL(maxValueChanged(double)), this, SLOT(maxValueChanged(double))); @@ -63,7 +56,7 @@ namespace MantidQt bool ResNorm::validate() { UserInputValidator uiv; - uiv.checkDataSelectorIsValid("Sample", m_uiForm.dsVanadium); + uiv.checkDataSelectorIsValid("Vanadium", m_uiForm.dsVanadium); uiv.checkDataSelectorIsValid("Resolution", m_uiForm.dsResolution); QString errors = uiv.generateErrorMessage(); @@ -111,10 +104,7 @@ namespace MantidQt runPythonScript(pyInput); // Plot the fit curve - plotMiniPlot("Fit", m_previewSpec, "ResNormPlot", "ResNormFitCurve"); - m_curves["ResNormFitCurve"]->setPen(QColor(Qt::red)); - - replot("ResNormPlot"); + m_uiForm.ppPlot->addSpectrum("Fit", "Fit", m_previewSpec, Qt::red); } /** @@ -137,9 +127,10 @@ namespace MantidQt */ void ResNorm::handleVanadiumInputReady(const QString& filename) { - plotMiniPlot(filename, m_previewSpec, "ResNormPlot", "RawPlotCurve"); - std::pair res; - std::pair range = getCurveRange("RawPlotCurve"); + m_uiForm.ppPlot->addSpectrum("Vanadium", filename, m_previewSpec); + std::pair res; + QPair curveRange = m_uiForm.ppPlot->getCurveRange("Vanadium"); + std::pair range(curveRange.first, curveRange.second); MatrixWorkspace_sptr vanWs = AnalysisDataService::Instance().retrieveWS(filename.toStdString()); m_uiForm.spPreviewSpectrum->setMaximum(static_cast(vanWs->getNumberHistograms()) - 1); @@ -209,15 +200,10 @@ namespace MantidQt m_previewSpec = value; if(m_uiForm.dsVanadium->isValid()) - plotMiniPlot(m_uiForm.dsVanadium->getCurrentDataName(), m_previewSpec, "ResNormPlot", "RawPlotCurve"); + m_uiForm.ppPlot->addSpectrum("Vanadium", m_uiForm.dsVanadium->getCurrentDataName(), m_previewSpec); if(AnalysisDataService::Instance().doesExist("Fit")) - { - plotMiniPlot("Fit", m_previewSpec, "ResNormPlot", "ResNormFitCurve"); - m_curves["ResNormFitCurve"]->setPen(QColor(Qt::red)); - } - - replot("ResNormPlot"); + m_uiForm.ppPlot->addSpectrum("Fit", "Fit", m_previewSpec, Qt::red); } } // namespace CustomInterfaces diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp index 616c9ff85231..696dc523c72e 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp @@ -15,15 +15,9 @@ namespace MantidQt { m_uiForm.setupUi(parent); - // Create the plot - m_plots["StretchPlot"] = new QwtPlot(m_parentWidget); - m_plots["StretchPlot"]->setCanvasBackground(Qt::white); - m_plots["StretchPlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); - m_plots["StretchPlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); - m_uiForm.plotSpace->addWidget(m_plots["StretchPlot"]); // Create range selector - m_rangeSelectors["StretchERange"] = new MantidWidgets::RangeSelector(m_plots["StretchPlot"]); + m_rangeSelectors["StretchERange"] = new MantidWidgets::RangeSelector(m_uiForm.ppPlot); connect(m_rangeSelectors["StretchERange"], SIGNAL(minValueChanged(double)), this, SLOT(minValueChanged(double))); connect(m_rangeSelectors["StretchERange"], SIGNAL(maxValueChanged(double)), this, SLOT(maxValueChanged(double))); @@ -159,8 +153,9 @@ namespace MantidQt */ void Stretch::handleSampleInputReady(const QString& filename) { - plotMiniPlot(filename, 0, "StretchPlot", "RawPlotCurve"); - std::pair range = getCurveRange("RawPlotCurve"); + m_uiForm.ppPlot->addSpectrum("Sample", filename, 0); + QPair curveRange = m_uiForm.ppPlot->getCurveRange("Sample"); + std::pair range(curveRange.first, curveRange.second); setMiniPlotGuides("StretchERange", m_properties["EMin"], m_properties["EMax"], range); setPlotRange("StretchERange", m_properties["EMin"], m_properties["EMax"], range); } From 27f414fbc773bfd8170b12d646f0971c72a8236e Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Thu, 12 Feb 2015 14:02:27 +0000 Subject: [PATCH 079/414] Fix issue with labls updating Refs #11036 --- Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index 61b7ce07d6fe..c0b6cf6fd44e 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -233,13 +233,12 @@ void PreviewPlot::addSpectrum(const QString & curveName, const MatrixWorkspace_s // Create the curve label QLabel *label = new QLabel(curveName); + label->setVisible(false); QPalette palette = label->palette(); palette.setColor(label->foregroundRole(), curveColour); label->setPalette(palette); - label->setVisible(legendIsShown()); - label->setWordWrap(true); - label->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); m_uiForm.loLegend->addWidget(label); + label->setVisible(legendIsShown()); m_curves[curveName].ws = ws; m_curves[curveName].curve = curve; From a04fcde29ddec64d204dd758684371b75c2486c9 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Thu, 12 Feb 2015 15:49:35 +0000 Subject: [PATCH 080/414] Re #9556 updating notation, array indexing, bin width --- .../CurveFitting/src/DynamicKuboToyabe.cpp | 95 +++++++++---------- 1 file changed, 47 insertions(+), 48 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index 613853730dbb..c0a23cde1a22 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -40,72 +40,71 @@ void DynamicKuboToyabe::init() declareParameter("Nu", 0.0, "Hopping rate"); } -double getDKT (double t, double sig, double nu){ +// Static Zero Field Kubo Toyabe relaxation function +double ZFKT (const double x, const double G){ + + const double q = G*G*x*x; + return (0.3333333333 + 0.6666666667*exp(-0.5*q)*(1-q)); +} + +// Static Non-Zero field Kubo Toyabe relaxation function +double HKT (const double x, const double G, const double F) +{ + throw std::runtime_error("HKT not implemented yet"); +} -#define tsmax 656 // 16 us of valid data -#define stk 25 -#define eps 0.05 // bin for calculations +// Dynamic Kubo-Toyabe +double getDKT (double t, double G, double v){ + const int tsmax = 656; // Length of the time axis, 32 us of valid data + const double eps = 0.05; // Bin width for calculations + // const int stk = 25; // Not used for the moment - int k,j, xi; - static double gs[tsmax+1], gd[tsmax+1]; - double y, tt, hop, xe; - static double oldsig=-1., oldnu=-1.; + static double oldG=-1., oldV=-1.; + static std::vector gStat(tsmax), gDyn(tsmax); - if ( (sig == oldsig) && (nu == oldnu) ){ - // Re-use previous computation - xi=int(fabs(t)/eps); - if (xi>tsmax-2) - xi = tsmax-2; - xe=(fabs(t)/eps)-xi; - return gd[xi+1]*(1-xe)+xe*gd[xi+2]; + // If previous call was for the same G, v + // Re-use previous computation + if ( (G == oldG) && (v == oldV) ){ + int x=int(fabs(t)/eps); + if (x>tsmax-2) + x = tsmax-2; + double xe=(fabs(t)/eps)-x; + return gDyn[x]*(1-xe)+xe*gDyn[x+1]; } + + // Else, store new values + oldG =G; + oldV =v; - oldsig=sig; - oldnu =nu; - - hop = nu*eps; + double hop = v*eps; // Generate static Kubo-Toyabe - for (k=1; k<=tsmax; k++){ - tt = (k-1)*eps*sig*(k-1)*eps*sig; - gs[k]=0.3333333333+0.6666666667*(1-tt)*exp(-tt/2); + for (size_t k=0; k=2; j--){ - y=y*(1-hop)+hop*gd[k-j+1]*gs[j]; + // Generate dynamic Kubo Toyabe + for (int k=0; k0; j--){ + y=y*(1-hop)+hop*gDyn[k-j]*gStat[j]; } - gd[k]=y; + gDyn[k]=y; } - - // Interpolate table. If beyond end, extrapolate... - xi=int(abs(t)/eps); - if (xi>tsmax-2) - xi = tsmax-2; - xe=abs(t)/eps-xi; - return gd[xi+1]*(1-xe)+xe*gd[xi+2]; + // Interpolate table + // If beyond end, extrapolate + int x=int(abs(t)/eps); + if (x>tsmax-2) + x = tsmax-2; + double xe=(fabs(t)/eps)-x; + return gDyn[x]*(1-xe)+xe*gDyn[x+1]; } -// Zero Field Kubo Toyabe relaxation function -double ZFKT (const double x, const double G){ - - const double q = G*G*x*x; - return (0.3333333333 + 0.6666666667*exp(-0.5*q)*(1-q)); -} - -// Non-Zero field Kubo Toyabe relaxation function -double HKT (const double x, const double G, const double F) -{ - throw std::runtime_error("HKT not implemented yet"); -} - // Dynamic Kubo Toyabe function void DynamicKuboToyabe::function1D(double* out, const double* xValues, const size_t nData)const { From be9daee5756776a78759983629b2d8d2c9b43550 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Thu, 12 Feb 2015 16:39:17 +0000 Subject: [PATCH 081/414] Clean up a screenshot after the test Refs #10870 --- Code/Mantid/MantidPlot/test/MantidPlotSliceViewerTest.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/test/MantidPlotSliceViewerTest.py b/Code/Mantid/MantidPlot/test/MantidPlotSliceViewerTest.py index a3f7a0e3a8f7..27961933c3f1 100644 --- a/Code/Mantid/MantidPlot/test/MantidPlotSliceViewerTest.py +++ b/Code/Mantid/MantidPlot/test/MantidPlotSliceViewerTest.py @@ -113,10 +113,14 @@ def test_saveImage(self): if not dest is None: filename = "SliceViewerSaveImage" filepath = os.path.join(dest, filename+".png") + # Remove any old file + if os.path.isfile(filepath): + os.remove(filepath) + # Save svw.saveImage(filepath) self.assertEquals(os.path.isfile(filepath), True, "Screenshot was not written out as expected.") - if file_exists: + if os.path.isfile(filepath): os.remove(filepath) def test_showLine(self): From 0d34503f23d55f4fae4c30f9f699738f44b14a38 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Thu, 12 Feb 2015 17:02:04 +0000 Subject: [PATCH 082/414] Make guess curves in fitting interfaces use workspaces Refs #11036 --- .../CustomInterfaces/src/Indirect/ConvFit.cpp | 78 ++++++++++--------- .../CustomInterfaces/src/Indirect/FuryFit.cpp | 22 ++++-- 2 files changed, 56 insertions(+), 44 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp index cd4068268181..b27970e19e28 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp @@ -162,7 +162,7 @@ namespace IDA bool useTies = m_uiForm.ckTieCentres->isChecked(); QString ties = (useTies ? "True" : "False"); - Mantid::API::CompositeFunction_sptr func = createFunction(useTies); + CompositeFunction_sptr func = createFunction(useTies); std::string function = std::string(func->asString()); QString stX = m_properties["StartX"]->valueText(); QString enX = m_properties["EndX"]->valueText(); @@ -213,8 +213,6 @@ namespace IDA */ bool ConvFit::validate() { - using Mantid::API::AnalysisDataService; - UserInputValidator uiv; uiv.checkDataSelectorIsValid("Sample", m_uiForm.dsSampleInput); @@ -334,18 +332,18 @@ namespace IDA * * @returns the composite fitting function. */ - Mantid::API::CompositeFunction_sptr ConvFit::createFunction(bool tieCentres) + CompositeFunction_sptr ConvFit::createFunction(bool tieCentres) { - auto conv = boost::dynamic_pointer_cast(Mantid::API::FunctionFactory::Instance().createFunction("Convolution")); - Mantid::API::CompositeFunction_sptr comp( new Mantid::API::CompositeFunction ); + auto conv = boost::dynamic_pointer_cast(FunctionFactory::Instance().createFunction("Convolution")); + CompositeFunction_sptr comp( new CompositeFunction ); - Mantid::API::IFunction_sptr func; + IFunction_sptr func; size_t index = 0; // ------------------------------------- // --- Composite / Linear Background --- // ------------------------------------- - func = Mantid::API::FunctionFactory::Instance().createFunction("LinearBackground"); + func = FunctionFactory::Instance().createFunction("LinearBackground"); comp->addFunction(func); const int bgType = m_uiForm.cbBackground->currentIndex(); // 0 = Fixed Flat, 1 = Fit Flat, 2 = Fit all @@ -375,27 +373,27 @@ namespace IDA // -------------------------------------------- // --- Composite / Convolution / Resolution --- // -------------------------------------------- - func = Mantid::API::FunctionFactory::Instance().createFunction("Resolution"); + func = FunctionFactory::Instance().createFunction("Resolution"); conv->addFunction(func); //add resolution file if (m_uiForm.dsResInput->isFileSelectorVisible()) { std::string resfilename = m_uiForm.dsResInput->getFullFilePath().toStdString(); - Mantid::API::IFunction::Attribute attr(resfilename); + IFunction::Attribute attr(resfilename); func->setAttribute("FileName", attr); } else { std::string resWorkspace = m_uiForm.dsResInput->getCurrentDataName().toStdString(); - Mantid::API::IFunction::Attribute attr(resWorkspace); + IFunction::Attribute attr(resWorkspace); func->setAttribute("Workspace", attr); } // -------------------------------------------------------- // --- Composite / Convolution / Model / Delta Function --- // -------------------------------------------------------- - Mantid::API::CompositeFunction_sptr model( new Mantid::API::CompositeFunction ); + CompositeFunction_sptr model( new CompositeFunction ); bool useDeltaFunc = m_blnManager->value(m_properties["UseDeltaFunc"]); @@ -403,7 +401,7 @@ namespace IDA if ( useDeltaFunc ) { - func = Mantid::API::FunctionFactory::Instance().createFunction("DeltaFunction"); + func = FunctionFactory::Instance().createFunction("DeltaFunction"); index = model->addFunction(func); std::string parName = createParName(index); populateFunction(func, model, m_properties["DeltaFunction"], parName, false); @@ -414,7 +412,7 @@ namespace IDA // ------------------------------------------------------------ //create temperature correction function to multiply with the lorentzians - Mantid::API::IFunction_sptr tempFunc; + IFunction_sptr tempFunc; QString temperature = m_uiForm.leTempCorrection->text(); bool useTempCorrection = (!temperature.isEmpty() && m_uiForm.ckTempCorrection->isChecked()); @@ -431,14 +429,14 @@ namespace IDA { //if temperature not included then product is lorentzian * 1 //create product function for temp * lorentzian - auto product = boost::dynamic_pointer_cast(Mantid::API::FunctionFactory::Instance().createFunction("ProductFunction")); + auto product = boost::dynamic_pointer_cast(FunctionFactory::Instance().createFunction("ProductFunction")); if(useTempCorrection) { createTemperatureCorrection(product); } - func = Mantid::API::FunctionFactory::Instance().createFunction("Lorentzian"); + func = FunctionFactory::Instance().createFunction("Lorentzian"); subIndex = product->addFunction(func); index = model->addFunction(product); prefix1 = createParName(index, subIndex); @@ -451,14 +449,14 @@ namespace IDA { //if temperature not included then product is lorentzian * 1 //create product function for temp * lorentzian - auto product = boost::dynamic_pointer_cast(Mantid::API::FunctionFactory::Instance().createFunction("ProductFunction")); + auto product = boost::dynamic_pointer_cast(FunctionFactory::Instance().createFunction("ProductFunction")); if(useTempCorrection) { createTemperatureCorrection(product); } - func = Mantid::API::FunctionFactory::Instance().createFunction("Lorentzian"); + func = FunctionFactory::Instance().createFunction("Lorentzian"); subIndex = product->addFunction(func); index = model->addFunction(product); prefix2 = createParName(index, subIndex); @@ -481,18 +479,18 @@ namespace IDA return comp; } - void ConvFit::createTemperatureCorrection(Mantid::API::CompositeFunction_sptr product) + void ConvFit::createTemperatureCorrection(CompositeFunction_sptr product) { //create temperature correction function to multiply with the lorentzians - Mantid::API::IFunction_sptr tempFunc; + IFunction_sptr tempFunc; QString temperature = m_uiForm.leTempCorrection->text(); //create user function for the exponential correction // (x*temp) / 1-exp(-(x*temp)) - tempFunc = Mantid::API::FunctionFactory::Instance().createFunction("UserFunction"); + tempFunc = FunctionFactory::Instance().createFunction("UserFunction"); //11.606 is the conversion factor from meV to K std::string formula = "((x*11.606)/Temp) / (1 - exp(-((x*11.606)/Temp)))"; - Mantid::API::IFunction::Attribute att(formula); + IFunction::Attribute att(formula); tempFunc->setAttribute("Formula", att); tempFunc->setParameter("Temp", temperature.toDouble()); @@ -563,7 +561,7 @@ namespace IDA return lorentzGroup; } - void ConvFit::populateFunction(Mantid::API::IFunction_sptr func, Mantid::API::IFunction_sptr comp, QtProperty* group, const std::string & pref, bool tie) + void ConvFit::populateFunction(IFunction_sptr func, IFunction_sptr comp, QtProperty* group, const std::string & pref, bool tie) { // Get subproperties of group and apply them as parameters on the function object QList props = group->subProperties(); @@ -723,7 +721,7 @@ namespace IDA } bool tieCentres = (m_uiForm.cbFitType->currentIndex() > 1); - Mantid::API::CompositeFunction_sptr function = createFunction(tieCentres); + CompositeFunction_sptr function = createFunction(tieCentres); if ( m_cfInputWS == NULL ) { @@ -750,8 +748,8 @@ namespace IDA } } - Mantid::API::FunctionDomain1DVector domain(inputXData); - Mantid::API::FunctionValues outputData(domain); + FunctionDomain1DVector domain(inputXData); + FunctionValues outputData(domain); function->function(domain, outputData); QVector dataX, dataY; @@ -762,13 +760,21 @@ namespace IDA dataY.append(outputData.getCalculated(i)); } - removeCurve("CFCalcCurve"); - m_curves["CFCalcCurve"] = new QwtPlotCurve(); - m_curves["CFCalcCurve"]->setData(dataX, dataY); - QPen fitPen(Qt::red, Qt::SolidLine); - m_curves["CFCalcCurve"]->setPen(fitPen); - m_curves["CFCalcCurve"]->attach(m_plots["ConvFitPlot"]); - m_plots["ConvFitPlot"]->replot(); + IAlgorithm_sptr createWsAlg = AlgorithmManager::Instance().create("CreateWorkspace"); + createWsAlg->initialize(); + createWsAlg->setChild(true); + createWsAlg->setLogging(false); + createWsAlg->setProperty("OutputWorkspace", "__GuessAnon"); + createWsAlg->setProperty("NSpec", 1); + createWsAlg->setProperty("DataX", dataX.toStdVector()); + createWsAlg->setProperty("DataY", dataY.toStdVector()); + createWsAlg->execute(); + MatrixWorkspace_sptr guessWs = createWsAlg->getProperty("OutputWorkspace"); + + plotMiniPlot(guessWs, 0, "ConvFitPlot", "guess"); + QPen p(Qt::green, Qt::SolidLine); + m_curves["guess"]->setPen(p); + replot("ConvFitPlot"); } void ConvFit::singleFit() @@ -786,7 +792,7 @@ namespace IDA m_uiForm.ckPlotGuess->setChecked(false); - Mantid::API::CompositeFunction_sptr function = createFunction(m_uiForm.ckTieCentres->isChecked()); + CompositeFunction_sptr function = createFunction(m_uiForm.ckTieCentres->isChecked()); // get output name QString fitType = fitTypeString(); @@ -801,7 +807,7 @@ namespace IDA outputNm += QString("conv_") + fitType + bgType + m_uiForm.spPlotSpectrum->text(); std::string output = outputNm.toStdString(); - Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("Fit"); + IAlgorithm_sptr alg = AlgorithmManager::Instance().create("Fit"); alg->initialize(); alg->setPropertyValue("Function", function->asString()); alg->setPropertyValue("InputWorkspace", m_cfInputWSName.toStdString()); @@ -826,7 +832,7 @@ namespace IDA m_curves["CFCalcCurve"]->setPen(fitPen); replot("ConvFitPlot"); - Mantid::API::IFunction_sptr outputFunc = alg->getProperty("Function"); + IFunction_sptr outputFunc = alg->getProperty("Function"); // Get params. QMap parameters; diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/FuryFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/FuryFit.cpp index 39c20d54222e..e445f9c08a15 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/FuryFit.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/FuryFit.cpp @@ -690,14 +690,20 @@ namespace IDA dataX.append(inputXData[i]); dataY.append(outputData.getCalculated(i)); } - - // Create the curve - removeCurve("FF_FitCurve"); - m_curves["FF_FitCurve"] = new QwtPlotCurve(); - m_curves["FF_FitCurve"]->setData(dataX, dataY); - m_curves["FF_FitCurve"]->attach(m_plots["FuryFitPlot"]); - QPen fitPen(Qt::red, Qt::SolidLine); - m_curves["FF_FitCurve"]->setPen(fitPen); + IAlgorithm_sptr createWsAlg = AlgorithmManager::Instance().create("CreateWorkspace"); + createWsAlg->initialize(); + createWsAlg->setChild(true); + createWsAlg->setLogging(false); + createWsAlg->setProperty("OutputWorkspace", "__GuessAnon"); + createWsAlg->setProperty("NSpec", 1); + createWsAlg->setProperty("DataX", dataX.toStdVector()); + createWsAlg->setProperty("DataY", dataY.toStdVector()); + createWsAlg->execute(); + MatrixWorkspace_sptr guessWs = createWsAlg->getProperty("OutputWorkspace"); + + plotMiniPlot(guessWs, 0, "FuryFitPlot", "guess"); + QPen p(Qt::green, Qt::SolidLine); + m_curves["guess"]->setPen(p); replot("FuryFitPlot"); } From a64b1ecb3c525222598acf5527fd72fe7ae7c70e Mon Sep 17 00:00:00 2001 From: Jean Bilheux Date: Thu, 12 Feb 2015 14:47:33 -0500 Subject: [PATCH 083/414] data workspace logs is not copied into final workspace. this resolves #11057 --- .../PythonInterface/plugins/algorithms/RefLReduction.py | 3 ++- .../reduction/instruments/reflectometer/wks_utility.py | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py index 9c173170f685..f8919c00b467 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py @@ -374,7 +374,8 @@ def PyExec(self): final_workspace = wks_utility.createFinalWorkspace(final_x_axis, final_y_axis, final_y_error_axis, - name_output_ws) + name_output_ws, + ws_event_data) self.setProperty('OutputWorkspace', mtd[name_output_ws]) diff --git a/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py b/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py index 0e37f61ed629..4bb4c47ca278 100644 --- a/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py +++ b/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py @@ -1936,14 +1936,15 @@ def createQworkspace(q_axis, y_axis, y_error_axis): return q_workspace -def createFinalWorkspace(q_axis, final_y_axis, final_error_axis, name_output_ws): +def createFinalWorkspace(q_axis, final_y_axis, final_error_axis, name_output_ws, parent_workspace): final_workspace = CreateWorkspace(OutputWorkspace=name_output_ws, DataX=q_axis, DataY=final_y_axis, DataE=final_error_axis, Nspec=1, - UnitX="Wavelength") + UnitX="Wavelength", + ParentWorkspace=parent_workspace) final_workspace.setDistribution(True) return final_workspace From cdaed80f734b07c421c3d520dbd72f0e3eb95831 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Fri, 13 Feb 2015 08:52:25 +0000 Subject: [PATCH 084/414] Re #9556 code refactoring --- .../CurveFitting/src/DynamicKuboToyabe.cpp | 55 ++++++++++--------- 1 file changed, 29 insertions(+), 26 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index c0a23cde1a22..5ece1fe010d9 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -60,44 +60,47 @@ double getDKT (double t, double G, double v){ const double eps = 0.05; // Bin width for calculations // const int stk = 25; // Not used for the moment - static double oldG=-1., oldV=-1.; static std::vector gStat(tsmax), gDyn(tsmax); - // If previous call was for the same G, v - // Re-use previous computation - if ( (G == oldG) && (v == oldV) ){ - int x=int(fabs(t)/eps); - if (x>tsmax-2) - x = tsmax-2; - double xe=(fabs(t)/eps)-x; - return gDyn[x]*(1-xe)+xe*gDyn[x+1]; - } + if ( (G != oldG) || (v != oldV) ){ - // Else, store new values - oldG =G; - oldV =v; + // If G or v have changed with respect to the + // previous call, we need to re-do the computations - double hop = v*eps; - // Generate static Kubo-Toyabe - for (size_t k=0; k0; j--){ - y=y*(1-hop)+hop*gDyn[k-j]*gStat[j]; + // But we only need to + // re-compute gStat if G has changed + + // Generate static Kubo-Toyabe + for (size_t k=0; k0; j--){ + y=y*(1-hop)+hop*gDyn[k-j]*gStat[j]; + } + gDyn[k]=y; } - gDyn[k]=y; } - + // Interpolate table // If beyond end, extrapolate - int x=int(abs(t)/eps); + int x=int(fabs(t)/eps); if (x>tsmax-2) x = tsmax-2; double xe=(fabs(t)/eps)-x; From f1ba93a9240bf912a93d1b422e40be3f5e57197f Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Fri, 13 Feb 2015 10:33:12 +0000 Subject: [PATCH 085/414] Use a driver script for the system tests Avoids duplication of job configuration on the server. Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript | 8 +-- Code/Mantid/Build/Jenkins/systemtests | 71 +++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 6 deletions(-) create mode 100755 Code/Mantid/Build/Jenkins/systemtests diff --git a/Code/Mantid/Build/Jenkins/buildscript b/Code/Mantid/Build/Jenkins/buildscript index b1899d337d4a..2558d3ecbcff 100755 --- a/Code/Mantid/Build/Jenkins/buildscript +++ b/Code/Mantid/Build/Jenkins/buildscript @@ -9,6 +9,7 @@ # BUILD_THREADS & PARAVIEW_DIR should be set in the configuration of each # slave. ############################################################################### +SCRIPT_DIR=$(dirname $(readlink -f "$0")) ############################################################################### # Print out the versions of things we are using @@ -203,10 +204,5 @@ fi # from a package to have at least one Linux checks it install okay ############################################################################### if [[ "${ON_RHEL6}" == true ]] && [[ ${JOB_NAME} == *pull_requests* ]]; then - PKGDIR=${WORKSPACE}/build - # Turn off usage reports and instrument downloading for the mantid call - # that creates the properties file - echo "UpdateInstrumentDefinitions.OnStartup = 0" > $userprops - echo "usagereports.enabled = 0" >> $userprops - python $WORKSPACE/Code/Mantid/Testing/SystemTests/scripts/InstallerTesting.py -o -d $PKGDIR + $SCRIPT_DIR/systemtests fi diff --git a/Code/Mantid/Build/Jenkins/systemtests b/Code/Mantid/Build/Jenkins/systemtests new file mode 100755 index 000000000000..5a792bdf1e41 --- /dev/null +++ b/Code/Mantid/Build/Jenkins/systemtests @@ -0,0 +1,71 @@ +#!/bin/bash -ex +############################################################################### +# LINUX/MAC SCRIPT TO DRIVE THE SYSTEM TESTS OF MANTID +# +# Notes: +# +# WORKSPACE, JOB_NAME, NODE_LABEL GIT_COMMIT are environment variables that +# are set by Jenkins. The last one corresponds to any labels set on a slave. +############################################################################### + +############################################################################### +# Print out the versions of things we are using +############################################################################### +cmake --version +echo "SHA1=${sha1}" + +############################################################################### +# Set up the location for the local object store outside of the build and +# source tree, which can be shared by multiple builds. +# It defaults to the parent directory of the workspace but can be overridden +# by setting the MANTID_DATA_STORE environment variable. +############################################################################### +if [ -z "$MANTID_DATA_STORE" ]; then + export MANTID_DATA_STORE=$(dirname $WORKSPACE) +fi + +############################################################################### +# RHEL6 setup steps - nodes must have a "rhel6" label set (in lowercase) +############################################################################### +if [[ ${NODE_LABELS} == *rhel6* ]]; then + SCL_ON_RHEL6="scl enable mantidlibs" + ON_RHEL6=true +else + SCL_ON_RHEL6="eval" +fi + +############################################################################### +# Create the build directory if it doesn't exist +############################################################################### +[ -d $WORKSPACE/build ] || mkdir $WORKSPACE/build +cd $WORKSPACE/build + +############################################################################### +# CMake configuration if it has not already been configured +# We use the special flag that only creates the targets for the data +############################################################################### +if [[ ! -e $WORKSPACE/build/CMakeCache.txt ]]; then + $SCL_ON_RHEL6 "cmake -DMANTID_DATA_STORE=${MANTID_DATA_STORE} -DTESTING_DATA_ONLY=ON ../Code/Mantid" +fi + +############################################################################### +# Build step +############################################################################### +$SCL_ON_RHEL6 "cmake --build . -- StandardTestData" +$SCL_ON_RHEL6 "cmake --build . -- SystemTestData" + +############################################################################### +# Run the tests +############################################################################### +# Remove any Mantid.user.properties file +userprops=~/.mantid/Mantid.user.properties +rm -f $userprops +# Turn off usage reports and instrument downloading for the mantid call +# that creates the properties file +echo "UpdateInstrumentDefinitions.OnStartup = 0" > $userprops +echo "usagereports.enabled = 0" >> $userprops + +# Run +PKGDIR=${WORKSPACE}/build +python $WORKSPACE/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py -o -d $PKGDIR + From f5248b398624821e21b6ab3187419711e90873f9 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Fri, 13 Feb 2015 10:45:25 +0000 Subject: [PATCH 086/414] Add new plot widget to fury fit Refs #11036 --- .../Indirect/ConvFit.h | 4 +- .../Indirect/ConvFit.ui | 38 ++++++------- .../Indirect/FuryFit.h | 6 +-- .../Indirect/FuryFit.ui | 38 ++++++------- .../CustomInterfaces/src/Indirect/ConvFit.cpp | 49 ++++++----------- .../CustomInterfaces/src/Indirect/FuryFit.cpp | 54 +++++++++---------- .../inc/MantidQtMantidWidgets/PreviewPlot.h | 2 + .../MantidWidgets/src/PreviewPlot.cpp | 12 +++++ 8 files changed, 95 insertions(+), 108 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h index 39655a9a1a11..f31f2d7f4ca7 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h @@ -6,8 +6,6 @@ #include "MantidAPI/MatrixWorkspace.h" #include "MantidAPI/CompositeFunction.h" -#include "boost/shared_ptr.hpp" - namespace MantidQt { namespace CustomInterfaces @@ -61,7 +59,7 @@ namespace IDA QtStringPropertyManager* m_stringManager; QtTreePropertyBrowser* m_cfTree; QMap m_fixedProps; - boost::shared_ptr m_cfInputWS; + Mantid::API::MatrixWorkspace_sptr m_cfInputWS; QString m_cfInputWSName; bool m_confitResFileType; diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.ui index fa74c5fd4fb8..903d3702eece 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.ui @@ -230,10 +230,21 @@ - + + + true + + + + 255 + 255 + 255 + + + - + @@ -254,23 +265,6 @@ - - - - Sample - - - - - - - color: rgb(255, 0, 0); - - - Fit - - - @@ -413,6 +407,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/FuryFit.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/FuryFit.h index a81915796844..f941762f2473 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/FuryFit.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/FuryFit.h @@ -6,8 +6,6 @@ #include "MantidAPI/CompositeFunction.h" #include "MantidAPI/MatrixWorkspace.h" -#include "boost/shared_ptr.hpp" - namespace Mantid { namespace API @@ -66,8 +64,8 @@ namespace IDA QtTreePropertyBrowser* m_ffTree; ///< FuryFit Property Browser QtDoublePropertyManager* m_ffRangeManager; ///< StartX and EndX for FuryFit QMap m_fixedProps; - boost::shared_ptr m_ffInputWS; - boost::shared_ptr m_ffOutputWS; + Mantid::API::MatrixWorkspace_sptr m_ffInputWS; + Mantid::API::MatrixWorkspace_sptr m_ffOutputWS; QString m_ffInputWSName; QString m_ties; diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/FuryFit.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/FuryFit.ui index adb91b783e34..8bda7e0a38e5 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/FuryFit.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/FuryFit.ui @@ -136,10 +136,21 @@ - + + + true + + + + 255 + 255 + 255 + + + - + @@ -160,23 +171,6 @@ - - - - Sample - - - - - - - color: rgb(255, 0, 0); - - - Fit - - - @@ -324,6 +318,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp index b27970e19e28..d2b9bf392818 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp @@ -50,20 +50,13 @@ namespace IDA m_cfTree->setFactoryForManager(m_blnManager, m_blnEdFac); m_cfTree->setFactoryForManager(m_dblManager, m_dblEdFac); - // Create Plot Widget - m_plots["ConvFitPlot"] = new QwtPlot(m_parentWidget); - m_plots["ConvFitPlot"]->setAxisFont(QwtPlot::xBottom, m_parentWidget->font()); - m_plots["ConvFitPlot"]->setAxisFont(QwtPlot::yLeft, m_parentWidget->font()); - m_plots["ConvFitPlot"]->setCanvasBackground(Qt::white); - m_uiForm.plot->addWidget(m_plots["ConvFitPlot"]); - // Create Range Selectors - m_rangeSelectors["ConvFitRange"] = new MantidQt::MantidWidgets::RangeSelector(m_plots["ConvFitPlot"]); - m_rangeSelectors["ConvFitBackRange"] = new MantidQt::MantidWidgets::RangeSelector(m_plots["ConvFitPlot"], + m_rangeSelectors["ConvFitRange"] = new MantidQt::MantidWidgets::RangeSelector(m_uiForm.ppPlot); + m_rangeSelectors["ConvFitBackRange"] = new MantidQt::MantidWidgets::RangeSelector(m_uiForm.ppPlot, MantidQt::MantidWidgets::RangeSelector::YSINGLE); m_rangeSelectors["ConvFitBackRange"]->setColour(Qt::darkGreen); m_rangeSelectors["ConvFitBackRange"]->setRange(0.0, 1.0); - m_rangeSelectors["ConvFitHWHM"] = new MantidQt::MantidWidgets::RangeSelector(m_plots["ConvFitPlot"]); + m_rangeSelectors["ConvFitHWHM"] = new MantidQt::MantidWidgets::RangeSelector(m_uiForm.ppPlot); m_rangeSelectors["ConvFitHWHM"]->setColour(Qt::red); // Populate Property Widget @@ -248,7 +241,7 @@ namespace IDA void ConvFit::newDataLoaded(const QString wsName) { m_cfInputWSName = wsName; - m_cfInputWS = AnalysisDataService::Instance().retrieveWS(m_cfInputWSName.toStdString()); + m_cfInputWS = AnalysisDataService::Instance().retrieveWS(m_cfInputWSName.toStdString()); int maxSpecIndex = static_cast(m_cfInputWS->getNumberHistograms()) - 1; @@ -688,10 +681,13 @@ namespace IDA int specNo = m_uiForm.spPlotSpectrum->text().toInt(); - plotMiniPlot(m_cfInputWS, specNo, "ConvFitPlot", "CFDataCurve"); + m_uiForm.ppPlot->clear(); + m_uiForm.ppPlot->addSpectrum("Sample", m_cfInputWS, specNo); + try { - const std::pair range = getCurveRange("CFDataCurve"); + const QPair curveRange = m_uiForm.ppPlot->getCurveRange("Sample"); + const std::pair range(curveRange.first, curveRange.second); m_rangeSelectors["ConvFitRange"]->setRange(range.first, range.second); m_uiForm.ckPlotGuess->setChecked(plotGuess); } @@ -707,18 +703,13 @@ namespace IDA m_dblManager->setValue(m_properties["Lorentzian 1.FWHM"], resolution); m_dblManager->setValue(m_properties["Lorentzian 2.FWHM"], resolution); } - - // Remove the old fit curve - removeCurve("CFCalcCurve"); - replot("ConvFitPlot"); } void ConvFit::plotGuess(QtProperty*) { - if ( ! m_uiForm.ckPlotGuess->isChecked() || m_curves["CFDataCurve"] == NULL ) - { + // Do nothing if there is no sample data curve + if(!m_uiForm.ppPlot->hasCurve("Sample")) return; - } bool tieCentres = (m_uiForm.cbFitType->currentIndex() > 1); CompositeFunction_sptr function = createFunction(tieCentres); @@ -771,10 +762,8 @@ namespace IDA createWsAlg->execute(); MatrixWorkspace_sptr guessWs = createWsAlg->getProperty("OutputWorkspace"); - plotMiniPlot(guessWs, 0, "ConvFitPlot", "guess"); - QPen p(Qt::green, Qt::SolidLine); - m_curves["guess"]->setPen(p); - replot("ConvFitPlot"); + m_uiForm.ppPlot->removeSpectrum("Fit"); + m_uiForm.ppPlot->addSpectrum("Guess", guessWs, 0, Qt::green); } void ConvFit::singleFit() @@ -784,12 +773,6 @@ namespace IDA plotInput(); - if ( m_curves["CFDataCurve"] == NULL ) - { - showMessageBox("There was an error reading the data file."); - return; - } - m_uiForm.ckPlotGuess->setChecked(false); CompositeFunction_sptr function = createFunction(m_uiForm.ckTieCentres->isChecked()); @@ -827,10 +810,8 @@ namespace IDA } // Plot the line on the mini plot - plotMiniPlot(outputNm+"_Workspace", 1, "ConvFitPlot", "CFCalcCurve"); - QPen fitPen(Qt::red, Qt::SolidLine); - m_curves["CFCalcCurve"]->setPen(fitPen); - replot("ConvFitPlot"); + m_uiForm.ppPlot->removeSpectrum("Guess"); + m_uiForm.ppPlot->addSpectrum("Fit", outputNm+"_Workspace", 1, Qt::red); IFunction_sptr outputFunc = alg->getProperty("Function"); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/FuryFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/FuryFit.cpp index e445f9c08a15..9b01afb73004 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/FuryFit.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/FuryFit.cpp @@ -47,18 +47,11 @@ namespace IDA m_ffTree = new QtTreePropertyBrowser(m_parentWidget); m_uiForm.properties->addWidget(m_ffTree); - // Setup FuryFit Plot Window - m_plots["FuryFitPlot"] = new QwtPlot(m_parentWidget); - m_plots["FuryFitPlot"]->setAxisFont(QwtPlot::xBottom, m_parentWidget->font()); - m_plots["FuryFitPlot"]->setAxisFont(QwtPlot::yLeft, m_parentWidget->font()); - m_uiForm.vlPlot->addWidget(m_plots["FuryFitPlot"]); - m_plots["FuryFitPlot"]->setCanvasBackground(QColor(255,255,255)); - - m_rangeSelectors["FuryFitRange"] = new MantidQt::MantidWidgets::RangeSelector(m_plots["FuryFitPlot"]); + m_rangeSelectors["FuryFitRange"] = new MantidQt::MantidWidgets::RangeSelector(m_uiForm.ppPlot); connect(m_rangeSelectors["FuryFitRange"], SIGNAL(minValueChanged(double)), this, SLOT(xMinSelected(double))); connect(m_rangeSelectors["FuryFitRange"], SIGNAL(maxValueChanged(double)), this, SLOT(xMaxSelected(double))); - m_rangeSelectors["FuryFitBackground"] = new MantidQt::MantidWidgets::RangeSelector(m_plots["FuryFitPlot"], + m_rangeSelectors["FuryFitBackground"] = new MantidQt::MantidWidgets::RangeSelector(m_uiForm.ppPlot, MantidQt::MantidWidgets::RangeSelector::YSINGLE); m_rangeSelectors["FuryFitBackground"]->setRange(0.0,1.0); m_rangeSelectors["FuryFitBackground"]->setColour(Qt::darkGreen); @@ -102,7 +95,7 @@ namespace IDA typeSelection(m_uiForm.cbFitType->currentIndex()); - // Connect to PlotGuess checkbox + // Update guess curve on property change connect(m_dblManager, SIGNAL(propertyChanged(QtProperty*)), this, SLOT(plotGuess(QtProperty*))); // Signal/slot ui connections @@ -210,7 +203,7 @@ namespace IDA void FuryFit::newDataLoaded(const QString wsName) { m_ffInputWSName = wsName; - m_ffInputWS = AnalysisDataService::Instance().retrieveWS(m_ffInputWSName.toStdString()); + m_ffInputWS = AnalysisDataService::Instance().retrieveWS(m_ffInputWSName.toStdString()); int maxSpecIndex = static_cast(m_ffInputWS->getNumberHistograms()) - 1; @@ -396,11 +389,14 @@ namespace IDA } int specNo = m_uiForm.spPlotSpectrum->value(); - plotMiniPlot(m_ffInputWS, specNo, "FuryFitPlot", "FF_DataCurve"); + + m_uiForm.ppPlot->clear(); + m_uiForm.ppPlot->addSpectrum("Sample", m_ffInputWS, specNo); try { - const std::pair range = getCurveRange("FF_DataCurve"); + const QPair curveRange = m_uiForm.ppPlot->getCurveRange("Sample"); + const std::pair range(curveRange.first, curveRange.second); m_rangeSelectors["FuryFitRange"]->setRange(range.first, range.second); m_ffRangeManager->setRange(m_properties["StartX"], range.first, range.second); m_ffRangeManager->setRange(m_properties["EndX"], range.first, range.second); @@ -409,9 +405,8 @@ namespace IDA setDefaultParameters("Exponential2"); setDefaultParameters("StretchedExp"); - m_plots["FuryFitPlot"]->setAxisScale(QwtPlot::xBottom, range.first, range.second); - m_plots["FuryFitPlot"]->setAxisScale(QwtPlot::yLeft, 0.0, 1.0); - replot("FuryFitPlot"); + m_uiForm.ppPlot->resizeX(); + m_uiForm.ppPlot->setAxisRange(qMakePair(0.0, 1.0), QwtPlot::yLeft); } catch(std::invalid_argument & exc) { @@ -548,6 +543,9 @@ namespace IDA if(!validate()) return; + // Don't plot a new guess curve until there is a fit + disconnect(m_dblManager, SIGNAL(propertyChanged(QtProperty*)), this, SLOT(plotGuess(QtProperty*))); + // First create the function auto function = createFunction(); @@ -602,12 +600,6 @@ namespace IDA return; } - // Now show the fitted curve of the mini plot - plotMiniPlot(outputNm+"_Workspace", 1, "FuryFitPlot", "FF_FitCurve"); - QPen fitPen(Qt::red, Qt::SolidLine); - m_curves["FF_FitCurve"]->setPen(fitPen); - replot("FuryFitPlot"); - IFunction_sptr outputFunc = alg->getProperty("Function"); // Get params. @@ -648,14 +640,21 @@ namespace IDA m_dblManager->setValue(m_properties["StretchedExp.Tau"], parameters[fval+"Tau"]); m_dblManager->setValue(m_properties["StretchedExp.Beta"], parameters[fval+"Beta"]); } + + // Can start upddating the guess curve again + connect(m_dblManager, SIGNAL(propertyChanged(QtProperty*)), this, SLOT(plotGuess(QtProperty*))); + + // Plot the guess first so that it is under the fit + plotGuess(NULL); + // Now show the fitted curve of the mini plot + m_uiForm.ppPlot->addSpectrum("Fit", outputNm+"_Workspace", 1, Qt::red); } void FuryFit::plotGuess(QtProperty*) { - if ( m_curves["FF_DataCurve"] == NULL ) - { + // Do nothing if there is no sample data curve + if(!m_uiForm.ppPlot->hasCurve("Sample")) return; - } CompositeFunction_sptr function = createFunction(true); @@ -701,10 +700,7 @@ namespace IDA createWsAlg->execute(); MatrixWorkspace_sptr guessWs = createWsAlg->getProperty("OutputWorkspace"); - plotMiniPlot(guessWs, 0, "FuryFitPlot", "guess"); - QPen p(Qt::green, Qt::SolidLine); - m_curves["guess"]->setPen(p); - replot("FuryFitPlot"); + m_uiForm.ppPlot->addSpectrum("Guess", guessWs, 0, Qt::green); } void FuryFit::fitContextMenu(const QPoint &) diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h index b54ccc0acbc3..13250323b045 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -79,6 +79,8 @@ namespace MantidWidgets void removeSpectrum(const Mantid::API::MatrixWorkspace_sptr ws); void removeSpectrum(const QString & curveName); + bool hasCurve(const QString & curveName); + signals: /// Signals that the plot should be refreshed void needToReplot(); diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index c0b6cf6fd44e..9ba4a8055946 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -313,6 +313,18 @@ void PreviewPlot::removeSpectrum(const QString & curveName) } +/** + * Checks to see if a given curne name is present on the plot. + * + * @param curveName Curve name + * @return True if curve is on plot + */ +bool PreviewPlot::hasCurve(const QString & curveName) +{ + return m_curves.contains(curveName); +} + + /** * Shows or hides the plot legend. * From c1bc081d8715e77120ae39eaa1f178f814b70f3f Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Fri, 13 Feb 2015 12:08:39 +0000 Subject: [PATCH 087/414] Add cmake option to only create data targets This is useful for the standalone system tests that won't necessarily have all of the Mantid build dependencies installed. Refs #10870 --- Code/Mantid/Build/CMake/CommonSetup.cmake | 31 +----------------- .../Mantid/Build/CMake/SetupDataTargets.cmake | 32 +++++++++++++++++++ Code/Mantid/Build/Jenkins/systemtests | 4 +-- Code/Mantid/CMakeLists.txt | 13 +++++++- 4 files changed, 47 insertions(+), 33 deletions(-) create mode 100644 Code/Mantid/Build/CMake/SetupDataTargets.cmake diff --git a/Code/Mantid/Build/CMake/CommonSetup.cmake b/Code/Mantid/Build/CMake/CommonSetup.cmake index 67414eae8559..10625001e3b6 100644 --- a/Code/Mantid/Build/CMake/CommonSetup.cmake +++ b/Code/Mantid/Build/CMake/CommonSetup.cmake @@ -305,36 +305,7 @@ endif() # External Data for testing ########################################################################### if ( CXXTEST_FOUND OR PYUNITTEST_FOUND ) - include ( MantidExternalData ) - - # None of our tests reference files directly as arguments so we have to manually - # call ExternalData_Expand_Arguments to register the files with the ExternalData - # mechanism - function(_create_data_target _targetname _content_link_patterns) - get_filename_component ( EXTERNALDATATEST_SOURCE_DIR ${PROJECT_SOURCE_DIR} ABSOLUTE ) - foreach(_pattern ${_content_link_patterns}) - file( GLOB_RECURSE _content_links - RELATIVE "${EXTERNALDATATEST_SOURCE_DIR}" ${_pattern} ) - foreach(link ${_content_links}) - string( REGEX REPLACE "\\.md5$" "" link ${link} ) - ExternalData_Expand_Arguments( ${_targetname} - link_location - DATA{${link}} - ) - endforeach() - endforeach() - # Create target to download data from the StandardTestData group. This must come after - # all tests have been added that reference the group, so we put it last. - ExternalData_Add_Target(${_targetname}) - set_target_properties(${_targetname} PROPERTIES EXCLUDE_FROM_ALL TRUE) - endfunction() - - # We'll create two targets: - # - StandardTestData: data required by the unit tests and documentation tests - # - SystemTestData: data required for the system tests - _create_data_target(StandardTestData "Testing/Data/DocTest/*.md5;Testing/Data/UnitTest/*.md5") - _create_data_target(SystemTestData "Testing/Data/SystemTest/*.md5;Testing/SystemTests/tests/analysis/reference/*.md5") - + include( SetupDataTargets ) endif() ########################################################################### diff --git a/Code/Mantid/Build/CMake/SetupDataTargets.cmake b/Code/Mantid/Build/CMake/SetupDataTargets.cmake new file mode 100644 index 000000000000..8f8a87e1e291 --- /dev/null +++ b/Code/Mantid/Build/CMake/SetupDataTargets.cmake @@ -0,0 +1,32 @@ +########################################################################### +# Define targets to download the data +########################################################################### +include ( MantidExternalData ) + +# None of our tests reference files directly as arguments so we have to manually +# call ExternalData_Expand_Arguments to register the files with the ExternalData +# mechanism +function(_create_data_target _targetname _content_link_patterns) + get_filename_component ( EXTERNALDATATEST_SOURCE_DIR ${PROJECT_SOURCE_DIR} ABSOLUTE ) + foreach(_pattern ${_content_link_patterns}) + file( GLOB_RECURSE _content_links + RELATIVE "${EXTERNALDATATEST_SOURCE_DIR}" ${_pattern} ) + foreach(link ${_content_links}) + string( REGEX REPLACE "\\.md5$" "" link ${link} ) + ExternalData_Expand_Arguments( ${_targetname} + link_location + DATA{${link}} + ) + endforeach() + endforeach() + # Create target to download data from the StandardTestData group. This must come after + # all tests have been added that reference the group, so we put it last. + ExternalData_Add_Target(${_targetname}) + set_target_properties(${_targetname} PROPERTIES EXCLUDE_FROM_ALL TRUE) +endfunction() + +# We'll create two targets: +# - StandardTestData: data required by the unit tests and documentation tests +# - SystemTestData: data required for the system tests +_create_data_target(StandardTestData "Testing/Data/DocTest/*.md5;Testing/Data/UnitTest/*.md5") +_create_data_target(SystemTestData "Testing/Data/SystemTest/*.md5;Testing/SystemTests/tests/analysis/reference/*.md5") diff --git a/Code/Mantid/Build/Jenkins/systemtests b/Code/Mantid/Build/Jenkins/systemtests index 5a792bdf1e41..5ced2d5bd7dc 100755 --- a/Code/Mantid/Build/Jenkins/systemtests +++ b/Code/Mantid/Build/Jenkins/systemtests @@ -41,11 +41,11 @@ fi cd $WORKSPACE/build ############################################################################### -# CMake configuration if it has not already been configured +# CMake configuration if it has not already been configured. # We use the special flag that only creates the targets for the data ############################################################################### if [[ ! -e $WORKSPACE/build/CMakeCache.txt ]]; then - $SCL_ON_RHEL6 "cmake -DMANTID_DATA_STORE=${MANTID_DATA_STORE} -DTESTING_DATA_ONLY=ON ../Code/Mantid" + $SCL_ON_RHEL6 "cmake -DMANTID_DATA_STORE=${MANTID_DATA_STORE} -DDATA_TARGETS_ONLY=ON ../Code/Mantid" fi ############################################################################### diff --git a/Code/Mantid/CMakeLists.txt b/Code/Mantid/CMakeLists.txt index 673bd4b295ca..d91951ed788a 100644 --- a/Code/Mantid/CMakeLists.txt +++ b/Code/Mantid/CMakeLists.txt @@ -12,6 +12,17 @@ set ( CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/Build/CMake") # Define the project name. project ( Mantid ) + +########################################################################### +# Quick exit if we only want data targets +########################################################################### +if( DATA_TARGETS_ONLY ) + include( SetupDataTargets ) + # System test config files + add_subdirectory( Testing/SystemTests/scripts ) + return() +endif() + set ( CPACK_PACKAGE_SUFFIX "" CACHE STRING "suffix used to determine the deployment type") set_property(CACHE CPACK_PACKAGE_SUFFIX PROPERTY STRINGS nightly unstable "") #empty string and release are treated as the same thing @@ -147,7 +158,7 @@ add_subdirectory ( scripts ) add_subdirectory ( docs ) -# System tests +# System test data target add_subdirectory ( Testing/SystemTests/scripts ) ########################################################################### From 8a1b874cba45e802e82c9ac727dbe9a1f9fa3b87 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Fri, 13 Feb 2015 12:23:42 +0000 Subject: [PATCH 088/414] Correct issues with guess on conv fit Refs #11036 --- .../MantidQtCustomInterfaces/Indirect/ConvFit.h | 2 +- .../CustomInterfaces/src/Indirect/ConvFit.cpp | 16 +++++++++++----- .../MantidQt/MantidWidgets/src/PreviewPlot.cpp | 6 ++++-- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h index f31f2d7f4ca7..2c4c4959d4bc 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h @@ -30,7 +30,7 @@ namespace IDA void bgTypeSelection(int index); void newDataLoaded(const QString wsName); void plotInput(); - void plotGuess(QtProperty*); + void plotGuess(); void singleFit(); void specMinChanged(int value); void specMaxChanged(int value); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp index d2b9bf392818..ebf92f8aec32 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp @@ -105,9 +105,13 @@ namespace IDA connect(m_rangeSelectors["ConvFitHWHM"], SIGNAL(maxValueChanged(double)), this, SLOT(hwhmChanged(double))); connect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(updateRS(QtProperty*, double))); connect(m_blnManager, SIGNAL(valueChanged(QtProperty*, bool)), this, SLOT(checkBoxUpdate(QtProperty*, bool))); - connect(m_dblManager, SIGNAL(propertyChanged(QtProperty*)), this, SLOT(plotGuess(QtProperty*))); connect(m_uiForm.ckTempCorrection, SIGNAL(toggled(bool)), m_uiForm.leTempCorrection, SLOT(setEnabled(bool))); + // Update guess curve when certain things happen + connect(m_dblManager, SIGNAL(propertyChanged(QtProperty*)), this, SLOT(plotGuess())); + connect(m_uiForm.cbFitType, SIGNAL(currentIndexChanged(int)), this, SLOT(plotGuess())); + connect(m_uiForm.ckPlotGuess, SIGNAL(stateChanged(int)), this, SLOT(plotGuess())); + // Have FWHM Range linked to Fit Start/End Range connect(m_rangeSelectors["ConvFitRange"], SIGNAL(rangeChanged(double, double)), m_rangeSelectors["ConvFitHWHM"], SLOT(setRange(double, double))); m_rangeSelectors["ConvFitHWHM"]->setRange(-1.0,1.0); @@ -705,10 +709,13 @@ namespace IDA } } - void ConvFit::plotGuess(QtProperty*) + void ConvFit::plotGuess() { - // Do nothing if there is no sample data curve - if(!m_uiForm.ppPlot->hasCurve("Sample")) + m_uiForm.ppPlot->removeSpectrum("Guess"); + + // Do nothing if there is not a sample and resolution + if(!(m_uiForm.dsSampleInput->isValid() && m_uiForm.dsResInput->isValid() + && m_uiForm.ckPlotGuess->isChecked())) return; bool tieCentres = (m_uiForm.cbFitType->currentIndex() > 1); @@ -762,7 +769,6 @@ namespace IDA createWsAlg->execute(); MatrixWorkspace_sptr guessWs = createWsAlg->getProperty("OutputWorkspace"); - m_uiForm.ppPlot->removeSpectrum("Fit"); m_uiForm.ppPlot->addSpectrum("Guess", guessWs, 0, Qt::green); } diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index 9ba4a8055946..376582042ef4 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -171,7 +171,7 @@ void PreviewPlot::setAxisRange(QPair range, int axisID) throw std::runtime_error("Supplied range is invalid."); m_uiForm.plot->setAxisScale(axisID, range.first, range.second); - replot(); + emit needToReplot(); } @@ -310,6 +310,8 @@ void PreviewPlot::removeSpectrum(const QString & curveName) // Remove the curve from the map if(it != m_curves.end()) m_curves.erase(it); + + emit needToReplot(); } @@ -449,7 +451,7 @@ void PreviewPlot::hardReplot() m_curves[*it].curve = addCurve(m_curves[*it].ws, m_curves[*it].wsIndex, m_curves[*it].colour); } - replot(); + emit needToReplot(); } From 1752fc2fe186490921b7ead2a32be003dedcd4db Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Fri, 13 Feb 2015 15:00:32 +0000 Subject: [PATCH 089/414] Add first test to try things out. Refs #10870 --- .../Testing/Data/SystemTest/HRP39187.RAW.md5 | 1 + .../Testing/Data/SystemTest/HRP39191.RAW.md5 | 1 + .../SystemTest/hrpd_new_072_01_corr.cal.md5 | 1 + .../tests/analysis/HRPDPowderDiffraction.py | 75 +++++++++++++++++++ .../reference/HRPDPowderDiffraction.nxs.md5 | 1 + 5 files changed, 79 insertions(+) create mode 100644 Code/Mantid/Testing/Data/SystemTest/HRP39187.RAW.md5 create mode 100644 Code/Mantid/Testing/Data/SystemTest/HRP39191.RAW.md5 create mode 100644 Code/Mantid/Testing/Data/SystemTest/hrpd_new_072_01_corr.cal.md5 create mode 100644 Code/Mantid/Testing/SystemTests/tests/analysis/HRPDPowderDiffraction.py create mode 100644 Code/Mantid/Testing/SystemTests/tests/analysis/reference/HRPDPowderDiffraction.nxs.md5 diff --git a/Code/Mantid/Testing/Data/SystemTest/HRP39187.RAW.md5 b/Code/Mantid/Testing/Data/SystemTest/HRP39187.RAW.md5 new file mode 100644 index 000000000000..6736dcddd7b0 --- /dev/null +++ b/Code/Mantid/Testing/Data/SystemTest/HRP39187.RAW.md5 @@ -0,0 +1 @@ +6aa506e83ba085964781b480d71c59fe diff --git a/Code/Mantid/Testing/Data/SystemTest/HRP39191.RAW.md5 b/Code/Mantid/Testing/Data/SystemTest/HRP39191.RAW.md5 new file mode 100644 index 000000000000..d9d1923775b2 --- /dev/null +++ b/Code/Mantid/Testing/Data/SystemTest/HRP39191.RAW.md5 @@ -0,0 +1 @@ +e422e2456884b0bd4c686e5d883f9d57 diff --git a/Code/Mantid/Testing/Data/SystemTest/hrpd_new_072_01_corr.cal.md5 b/Code/Mantid/Testing/Data/SystemTest/hrpd_new_072_01_corr.cal.md5 new file mode 100644 index 000000000000..37c71d5dbfe1 --- /dev/null +++ b/Code/Mantid/Testing/Data/SystemTest/hrpd_new_072_01_corr.cal.md5 @@ -0,0 +1 @@ +21f937d9b1bfc5032d3fbf8f85920c15 diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/HRPDPowderDiffraction.py b/Code/Mantid/Testing/SystemTests/tests/analysis/HRPDPowderDiffraction.py new file mode 100644 index 000000000000..7ed7c9ccaa7d --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/tests/analysis/HRPDPowderDiffraction.py @@ -0,0 +1,75 @@ +import stresstesting +from mantid.simpleapi import * + +''' Simply tests that our LoadRaw and LoadISISNexus algorithms produce the same workspace''' +class HRPDPowderDiffraction(stresstesting.MantidStressTest): + + def requiredFiles(self): + return ["HRP39191.RAW", "hrpd_new_072_01_corr.cal", "HRP39187.RAW", 'HRPDPowderDiffraction.nxs'] + + def runTest(self): + #Load the Vanadium + LoadRaw(Filename="HRP39191.RAW",OutputWorkspace="Vanadium") + #mask out the vanadium peaks + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="19970",XMax="20140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="39970",XMax="40140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="59970",XMax="60140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="79970",XMax="80140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="99970",XMax="100140") + #align vanadium detectors + AlignDetectors(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",CalibrationFile="hrpd_new_072_01_corr.cal") + #normalise by current + NormaliseByCurrent(InputWorkspace="Vanadium",OutputWorkspace="Vanadium") + #correct for solid angle + SolidAngle(InputWorkspace="Vanadium",OutputWorkspace="Corr") + Divide(LHSWorkspace="Vanadium",RHSWorkspace="Corr",OutputWorkspace="Vanadium") + #Multiply the solid angle by the integrated vanadium flux between 1.4 and 3 Angstrom + ConvertUnits(InputWorkspace="Vanadium",OutputWorkspace="flux",Target="Wavelength") + Integration(InputWorkspace="flux",OutputWorkspace="flux",RangeLower="1.4",RangeUpper="3") + Multiply(LHSWorkspace="Corr",RHSWorkspace="flux",OutputWorkspace="Corr") + #adjust the correction down by a factor of 1000 + CreateSingleValuedWorkspace(OutputWorkspace="Sc",DataValue="1000") + Divide(LHSWorkspace="Corr",RHSWorkspace="Sc",OutputWorkspace="Corr") + #Load the Vanadium - a second time + LoadRaw(Filename="HRP39191.RAW",OutputWorkspace="Vanadium") + #mask out the vanadium peaks + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="19970",XMax="20140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="39970",XMax="40140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="59970",XMax="60140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="79970",XMax="80140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="99970",XMax="100140") + #align vanadium detectors + AlignDetectors(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",CalibrationFile="hrpd_new_072_01_corr.cal") + #normalise by current + NormaliseByCurrent(InputWorkspace="Vanadium",OutputWorkspace="Vanadium") + #correct by accumulated correction - solid angle/(1000*flux(1.4 - 3 Angstrom)) + Divide(LHSWorkspace="Vanadium",RHSWorkspace="Corr",OutputWorkspace="Vanadium") + #Load the vanadium empty + LoadRaw(Filename="HRP39187.RAW",OutputWorkspace="VEmpty") + #mask out the vanadium peaks + MaskBins(InputWorkspace="VEmpty",OutputWorkspace="VEmpty",XMin="19970",XMax="20140") + MaskBins(InputWorkspace="VEmpty",OutputWorkspace="VEmpty",XMin="39970",XMax="40140") + MaskBins(InputWorkspace="VEmpty",OutputWorkspace="VEmpty",XMin="59970",XMax="60140") + MaskBins(InputWorkspace="VEmpty",OutputWorkspace="VEmpty",XMin="79970",XMax="80140") + MaskBins(InputWorkspace="VEmpty",OutputWorkspace="VEmpty",XMin="99970",XMax="100140") + #align vanadium empty detectors + AlignDetectors(InputWorkspace="VEmpty",OutputWorkspace="VEmpty",CalibrationFile="hrpd_new_072_01_corr.cal") + #correct by accumulated correction - solid angle/(1000*flux(1.4 - 3 Angstrom)) + Divide(LHSWorkspace="VEmpty",RHSWorkspace="Corr",OutputWorkspace="VEmpty") + #normalise by current + NormaliseByCurrent(InputWorkspace="VEmpty",OutputWorkspace="VEmpty") + #Subtract Vanadium empty from the Vanadium + Minus(LHSWorkspace="Vanadium",RHSWorkspace="VEmpty",OutputWorkspace="Vanadium") + #Convert to wavelength + ConvertUnits(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",Target="Wavelength") + #Correct for cylinderAbsorption + CylinderAbsorption(InputWorkspace="Vanadium",OutputWorkspace="Transmission",CylinderSampleHeight="2",CylinderSampleRadius="0.4",AttenuationXSection="5.1",ScatteringXSection="5.08",SampleNumberDensity="0.072",NumberOfSlices="10",NumberOfAnnuli="10",NumberOfWavelengthPoints="100") + Divide(LHSWorkspace="Vanadium",RHSWorkspace="Transmission",OutputWorkspace="Vanadium") + #convert to dspacing and focuss + ConvertUnits(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",Target="dSpacing") + DiffractionFocussing(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",GroupingFileName="hrpd_new_072_01_corr.cal") + + def validate(self): + # Fitting parameters not saved to ParameterMap + self.disableChecking.append("Instrument") + return 'Vanadium','HRPDPowderDiffraction.nxs' diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/HRPDPowderDiffraction.nxs.md5 b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/HRPDPowderDiffraction.nxs.md5 new file mode 100644 index 000000000000..0cc9b76c87b6 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/HRPDPowderDiffraction.nxs.md5 @@ -0,0 +1 @@ +078a0d8d4c9f0aa5b2ece6099e13b0b9 From 5b18086a008ab603d09ed488df68fe36770ecf52 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Fri, 13 Feb 2015 15:07:13 +0000 Subject: [PATCH 090/414] Remove unused code from IndirectTab Also prefer QPair over std::pair in UI stuff Refs #11036 --- .../Indirect/IndirectBayesTab.h | 4 +- .../Indirect/IndirectTab.h | 27 +--- .../src/Indirect/IndirectBayesTab.cpp | 6 +- .../src/Indirect/IndirectCalibration.cpp | 30 ++-- .../src/Indirect/IndirectDiagnostics.cpp | 14 +- .../src/Indirect/IndirectMoments.cpp | 7 +- .../src/Indirect/IndirectTab.cpp | 153 +----------------- .../src/Indirect/IndirectTransmission.cpp | 7 - .../CustomInterfaces/src/Indirect/JumpFit.cpp | 11 +- .../CustomInterfaces/src/Indirect/Quasi.cpp | 8 +- .../CustomInterfaces/src/Indirect/ResNorm.cpp | 11 +- .../CustomInterfaces/src/Indirect/Stretch.cpp | 23 ++- 12 files changed, 64 insertions(+), 237 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectBayesTab.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectBayesTab.h index 3d76e4d8bdf9..cbb391a48c3b 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectBayesTab.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectBayesTab.h @@ -96,9 +96,9 @@ namespace MantidQt /// Function to run a string as python code void runPythonScript(const QString& pyInput); /// Function to read an instrument's resolution from the IPF using a string - bool getInstrumentResolution(const QString& filename, std::pair& res); + bool getInstrumentResolution(const QString& filename, QPair & res); /// Function to read an instrument's resolution from the IPF using a workspace pointer - bool getInstrumentResolution(Mantid::API::MatrixWorkspace_const_sptr ws, std::pair& res); + bool getInstrumentResolution(Mantid::API::MatrixWorkspace_const_sptr ws, QPair & res); /// Function to set the position of the lower guide on the plot void updateLowerGuide(MantidQt::MantidWidgets::RangeSelector* rs, QtProperty* lower, QtProperty* upper, double value); /// Function to set the position of the upper guide on the plot diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTab.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTab.h index 06ead2abdfc6..1c6750a08434 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTab.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTab.h @@ -13,6 +13,7 @@ #include #include +#include #include #include @@ -88,28 +89,10 @@ namespace CustomInterfaces /// Run the load algorithm with the given file name, output name and spectrum range bool loadFile(const QString& filename, const QString& outputName, const int specMin = -1, const int specMax = -1); - /// Function to plot a workspace to the miniplot using a workspace name - void plotMiniPlot(const QString& workspace, size_t index, const QString& plotID, const QString& curveID = ""); - /// Function to plot a workspace to the miniplot using a workspace pointer - void plotMiniPlot(const Mantid::API::MatrixWorkspace_const_sptr & workspace, size_t wsIndex, const QString& plotID, const QString& curveID = ""); - /// Function to replot a miniplot - void replot(const QString& plotID); - /// Function to remove a curve from a plot - void removeCurve(const QString& curveID); - /// Function to remove all curves from plots - void removeAllCurves(); - - /// Function to get the range of the curve displayed on the mini plot - std::pair getCurveRange(const QString& plotID); - /// Function to set the range of an axis on a plot - void setAxisRange(const QString& plotID, QwtPlot::Axis axis, std::pair range); - /// Function to autoscale a given axis based on the data in a curve - void setXAxisToCurve(const QString& plotID, const QString& curveID); - /// Function to set the range limits of the plot - void setPlotRange(const QString& rsID, QtProperty* min, QtProperty* max, const std::pair& bounds); + void setPlotPropertyRange(const QString& rsID, QtProperty* min, QtProperty* max, const QPair & bounds); /// Function to set the range selector on the mini plot - void setMiniPlotGuides(const QString& rsID, QtProperty* lower, QtProperty* upper, const std::pair& bounds); + void setRangeSelector(const QString& rsID, QtProperty* lower, QtProperty* upper, const QPair & bounds); /// Function to run an algorithm on a seperate thread void runAlgorithm(const Mantid::API::IAlgorithm_sptr algorithm); @@ -119,10 +102,6 @@ namespace CustomInterfaces /// Parent QWidget (if applicable) QWidget *m_parentWidget; - /// Plot of the input - std::map m_plots; - /// Curve on the plot - std::map m_curves; /// Range selector widget for mini plot std::map m_rangeSelectors; /// Tree of the properties diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectBayesTab.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectBayesTab.cpp index 6da36475967e..2b9891b2d865 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectBayesTab.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectBayesTab.cpp @@ -48,7 +48,7 @@ namespace MantidQt * @param workspace :: Name of the workspace to use * @param res :: The retrieved values for the resolution parameter (if one was found) */ - bool IndirectBayesTab::getInstrumentResolution(const QString& workspace, std::pair& res) + bool IndirectBayesTab::getInstrumentResolution(const QString& workspace, QPair & res) { auto ws = Mantid::API::AnalysisDataService::Instance().retrieveWS(workspace.toStdString()); return getInstrumentResolution(ws, res); @@ -61,7 +61,7 @@ namespace MantidQt * @param ws :: Pointer to the workspace to use * @param res :: The retrieved values for the resolution parameter (if one was found) */ - bool IndirectBayesTab::getInstrumentResolution(Mantid::API::MatrixWorkspace_const_sptr ws, std::pair& res) + bool IndirectBayesTab::getInstrumentResolution(Mantid::API::MatrixWorkspace_const_sptr ws, QPair & res) { auto inst = ws->getInstrument(); auto analyser = inst->getStringParameter("analyser"); @@ -74,7 +74,7 @@ namespace MantidQt //set the default instrument resolution if(params.size() > 0) { - res = std::make_pair(-params[0], params[0]); + res = qMakePair(-params[0], params[0]); return true; } } diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp index b29397350678..826fa3735ea2 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp @@ -315,11 +315,11 @@ namespace CustomInterfaces // Set peak and background ranges std::map ranges = getRangesFromInstrument(); - std::pair peakRange(ranges["peak-start-tof"], ranges["peak-end-tof"]); - std::pair backgroundRange(ranges["back-start-tof"], ranges["back-end-tof"]); + QPair peakRange(ranges["peak-start-tof"], ranges["peak-end-tof"]); + QPair backgroundRange(ranges["back-start-tof"], ranges["back-end-tof"]); - setMiniPlotGuides("CalPeak", m_properties["CalPeakMin"], m_properties["CalPeakMax"], peakRange); - setMiniPlotGuides("CalBackground", m_properties["CalBackMin"], m_properties["CalBackMax"], backgroundRange); + setRangeSelector("CalPeak", m_properties["CalPeakMin"], m_properties["CalPeakMax"], peakRange); + setRangeSelector("CalBackground", m_properties["CalBackMin"], m_properties["CalBackMax"], backgroundRange); } /** @@ -360,14 +360,14 @@ namespace CustomInterfaces Mantid::API::AnalysisDataService::Instance().retrieve(wsname.toStdString())); const Mantid::MantidVec & dataX = input->readX(0); - std::pair range(dataX.front(), dataX.back()); + QPair range(dataX.front(), dataX.back()); m_uiForm.ppCalibration->clear(); m_uiForm.ppCalibration->addSpectrum("Raw", input, 0); m_uiForm.ppCalibration->resizeX(); - setPlotRange("CalPeak", m_properties["CalELow"], m_properties["CalEHigh"], range); - setPlotRange("CalBackground", m_properties["CalStart"], m_properties["CalEnd"], range); + setPlotPropertyRange("CalPeak", m_properties["CalELow"], m_properties["CalEHigh"], range); + setPlotPropertyRange("CalBackground", m_properties["CalStart"], m_properties["CalEnd"], range); m_uiForm.ppCalibration->replot(); @@ -424,9 +424,9 @@ namespace CustomInterfaces } const Mantid::MantidVec & dataX = energyWs->readX(0); - std::pair range(dataX.front(), dataX.back()); + QPair range(dataX.front(), dataX.back()); - setPlotRange("ResBackground", m_properties["ResStart"], m_properties["ResEnd"], range); + setPlotPropertyRange("ResBackground", m_properties["ResStart"], m_properties["ResEnd"], range); m_uiForm.ppResolution->clear(); m_uiForm.ppResolution->addSpectrum("Energy", energyWs, 0); @@ -462,13 +462,13 @@ namespace CustomInterfaces { double res = params[0]; - //Set default rebinning bounds - std::pair peakRange(-res*10, res*10); - setMiniPlotGuides("ResPeak", m_properties["ResELow"], m_properties["ResEHigh"], peakRange); + // Set default rebinning bounds + QPair peakRange(-res*10, res*10); + setRangeSelector("ResPeak", m_properties["ResELow"], m_properties["ResEHigh"], peakRange); - //Set default background bounds - std::pair backgroundRange(-res*9, -res*8); - setMiniPlotGuides("ResBackground", m_properties["ResStart"], m_properties["ResEnd"], backgroundRange); + // Set default background bounds + QPair backgroundRange(-res*9, -res*8); + setRangeSelector("ResBackground", m_properties["ResStart"], m_properties["ResEnd"], backgroundRange); } } } diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp index 67ef2a93c72c..c773f40c4c8b 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp @@ -215,10 +215,10 @@ namespace CustomInterfaces //Set peak and background ranges if(instDetails.size() >= 8) { - setMiniPlotGuides("SlicePeak", m_properties["PeakStart"], m_properties["PeakEnd"], - std::pair(instDetails["peak-start"].toDouble(), instDetails["peak-end"].toDouble())); - setMiniPlotGuides("SliceBackground", m_properties["BackgroundStart"], m_properties["BackgroundEnd"], - std::pair(instDetails["back-start"].toDouble(), instDetails["back-end"].toDouble())); + setRangeSelector("SlicePeak", m_properties["PeakStart"], m_properties["PeakEnd"], + qMakePair(instDetails["peak-start"].toDouble(), instDetails["peak-end"].toDouble())); + setRangeSelector("SliceBackground", m_properties["BackgroundStart"], m_properties["BackgroundEnd"], + qMakePair(instDetails["back-start"].toDouble(), instDetails["back-end"].toDouble())); } } @@ -258,13 +258,13 @@ namespace CustomInterfaces Mantid::API::AnalysisDataService::Instance().retrieve(wsname.toStdString())); const Mantid::MantidVec & dataX = input->readX(0); - std::pair range(dataX.front(), dataX.back()); + QPair range(dataX.front(), dataX.back()); m_uiForm.ppRawPlot->clear(); m_uiForm.ppRawPlot->addSpectrum("Raw", input, 0); - setPlotRange("SlicePeak", m_properties["PeakStart"], m_properties["PeakEnd"], range); - setPlotRange("SliceBackground", m_properties["BackgroundStart"], m_properties["BackgroundEnd"], range); + setPlotPropertyRange("SlicePeak", m_properties["PeakStart"], m_properties["PeakEnd"], range); + setPlotPropertyRange("SliceBackground", m_properties["BackgroundStart"], m_properties["BackgroundEnd"], range); m_uiForm.ppRawPlot->resizeX(); } diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp index b0b76b22135d..48f35777924b 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp @@ -113,10 +113,9 @@ namespace CustomInterfaces m_uiForm.ppRawPlot->clear(); m_uiForm.ppRawPlot->addSpectrum("Raw", filename, 0); - QPair curveRange = m_uiForm.ppRawPlot->getCurveRange("Raw"); - std::pair range = std::make_pair(curveRange.first, curveRange.second); - setMiniPlotGuides("MomentsRangeSelector", m_properties["EMin"], m_properties["EMax"], range); - setPlotRange("MomentsRangeSelector", m_properties["EMin"], m_properties["EMax"], range); + QPair range = m_uiForm.ppRawPlot->getCurveRange("Raw"); + setRangeSelector("MomentsRangeSelector", m_properties["EMin"], m_properties["EMax"], range); + setPlotPropertyRange("MomentsRangeSelector", m_properties["EMin"], m_properties["EMax"], range); connect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(updateProperties(QtProperty*, double))); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp index 6e2d5109c05f..62e87cf653f4 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTab.cpp @@ -22,8 +22,7 @@ namespace CustomInterfaces /** Constructor */ IndirectTab::IndirectTab(QObject* parent) : QObject(parent), - m_plots(), m_curves(), m_rangeSelectors(), - m_properties(), + m_rangeSelectors(), m_properties(), m_dblManager(new QtDoublePropertyManager()), m_blnManager(new QtBoolPropertyManager()), m_grpManager(new QtGroupPropertyManager()), m_dblEdFac(new DoubleEditorFactory()), m_pythonRunner(), @@ -143,146 +142,6 @@ namespace CustomInterfaces return load->isExecuted(); } - /** - * Gets the range of the curve plotted in the mini plot - * - * @param curveID :: The string index of the curve in the m_curves map - * @return A pair containing the maximum and minimum points of the curve - */ - std::pair IndirectTab::getCurveRange(const QString& curveID) - { - size_t npts = m_curves[curveID]->data().size(); - - if( npts < 2 ) - throw std::invalid_argument("Too few points on data curve to determine range."); - - return std::make_pair(m_curves[curveID]->data().x(0), m_curves[curveID]->data().x(npts-1)); - } - - /** - * Set the range of an axis on a miniplot - * - * @param plotID :: Index of plot in m_plots map - * @param axis :: ID of axis to set range of - * @param range :: Pair of double values specifying range - */ - void IndirectTab::setAxisRange(const QString& plotID, QwtPlot::Axis axis, - std::pair range) - { - m_plots[plotID]->setAxisScale(axis, range.first, range.second); - } - - /** - * Sets the X axis of a plot to match the range of x values on a curve - * - * @param plotID :: Index of plot in m_plots map - * @param curveID :: Index of curve in m_curves map - */ - void IndirectTab::setXAxisToCurve(const QString& plotID, const QString& curveID) - { - auto range = getCurveRange(curveID); - setAxisRange(plotID, QwtPlot::xBottom, range); - } - - /** - * Plot a workspace to the miniplot given a workspace name and - * a specturm index. - * - * This method uses the analysis data service to retrieve the workspace. - * - * @param workspace :: The name of the workspace - * @param index :: The spectrum index of the workspace - * @param plotID :: String index of the plot in the m_plots map - * @param curveID :: String index of the curve in the m_curves map, defaults to plot ID - */ - void IndirectTab::plotMiniPlot(const QString& workspace, size_t index, - const QString& plotID, const QString& curveID) - { - auto ws = AnalysisDataService::Instance().retrieveWS(workspace.toStdString()); - plotMiniPlot(ws, index, plotID, curveID); - } - - /** - * Replot a given mini plot - * - * @param plotID :: ID of plot in m_plots map - */ - void IndirectTab::replot(const QString& plotID) - { - m_plots[plotID]->replot(); - } - - /** - * Removes a curve from a mini plot and deletes it. - * - * @param curveID :: ID of plot in m_plots map - */ - void IndirectTab::removeCurve(const QString& curveID) - { - if(m_curves[curveID] == NULL) - return; - - m_curves[curveID]->attach(NULL); - delete m_curves[curveID]; - m_curves[curveID] = NULL; - } - - /** - * Removes all curves from their plots. - */ - void IndirectTab::removeAllCurves() - { - for(auto it = m_curves.begin(); it != m_curves.end(); ++it) - { - it->second->attach(NULL); - delete it->second; - } - - m_curves.clear(); - } - - /** - * Plot a workspace to the miniplot given a workspace pointer and - * a specturm index. - * - * @param workspace :: Pointer to the workspace - * @param wsIndex :: The spectrum index of the workspace - * @param plotID :: String index of the plot in the m_plots map - * @param curveID :: String index of the curve in the m_curves map, defaults to plot ID - */ - void IndirectTab::plotMiniPlot(const Mantid::API::MatrixWorkspace_const_sptr & workspace, size_t wsIndex, - const QString& plotID, const QString& curveID) - { - using Mantid::MantidVec; - - QString cID = curveID; - if(cID == "") - cID = plotID; - - //check if we can plot - if( wsIndex >= workspace->getNumberHistograms() || workspace->readX(0).size() < 2 ) - return; - - const bool logScale(false), distribution(false); - QwtWorkspaceSpectrumData wsData(*workspace, static_cast(wsIndex), logScale, distribution); - - removeCurve(cID); - - size_t nhist = workspace->getNumberHistograms(); - if ( wsIndex >= nhist ) - { - emit showMessageBox("Error: Workspace index out of range."); - } - else - { - m_curves[cID] = new QwtPlotCurve(); - m_curves[cID]->setData(wsData); - m_curves[cID]->attach(m_plots[plotID]); - - m_plots[plotID]->replot(); - } - } - /** * Sets the edge bounds of plot to prevent the user inputting invalid values * Also sets limits for range selector movement @@ -292,8 +151,8 @@ namespace CustomInterfaces * @param max :: The upper bound property in the property browser * @param bounds :: The upper and lower bounds to be set */ - void IndirectTab::setPlotRange(const QString& rsID, QtProperty* min, QtProperty* max, - const std::pair& bounds) + void IndirectTab::setPlotPropertyRange(const QString& rsID, QtProperty* min, QtProperty* max, + const QPair & bounds) { m_dblManager->setMinimum(min, bounds.first); m_dblManager->setMaximum(min, bounds.second); @@ -303,15 +162,15 @@ namespace CustomInterfaces } /** - * Set the position of the guides on the mini plot + * Set the position of the range selectors on the mini plot * * @param rsID :: The string index of the range selector in the map m_rangeSelectors * @param lower :: The lower bound property in the property browser * @param upper :: The upper bound property in the property browser * @param bounds :: The upper and lower bounds to be set */ - void IndirectTab::setMiniPlotGuides(const QString& rsID, QtProperty* lower, QtProperty* upper, - const std::pair& bounds) + void IndirectTab::setRangeSelector(const QString& rsID, QtProperty* lower, QtProperty* upper, + const QPair & bounds) { m_dblManager->setValue(lower, bounds.first); m_dblManager->setValue(upper, bounds.second); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp index c2413f295ed6..a8bc0b35b0e6 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmission.cpp @@ -19,13 +19,6 @@ namespace CustomInterfaces connect(this, SIGNAL(newInstrumentConfiguration()), this, SLOT(instrumentSet())); - // Preview plot - m_plots["PreviewPlot"] = new QwtPlot(m_parentWidget); - m_plots["PreviewPlot"]->setAxisFont(QwtPlot::xBottom, parent->font()); - m_plots["PreviewPlot"]->setAxisFont(QwtPlot::yLeft, parent->font()); - m_plots["PreviewPlot"]->setCanvasBackground(Qt::white); - m_uiForm.plotPreview->addWidget(m_plots["PreviewPlot"]); - // Update the preview plot when the algorithm is complete connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(transAlgDone(bool))); connect(m_uiForm.dsSampleInput, SIGNAL(dataReady(QString)), this, SLOT(dataLoaded())); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/JumpFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/JumpFit.cpp index 839df22f51d6..5fa2ba6da67d 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/JumpFit.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/JumpFit.cpp @@ -222,17 +222,16 @@ namespace MantidQt m_uiForm.ppPlot->clear(); m_uiForm.ppPlot->addSpectrum("Sample", filename, m_spectraList[currentWidth]); - std::pair res; - QPair curveRange = m_uiForm.ppPlot->getCurveRange("Sample"); - std::pair range(curveRange.first, curveRange.second); + QPair res; + QPair range = m_uiForm.ppPlot->getCurveRange("Sample"); // Use the values from the instrument parameter file if we can if(getInstrumentResolution(filename, res)) - setMiniPlotGuides("JumpFitQ", m_properties["QMin"], m_properties["QMax"], res); + setRangeSelector("JumpFitQ", m_properties["QMin"], m_properties["QMax"], res); else - setMiniPlotGuides("JumpFitQ", m_properties["QMin"], m_properties["QMax"], range); + setRangeSelector("JumpFitQ", m_properties["QMin"], m_properties["QMax"], range); - setPlotRange("JumpFitQ", m_properties["QMin"], m_properties["QMax"], range); + setPlotPropertyRange("JumpFitQ", m_properties["QMin"], m_properties["QMax"], range); } else { diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp index 4617207a3c9c..aab618bf18e3 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp @@ -264,10 +264,10 @@ namespace MantidQt int numHist = static_cast(inWs->getNumberHistograms()) - 1; m_uiForm.spPreviewSpectrum->setMaximum(numHist); updateMiniPlot(); - QPair curveRange = m_uiForm.ppPlot->getCurveRange("Sample"); - std::pair range(curveRange.first, curveRange.second); - setMiniPlotGuides("QuasiERange", m_properties["EMin"], m_properties["EMax"], range); - setPlotRange("QuasiERange", m_properties["EMin"], m_properties["EMax"], range); + + QPair range = m_uiForm.ppPlot->getCurveRange("Sample"); + setRangeSelector("QuasiERange", m_properties["EMin"], m_properties["EMax"], range); + setPlotPropertyRange("QuasiERange", m_properties["EMin"], m_properties["EMax"], range); } /** diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ResNorm.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ResNorm.cpp index fb7cc28452e1..354d1f50df9e 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ResNorm.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ResNorm.cpp @@ -126,9 +126,8 @@ namespace MantidQt void ResNorm::handleVanadiumInputReady(const QString& filename) { m_uiForm.ppPlot->addSpectrum("Vanadium", filename, m_previewSpec); - std::pair res; - QPair curveRange = m_uiForm.ppPlot->getCurveRange("Vanadium"); - std::pair range(curveRange.first, curveRange.second); + QPair res; + QPair range = m_uiForm.ppPlot->getCurveRange("Vanadium"); MatrixWorkspace_sptr vanWs = AnalysisDataService::Instance().retrieveWS(filename.toStdString()); m_uiForm.spPreviewSpectrum->setMaximum(static_cast(vanWs->getNumberHistograms()) - 1); @@ -140,14 +139,14 @@ namespace MantidQt res.first = res.first * 10; res.second = res.second * 10; - setMiniPlotGuides("ResNormERange", m_properties["EMin"], m_properties["EMax"], res); + setRangeSelector("ResNormERange", m_properties["EMin"], m_properties["EMax"], res); } else { - setMiniPlotGuides("ResNormERange", m_properties["EMin"], m_properties["EMax"], range); + setRangeSelector("ResNormERange", m_properties["EMin"], m_properties["EMax"], range); } - setPlotRange("ResNormERange", m_properties["EMin"], m_properties["EMax"], range); + setPlotPropertyRange("ResNormERange", m_properties["EMin"], m_properties["EMax"], range); } /** diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp index e437f0e4ae20..98a8c958ed76 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp @@ -10,7 +10,7 @@ namespace MantidQt { namespace CustomInterfaces { - Stretch::Stretch(QWidget * parent) : + Stretch::Stretch(QWidget * parent) : IndirectBayesTab(parent) { m_uiForm.setupUi(parent); @@ -29,7 +29,7 @@ namespace MantidQt m_properties["SampleBinning"] = m_dblManager->addProperty("Sample Binning"); m_properties["Sigma"] = m_dblManager->addProperty("Sigma"); m_properties["Beta"] = m_dblManager->addProperty("Beta"); - + m_dblManager->setDecimals(m_properties["EMin"], NUM_DECIMALS); m_dblManager->setDecimals(m_properties["EMax"], NUM_DECIMALS); m_dblManager->setDecimals(m_properties["SampleBinning"], INT_DECIMALS); @@ -63,7 +63,7 @@ namespace MantidQt /** * Validate the form to check the program can be run - * + * * @return :: Whether the form was valid */ bool Stretch::validate() @@ -86,7 +86,7 @@ namespace MantidQt * Collect the settings on the GUI and build a python * script that runs Stretch */ - void Stretch::run() + void Stretch::run() { using namespace Mantid::API; @@ -95,7 +95,7 @@ namespace MantidQt QString elasticPeak("False"); QString sequence("False"); - QString pyInput = + QString pyInput = "from IndirectBayes import QuestRun\n"; QString sampleName = m_uiForm.dsSample->getCurrentDataName(); @@ -134,7 +134,7 @@ namespace MantidQt /** * Set the data selectors to use the default save directory * when browsing for input files. - * + * * @param settings :: The current settings */ void Stretch::loadSettings(const QSettings& settings) @@ -146,16 +146,15 @@ namespace MantidQt /** * Plots the loaded file to the miniplot and sets the guides * and the range - * + * * @param filename :: The name of the workspace to plot */ void Stretch::handleSampleInputReady(const QString& filename) { m_uiForm.ppPlot->addSpectrum("Sample", filename, 0); - QPair curveRange = m_uiForm.ppPlot->getCurveRange("Sample"); - std::pair range(curveRange.first, curveRange.second); - setMiniPlotGuides("StretchERange", m_properties["EMin"], m_properties["EMax"], range); - setPlotRange("StretchERange", m_properties["EMin"], m_properties["EMax"], range); + QPair range = m_uiForm.ppPlot->getCurveRange("Sample"); + setRangeSelector("StretchERange", m_properties["EMin"], m_properties["EMax"], range); + setPlotPropertyRange("StretchERange", m_properties["EMin"], m_properties["EMax"], range); } /** @@ -175,7 +174,7 @@ namespace MantidQt */ void Stretch::maxValueChanged(double max) { - m_dblManager->setValue(m_properties["EMax"], max); + m_dblManager->setValue(m_properties["EMax"], max); } /** From b9d7582de4673dbd16636e96efbf124b272d4cc0 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Fri, 13 Feb 2015 15:32:27 +0000 Subject: [PATCH 091/414] Re #9556 Removing unused macros --- .../Framework/CurveFitting/src/DynamicKuboToyabe.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index 5ece1fe010d9..b8f353c06a0f 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -6,13 +6,6 @@ #include "MantidAPI/FunctionFactory.h" #include -#define EPS 1e-6 -#define JMAX 14 -#define JMAXP (JMAX+1) -#define K 5 -#define NR_END 1 -#define FREE_ARG char* - namespace Mantid { namespace CurveFitting From 5db99b85456a8054564625b06025536770a344b1 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Fri, 13 Feb 2015 15:40:28 +0000 Subject: [PATCH 092/414] Reorganise the windows built script so the order matches the Unix one Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript.bat | 77 ++++++++++++++--------- 1 file changed, 49 insertions(+), 28 deletions(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript.bat b/Code/Mantid/Build/Jenkins/buildscript.bat index f861162c87c9..bdc52542d22c 100755 --- a/Code/Mantid/Build/Jenkins/buildscript.bat +++ b/Code/Mantid/Build/Jenkins/buildscript.bat @@ -10,19 +10,6 @@ "C:\Program Files (x86)\CMake 2.8\bin\cmake.exe" --version echo %sha1% -::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -:: Check the required build configuration -::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -set BUILD_CONFIG= -if not "%JOB_NAME%"=="%JOB_NAME:debug=%" ( - set BUILD_CONFIG=Debug -) else ( -if not "%JOB_NAME%"=="%JOB_NAME:relwithdbg=%" ( - set BUILD_CONFIG=RelWithDbg -) else ( - set BUILD_CONFIG=Release - )) - ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Get or update the third party dependencies ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: @@ -43,23 +30,52 @@ if NOT DEFINED MANTID_DATA_STORE ( ) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -:: Check whether this is a clean build (must have 'clean' in the job name) +:: Check job requirements from the name ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -set PACKAGE_DOCS= if "%JOB_NAME%"=="%JOB_NAME:clean=%" ( - set CLEANBUILD=no -) else ( - set CLEANBUILD=yes - set PACKAGE_DOCS=-DPACKAGE_DOCS=True - rmdir /S /Q build + set CLEANBUILD=yes + set BUILDPKG=yes +) +if "%JOB_NAME%"=="%JOB_NAME:pull_requests=%" ( + set BUILDPKG=yes +) + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Packaging options +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +set PACKAGE_DOCS= +if "%BUILDPKG%" EQU "yes" ( + set PACKAGE_DOCS=-DPACKAGE_DOCS=ON ) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -:: Create the build directory if it doesn't exist +:: Setup the build directory ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +if "%CLEANBUILD%" EQU "yes" ( + rmdir /S /Q %WORKSPACE%\build +) md %WORKSPACE%\build cd %WORKSPACE%\build +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Clean up any artifacts from last build so that if it fails +:: they don't get archived again. +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +del *.exe + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Check the required build configuration +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +set BUILD_CONFIG= +if not "%JOB_NAME%"=="%JOB_NAME:debug=%" ( + set BUILD_CONFIG=Debug +) else ( +if not "%JOB_NAME%"=="%JOB_NAME:relwithdbg=%" ( + set BUILD_CONFIG=RelWithDbg +) else ( + set BUILD_CONFIG=Release + )) + ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: CMake configuration ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: @@ -75,17 +91,22 @@ if ERRORLEVEL 1 exit /B %ERRORLEVEL% ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Run the tests ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +# Remove the user properties file just in case anything polluted it +set USERPROPS=bin\%BUILD_CONFIG%\Mantid.user.properties +del %USERPROPS% "C:\Program Files (x86)\CMake 2.8\bin\ctest.exe" -C %BUILD_CONFIG% -j%BUILD_THREADS% --schedule-random --output-on-failure if ERRORLEVEL 1 exit /B %ERRORLEVEL% ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -:: Create the install kit if this is a clean build +:: Create the install kit if required ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -if "%CLEANBUILD%" EQU "yes" ( - :: Build offline documentation - msbuild /nologo /nr:false /p:Configuration=%BUILD_CONFIG% docs/docs-qthelp.vcxproj +if "%BUILDPKG%" EQU "yes" ( + :: Build offline documentation + msbuild /nologo /nr:false /p:Configuration=%BUILD_CONFIG% docs/docs-qthelp.vcxproj - :: ignore errors as the exit code of the build isn't correct - ::if ERRORLEVEL 1 exit /B %ERRORLEVEL% - cpack -C %BUILD_CONFIG% --config CPackConfig.cmake + :: Ignore errors as the exit code of msbuild is wrong here. + :: It always marks the build as a failure even thought the MantidPlot exit + :: code is correct! + ::if ERRORLEVEL 1 exit /B %ERRORLEVEL% + cpack -C %BUILD_CONFIG% --config CPackConfig.cmake ) From 72c396dede5b88f121875fc4bd5c3e7069638320 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Fri, 13 Feb 2015 17:10:24 +0000 Subject: [PATCH 093/414] Add save to smooth calibration Refs #10513 --- .../src/Indirect/IndirectCalibration.cpp | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp index 7bd345c26e9c..ca994e1e8444 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectCalibration.cpp @@ -184,7 +184,7 @@ namespace CustomInterfaces QString calibrationWsName = outputWorkspaceNameStem + "_calib"; // Configure the calibration algorithm - IAlgorithm_sptr calibrationAlg = AlgorithmManager::Instance().create("CreateCalibrationWorkspace", -1); + IAlgorithm_sptr calibrationAlg = AlgorithmManager::Instance().create("CreateCalibrationWorkspace"); calibrationAlg->initialize(); calibrationAlg->setProperty("InputFiles", filenames.toStdString()); @@ -212,7 +212,7 @@ namespace CustomInterfaces // Add save algorithm to queue if ticked if( m_uiForm.ckSave->isChecked() ) { - IAlgorithm_sptr saveAlg = AlgorithmManager::Instance().create("SaveNexus", -1); + IAlgorithm_sptr saveAlg = AlgorithmManager::Instance().create("SaveNexusProcessed"); saveAlg->initialize(); saveAlg->setProperty("Filename", calibrationWsName.toStdString() + ".nxs"); @@ -237,7 +237,7 @@ namespace CustomInterfaces bool smooth = m_uiForm.ckSmoothResolution->isChecked(); bool save = m_uiForm.ckSave->isChecked(); - Mantid::API::IAlgorithm_sptr resAlg = Mantid::API::AlgorithmManager::Instance().create("IndirectResolution", -1); + IAlgorithm_sptr resAlg = AlgorithmManager::Instance().create("IndirectResolution", -1); resAlg->initialize(); resAlg->setProperty("InputFiles", filenames.toStdString()); @@ -266,7 +266,7 @@ namespace CustomInterfaces if(smooth) { - Mantid::API::IAlgorithm_sptr smoothAlg = Mantid::API::AlgorithmManager::Instance().create("WienerSmooth"); + IAlgorithm_sptr smoothAlg = AlgorithmManager::Instance().create("WienerSmooth"); smoothAlg->initialize(); smoothAlg->setProperty("OutputWorkspace", resolutionWsName.toStdString()); @@ -277,7 +277,14 @@ namespace CustomInterfaces if(save) { - //TODO: Do save + IAlgorithm_sptr saveAlg = AlgorithmManager::Instance().create("SaveNexusProcessed"); + saveAlg->initialize(); + + BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromSmoothProps; + inputFromSmoothProps["InputWorkspace"] = calibrationWsName.toStdString(); + saveAlg->setProperty("Filename", resolutionWsName.toStdString() + ".nxs"); + + m_batchAlgoRunner->addAlgorithm(saveAlg, inputFromSmoothProps); } } @@ -393,8 +400,8 @@ namespace CustomInterfaces return; } - Mantid::API::MatrixWorkspace_sptr input = boost::dynamic_pointer_cast( - Mantid::API::AnalysisDataService::Instance().retrieve(wsname.toStdString())); + MatrixWorkspace_sptr input = boost::dynamic_pointer_cast( + AnalysisDataService::Instance().retrieve(wsname.toStdString())); const Mantid::MantidVec & dataX = input->readX(0); std::pair range(dataX.front(), dataX.back()); @@ -478,7 +485,7 @@ namespace CustomInterfaces * * @param ws :: Mantid workspace containing the loaded instument */ - void IndirectCalibration::calSetDefaultResolution(Mantid::API::MatrixWorkspace_const_sptr ws) + void IndirectCalibration::calSetDefaultResolution(MatrixWorkspace_const_sptr ws) { auto inst = ws->getInstrument(); auto analyser = inst->getStringParameter("analyser"); From 1f5c8337cb1986a47f3cd68bc60c5243a9d3fe70 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Fri, 13 Feb 2015 11:45:55 +0000 Subject: [PATCH 094/414] refs #11056. New method createPeakHKL. Unit tested to ensure we are creating a self-consistent peak. Expose to python and unit test there too. --- .../Framework/API/inc/MantidAPI/IPeak.h | 2 +- .../API/inc/MantidAPI/IPeaksWorkspace.h | 15 ++++-- .../DataObjects/inc/MantidDataObjects/Peak.h | 6 +-- .../inc/MantidDataObjects/PeaksWorkspace.h | 7 ++- .../Mantid/Framework/DataObjects/src/Peak.cpp | 12 ++--- .../DataObjects/src/PeaksWorkspace.cpp | 32 ++++++++++- .../Framework/DataObjects/test/PeakTest.h | 22 ++------ .../DataObjects/test/PeaksWorkspaceTest.h | 54 +++++++++++++++++++ .../Framework/MDEvents/src/MDWSTransform.cpp | 2 +- .../mantid/api/src/Exports/IPeak.cpp | 10 +++- .../api/src/Exports/IPeaksWorkspace.cpp | 27 +++++++++- .../python/mantid/api/IPeaksWorkspaceTest.py | 15 +++++- 12 files changed, 166 insertions(+), 38 deletions(-) diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h b/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h index a0c92986df81..0ceb44554efc 100644 --- a/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h +++ b/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h @@ -51,7 +51,7 @@ class MANTID_API_DLL IPeak { virtual bool findDetector() = 0; virtual void setQSampleFrame(Mantid::Kernel::V3D QSampleFrame, - double detectorDistance = 1.0) = 0; + boost::optional detectorDistance = boost::optional()) = 0; virtual void setQLabFrame(Mantid::Kernel::V3D QLabFrame, boost::optional detectorDistance = boost::optional()) = 0; diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/IPeaksWorkspace.h b/Code/Mantid/Framework/API/inc/MantidAPI/IPeaksWorkspace.h index 7282be8542cc..15bd48bf8b94 100644 --- a/Code/Mantid/Framework/API/inc/MantidAPI/IPeaksWorkspace.h +++ b/Code/Mantid/Framework/API/inc/MantidAPI/IPeaksWorkspace.h @@ -7,6 +7,7 @@ #include "MantidAPI/ITableWorkspace.h" #include "MantidAPI/ExperimentInfo.h" #include "MantidKernel/SpecialCoordinateSystem.h" +#include namespace Mantid { @@ -98,12 +99,20 @@ class MANTID_API_DLL IPeaksWorkspace : public ITableWorkspace, //--------------------------------------------------------------------------------------------- /** Create an instance of a Peak - * @param QLabFrame :: Q of the center of the peak, in reciprocal space - * @param detectorDistance :: distance between the sample and the detector. + * @param QLabFrame :: Q of the center of the peak in the lab frame, in reciprocal space + * @param detectorDistance :: Optional distance between the sample and the detector. Calculated if not provided. * @return a pointer to a new Peak object. */ virtual IPeak *createPeak(Mantid::Kernel::V3D QLabFrame, - double detectorDistance = 1.0) const = 0; + boost::optional detectorDistance) const = 0; + + + /** + * Create an instance of a peak using a V3D + * @param HKL V3D + * @return a pointer to a new Peak object. + */ + virtual IPeak *createPeakHKL(Mantid::Kernel::V3D HKL) const = 0; //--------------------------------------------------------------------------------------------- /** Determine if the workspace has been integrated using a peaks integration diff --git a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Peak.h b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Peak.h index cc3a5a084750..c5c33fbc2a52 100644 --- a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Peak.h +++ b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Peak.h @@ -28,10 +28,10 @@ class DLLExport Peak : public API::IPeak { Peak(); Peak(Geometry::Instrument_const_sptr m_inst, Mantid::Kernel::V3D QLabFrame, - double detectorDistance = 1.0); + boost::optional detectorDistance = boost::optional()); Peak(Geometry::Instrument_const_sptr m_inst, Mantid::Kernel::V3D QSampleFrame, Mantid::Kernel::Matrix goniometer, - double detectorDistance = 1.0); + boost::optional detectorDistance = boost::optional()); Peak(Geometry::Instrument_const_sptr m_inst, int m_DetectorID, double m_Wavelength); Peak(Geometry::Instrument_const_sptr m_inst, int m_DetectorID, @@ -86,7 +86,7 @@ class DLLExport Peak : public API::IPeak { Mantid::Kernel::V3D getDetectorPositionNoCheck() const; void setQSampleFrame(Mantid::Kernel::V3D QSampleFrame, - double detectorDistance = 1.0); + boost::optional detectorDistance = boost::optional()); void setQLabFrame(Mantid::Kernel::V3D QLabFrame, boost::optional detectorDistance = boost::optional()); diff --git a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/PeaksWorkspace.h b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/PeaksWorkspace.h index 42cc58043f1b..4c4efe464c89 100644 --- a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/PeaksWorkspace.h +++ b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/PeaksWorkspace.h @@ -21,6 +21,7 @@ #include #include #include +#include // IsamplePosition should be IsampleOrientation namespace Mantid { @@ -108,9 +109,13 @@ class DLLExport PeaksWorkspace : public Mantid::API::IPeaksWorkspace { const Peak &getPeak(int peakNum) const; API::IPeak *createPeak(Kernel::V3D QFrame, - double detectorDistance = 1.0) const; + boost::optional detectorDistance = boost::optional()) const; std::vector> peakInfo(Kernel::V3D qFrame, bool labCoords) const; + + + Peak *createPeakHKL(Kernel::V3D HKL) const; + int peakInfoNumber(Kernel::V3D qFrame, bool labCoords) const; std::vector &getPeaks(); diff --git a/Code/Mantid/Framework/DataObjects/src/Peak.cpp b/Code/Mantid/Framework/DataObjects/src/Peak.cpp index f71934530f6f..71e958d83617 100644 --- a/Code/Mantid/Framework/DataObjects/src/Peak.cpp +++ b/Code/Mantid/Framework/DataObjects/src/Peak.cpp @@ -30,11 +30,11 @@ Peak::Peak() * * @param m_inst :: Shared pointer to the instrument for this peak detection * @param QLabFrame :: Q of the center of the peak, in reciprocal space - * @param detectorDistance :: distance between the sample and the detector. + * @param detectorDistance :: Optional distance between the sample and the detector. Calculated if not explicitly provided. * Used to give a valid TOF. Default 1.0 meters. */ Peak::Peak(Geometry::Instrument_const_sptr m_inst, - Mantid::Kernel::V3D QLabFrame, double detectorDistance) + Mantid::Kernel::V3D QLabFrame, boost::optional detectorDistance) : m_H(0), m_K(0), m_L(0), m_Intensity(0), m_SigmaIntensity(0), m_BinCount(0), m_GoniometerMatrix(3, 3, true), m_InverseGoniometerMatrix(3, 3, true), m_RunNumber(0), m_MonitorCount(0), @@ -52,12 +52,12 @@ Peak::Peak(Geometry::Instrument_const_sptr m_inst, * @param QSampleFrame :: Q of the center of the peak, in reciprocal space, in *the sample frame (goniometer rotation accounted for). * @param goniometer :: a 3x3 rotation matrix - * @param detectorDistance :: distance between the sample and the detector. + * @param detectorDistance :: Optional distance between the sample and the detector. Calculated if not explicitly provided. * Used to give a valid TOF. Default 1.0 meters. */ Peak::Peak(Geometry::Instrument_const_sptr m_inst, Mantid::Kernel::V3D QSampleFrame, - Mantid::Kernel::Matrix goniometer, double detectorDistance) + Mantid::Kernel::Matrix goniometer, boost::optional detectorDistance) : m_H(0), m_K(0), m_L(0), m_Intensity(0), m_SigmaIntensity(0), m_BinCount(0), m_GoniometerMatrix(goniometer), m_InverseGoniometerMatrix(goniometer), m_RunNumber(0), m_MonitorCount(0), @@ -464,10 +464,10 @@ Mantid::Kernel::V3D Peak::getQSampleFrame() const { * This is in inelastic convention: momentum transfer of the LATTICE! * Also, q does NOT have a 2pi factor = it is equal to 1/wavelength. * @param detectorDistance :: distance between the sample and the detector. - * Used to give a valid TOF. Default 1.0 meters. + * Used to give a valid TOF. You do NOT need to explicitly set this. */ void Peak::setQSampleFrame(Mantid::Kernel::V3D QSampleFrame, - double detectorDistance) { + boost::optional detectorDistance) { V3D Qlab = m_GoniometerMatrix * QSampleFrame; this->setQLabFrame(Qlab, detectorDistance); } diff --git a/Code/Mantid/Framework/DataObjects/src/PeaksWorkspace.cpp b/Code/Mantid/Framework/DataObjects/src/PeaksWorkspace.cpp index 5258f57751e4..93ee5c6577c9 100644 --- a/Code/Mantid/Framework/DataObjects/src/PeaksWorkspace.cpp +++ b/Code/Mantid/Framework/DataObjects/src/PeaksWorkspace.cpp @@ -199,11 +199,11 @@ const Peak &PeaksWorkspace::getPeak(const int peakNum) const { //--------------------------------------------------------------------------------------------- /** Creates an instance of a Peak BUT DOES NOT ADD IT TO THE WORKSPACE * @param QLabFrame :: Q of the center of the peak, in reciprocal space - * @param detectorDistance :: distance between the sample and the detector. + * @param detectorDistance :: optional distance between the sample and the detector. You do NOT need to explicitly provide this distance. * @return a pointer to a new Peak object. */ API::IPeak *PeaksWorkspace::createPeak(Kernel::V3D QLabFrame, - double detectorDistance) const { + boost::optional detectorDistance) const { return new Peak(this->getInstrument(), QLabFrame, detectorDistance); } @@ -299,6 +299,7 @@ PeaksWorkspace::peakInfo(Kernel::V3D qFrame, bool labCoords) const { } try { + API::IPeak *peak = createPeak(Qlab); if (sample().hasOrientedLattice()) { @@ -387,6 +388,33 @@ PeaksWorkspace::peakInfo(Kernel::V3D qFrame, bool labCoords) const { return Result; } +/** + * Create a Peak from a HKL value provided by the client. + * + * + * @param HKL : reciprocal lattice vector coefficients + * @return Fully formed peak. + */ +Peak *PeaksWorkspace::createPeakHKL(V3D HKL) const +{ + Geometry::OrientedLattice lattice = this->sample().getOrientedLattice(); + Geometry::Goniometer goniometer = this->run().getGoniometer(); + + // Calculate qLab from q HKL. As per Busing and Levy 1967, q_lab_frame = 2pi * Goniometer * UB * HKL + V3D qLabFrame = goniometer.getR() * lattice.getUB() * HKL * 2 * M_PI; + + // create a peak using the qLab frame + auto peak = new Peak(this->getInstrument(), qLabFrame); // This should calculate the detector positions too. + + // We need to set HKL separately to keep things consistent. + peak->setHKL(HKL[0], HKL[1], HKL[2]); + + // Set the goniometer + peak->setGoniometerMatrix(goniometer.getR()); + + return peak; +} + /** * Returns selected information for a "peak" at QLabFrame. * diff --git a/Code/Mantid/Framework/DataObjects/test/PeakTest.h b/Code/Mantid/Framework/DataObjects/test/PeakTest.h index 638f299f8245..317d54c3e840 100644 --- a/Code/Mantid/Framework/DataObjects/test/PeakTest.h +++ b/Code/Mantid/Framework/DataObjects/test/PeakTest.h @@ -271,8 +271,9 @@ class PeakTest : public CxxTest::TestSuite void test_setQLabFrame_ThrowsIfQIsNull() { Peak p1(inst, 10000, 2.0); - TS_ASSERT_THROWS_ANYTHING(Peak p2(inst, V3D(0,0,0), 1.0)); - TS_ASSERT_THROWS_ANYTHING(Peak p2(inst, V3D(1,2,0), 1.0)); + const boost::optional distance = 1.0; + TS_ASSERT_THROWS_ANYTHING(Peak p2(inst, V3D(0,0,0), distance)); + TS_ASSERT_THROWS_ANYTHING(Peak p2(inst, V3D(1,2,0), distance)); } @@ -301,7 +302,7 @@ class PeakTest : public CxxTest::TestSuite V3D detPos1 = p1.getDetPos(); // Construct using just Q - Peak p2(inst, Qlab1, detPos1.norm()); + Peak p2(inst, Qlab1, boost::optional(detPos1.norm())); comparePeaks(p1, p2); TS_ASSERT_EQUALS( p2.getBankName(), "None"); TS_ASSERT_EQUALS( p2.getRow(), -1); @@ -311,7 +312,6 @@ class PeakTest : public CxxTest::TestSuite void test_setQLabFrame2() { - // Create fictional instrument const V3D source(0,0,0); const V3D sample(15, 0, 0); @@ -320,24 +320,12 @@ class PeakTest : public CxxTest::TestSuite const V3D beam2 = detectorPos - sample; auto minimalInstrument = ComponentCreationHelper::createMinimalInstrument( source, sample, detectorPos ); - // Calculate energy of neutron based on velocity - const double velocity = 1.1 * 10e3; // m/sec - double efixed = 0.5 * Mantid::PhysicalConstants::NeutronMass * velocity * velocity ; // In Joules - efixed = efixed / Mantid::PhysicalConstants::meV; - // Derive distances and angles const double l1 = beam1.norm(); const double l2 = beam2.norm(); - const double scatteringAngle2 = beam2.angle(beam1); const V3D qLabDir = (beam1/l1) - (beam2/l2); - // Derive the wavelength - std::vector x; const double microSecsInSec = 1e6; - x.push_back( ( (l1 + l2) / velocity ) * microSecsInSec ); // Make a TOF - std::vector y; - Unit_sptr unitOfLambda = UnitFactory::Instance().create("Wavelength"); - unitOfLambda->fromTOF(x, y, l1, l2, scatteringAngle2, 0, efixed, 0); // Derive QLab for diffraction const double wavenumber_in_angstrom_times_tof_in_microsec = @@ -389,7 +377,7 @@ class PeakTest : public CxxTest::TestSuite V3D detPos1 = p1.getDetPos(); // Construct using just Q - Peak p2(inst, Qlab1, detPos1.norm()); + Peak p2(inst, Qlab1, boost::optional(detPos1.norm())); TS_ASSERT( p2.findDetector() ); comparePeaks(p1, p2); TS_ASSERT_EQUALS( p2.getBankName(), "bank1"); diff --git a/Code/Mantid/Framework/DataObjects/test/PeaksWorkspaceTest.h b/Code/Mantid/Framework/DataObjects/test/PeaksWorkspaceTest.h index 20d627c7d99e..45f37ed189d0 100644 --- a/Code/Mantid/Framework/DataObjects/test/PeaksWorkspaceTest.h +++ b/Code/Mantid/Framework/DataObjects/test/PeaksWorkspaceTest.h @@ -14,6 +14,8 @@ #include "MantidKernel/V3D.h" #include "MantidKernel/Strings.h" #include "MantidKernel/PhysicalConstants.h" +#include "MantidGeometry/Crystal/OrientedLattice.h" +#include "MantidGeometry/Instrument/Goniometer.h" #include "MantidTestHelpers/NexusTestHelper.h" #include "MantidTestHelpers/ComponentCreationHelper.h" #include "MantidAPI/AlgorithmManager.h" @@ -360,6 +362,58 @@ class PeaksWorkspaceTest : public CxxTest::TestSuite TS_ASSERT_EQUALS(coordSystem, pw->getSpecialCoordinateSystem()); } + void test_createPeakHKL() + { + // Create simple fictional instrument + const V3D source(0,0,0); + const V3D sample(15, 0, 0); + const V3D detectorPos(20, 5, 0); + const V3D beam1 = sample - source; + const V3D beam2 = detectorPos - sample; + auto minimalInstrument = ComponentCreationHelper::createMinimalInstrument( source, sample, detectorPos ); + + // Derive distances and angles + const double l1 = beam1.norm(); + const double l2 = beam2.norm(); + const V3D qLabDir = (beam1/l1) - (beam2/l2); + + const double microSecsInSec = 1e6; + + // Derive QLab for diffraction + const double wavenumber_in_angstrom_times_tof_in_microsec = + (Mantid::PhysicalConstants::NeutronMass * (l1 + l2) * 1e-10 * microSecsInSec) / + Mantid::PhysicalConstants::h_bar; + V3D qLab = qLabDir * wavenumber_in_angstrom_times_tof_in_microsec; + + Mantid::Geometry::OrientedLattice orientedLattice(1, 1, 1, 90, 90, 90); // U is identity, real and reciprocal lattice vectors are identical. + Mantid::Geometry::Goniometer goniometer; // identity + V3D hkl = qLab / (2 * M_PI); // Given our settings above, this is the simplified relationship between qLab and hkl. + + // Now create a peaks workspace around the simple fictional instrument + PeaksWorkspace ws; + ws.setInstrument(minimalInstrument); + ws.mutableSample().setOrientedLattice(&orientedLattice); + ws.mutableRun().setGoniometer(goniometer, false); + + // Create the peak + Peak* peak = ws.createPeakHKL(hkl); + + /* + Now we check we have made a self - consistent peak + */ + TSM_ASSERT_EQUALS("New peak should have HKL we demanded.", hkl, peak->getHKL()); + TSM_ASSERT_EQUALS("New peak should have QLab we expected.", qLab, peak->getQLabFrame()); + TSM_ASSERT_EQUALS("QSample and QLab should be identical given the identity goniometer settings.", peak->getQLabFrame(), peak->getQSampleFrame()); + auto detector = peak->getDetector(); + TSM_ASSERT("No detector", detector); + TSM_ASSERT_EQUALS("This detector id does not match what we expect from the instrument definition", 1, detector->getID()); + TSM_ASSERT_EQUALS("Thie detector position is wrong", detectorPos, detector->getPos()); + TSM_ASSERT_EQUALS("Goniometer has not been set properly", goniometer.getR(), peak->getGoniometerMatrix()); + + // Clean up. + delete peak; + } + private: PeaksWorkspace_sptr createSaveTestPeaksWorkspace() diff --git a/Code/Mantid/Framework/MDEvents/src/MDWSTransform.cpp b/Code/Mantid/Framework/MDEvents/src/MDWSTransform.cpp index 15dbab13aef5..d4c24c31db6a 100644 --- a/Code/Mantid/Framework/MDEvents/src/MDWSTransform.cpp +++ b/Code/Mantid/Framework/MDEvents/src/MDWSTransform.cpp @@ -9,9 +9,9 @@ namespace { // logger for the algorithm workspaces Kernel::Logger g_Log("MDWSTransform"); } - using namespace CnvrtToMD; + /** method to build the Q-coordinates transformation. * * @param TargWSDescription -- the class which describes target MD workspace. In diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp index f88422894a47..7d2623a13ef3 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp @@ -14,6 +14,11 @@ void setQLabFrame(IPeak &peak, Mantid::Kernel::V3D qLabFrame, double distance) { // Set the qlab frame return peak.setQLabFrame(qLabFrame, distance); } +void setQSampleFrame(IPeak &peak, Mantid::Kernel::V3D qSampleFrame, double distance) { + // Set the qsample frame + return peak.setQSampleFrame(qSampleFrame, distance); +} + } void export_IPeak() @@ -42,8 +47,9 @@ void export_IPeak() "Using the instrument set in the peak, perform ray tracing to find the exact detector.") .def("getQSampleFrame", &IPeak::getQSampleFrame, "Return the Q change (of the lattice, k_i - k_f) for this peak." "The Q is in the Sample frame: the goniometer rotation WAS taken out. ") - .def("setQLabFrame", (void (IPeak::*)(Mantid::Kernel::V3D))&IPeak::setQLabFrame) - .def("setQLabFrame", setQLabFrame, "Set the peak using the peak's position in reciprocal space, in the lab frame.") + .def("setQLabFrame", (void (IPeak::*)(Mantid::Kernel::V3D))&IPeak::setQLabFrame, "Set the peak using the peak's position in reciprocal space, in the lab frame.") + .def("setQLabFrame", setQLabFrame, "Set the peak using the peak's position in reciprocal space, in the lab frame. Detector distance explicitly supplied.") // two argument overload + .def("setQSampleFrame", (void (IPeak::*)(Mantid::Kernel::V3D))&IPeak::setQSampleFrame, "Set the peak using the peak's position in reciprocal space, in the sample frame.") .def("setQSampleFrame", &IPeak::setQSampleFrame, "Set the peak using the peak's position in reciprocal space, in the sample frame.") .def("setWavelength", &IPeak::setWavelength, "Set the incident wavelength of the neutron. Calculates the energy from this assuming elastic scattering.") .def("getWavelength", &IPeak::getWavelength, "Return the incident wavelength") diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp index 80f30016b472..2b8f12e0975f 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp @@ -1,6 +1,7 @@ #include "MantidAPI/IPeaksWorkspace.h" #include "MantidAPI/IPeak.h" #include "MantidPythonInterface/kernel/Registry/DataItemInterface.h" +#include "MantidPythonInterface/kernel/Converters/PyObjectToV3D.h" #include #include @@ -8,6 +9,28 @@ using namespace Mantid::API; using Mantid::PythonInterface::Registry::DataItemInterface; using namespace boost::python; +namespace { + +/// Create a peak via it's HKL value from a list or numpy array +void createPeakHKL(IPeaksWorkspace & self, const object& data) +{ + self.createPeakHKL(Mantid::PythonInterface::Converters(data)); +} + +/// Create a peak via it's QLab value from a list or numpy array +void createPeakQLab(IPeaksWorkspace & self, const object& data) +{ + self.createPeak(Mantid::PythonInterface::Converters(data)); +} + +/// Create a peak via it's QLab value from a list or numpy array +void createPeakQLabWithDistance(IPeaksWorkspace & self, const object& data, double detectorDistance) +{ + self.createPeak(Mantid::PythonInterface::Converters(data), distance); +} + +} + void export_IPeaksWorkspace() { // IPeaksWorkspace class @@ -16,7 +39,9 @@ void export_IPeaksWorkspace() .def("addPeak", &IPeaksWorkspace::addPeak, "Add a peak to the workspace") .def("removePeak", &IPeaksWorkspace::removePeak, "Remove a peak from the workspace") .def("getPeak", &IPeaksWorkspace::getPeakPtr, return_internal_reference<>(), "Returns a peak at the given index" ) - .def("createPeak", &IPeaksWorkspace::createPeak, return_internal_reference<>(), "Create a Peak and return it") + .def("createPeak", createPeakQLab, return_internal_reference<>(), "Create a Peak and return it from its coordinates in the QLab frame") + .def("createPeak", createPeakQLabWithDistance, return_internal_reference<>(), "Create a Peak and return it from its coordinates in the QLab frame, detector-sample distance explicitly provided") + .def("createPeakHKL", createPeakHKL, return_internal_reference<>(), "Create a Peak and return it from its coordinates in the HKL frame") .def("hasIntegratedPeaks", &IPeaksWorkspace::hasIntegratedPeaks, "Determine if the peaks have been integrated") .def("getRun", &IPeaksWorkspace::mutableRun, return_internal_reference<>(), "Return the Run object for this workspace") diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py index c41d65e9e72a..71dee292185b 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py @@ -51,7 +51,7 @@ def test_interface(self): # Peaks workspace will not be integrated by default. self.assertTrue(not pws.hasIntegratedPeaks()) - def test_peak_setQLab(self): + def test_peak_setQLabFrame(self): pws = WorkspaceCreationHelper.createPeaksWorkspace(1) p = pws.getPeak(0) try: @@ -64,6 +64,19 @@ def test_peak_setQLab(self): except Exception: self.fail("Tried setQLabFrame with one V3D argument and a double distance") + def test_peak_setQSampleFrame(self): + pws = WorkspaceCreationHelper.createPeaksWorkspace(1) + p = pws.getPeak(0) + try: + p.setQSampleFrame(V3D(1,1,1)) + except Exception: + self.fail("Tried setQSampleFrame with one V3D argument") + + try: + p.setQSampleFrame(V3D(1,1,1), 1) + except Exception: + self.fail("Tried setQSampleFrame with one V3D argument and a double distance") + From 9cac9f29e951cd3a2951705f74169ccbf6089514 Mon Sep 17 00:00:00 2001 From: Nick Draper Date: Fri, 13 Feb 2015 18:14:34 +0000 Subject: [PATCH 095/414] re #11091 mostly done, unit tests pass --- .../DataHandling/src/DownloadInstrument.cpp | 3 +- .../Kernel/inc/MantidKernel/InternetHelper.h | 49 ++++- .../Framework/Kernel/src/InternetHelper.cpp | 204 +++++++++++++++--- .../Kernel/test/InternetHelperTest.h | 69 ++++++ .../WorkflowAlgorithms/src/SendUsage.cpp | 8 +- 5 files changed, 291 insertions(+), 42 deletions(-) diff --git a/Code/Mantid/Framework/DataHandling/src/DownloadInstrument.cpp b/Code/Mantid/Framework/DataHandling/src/DownloadInstrument.cpp index 8fcaf7d739ad..2d4788b2b75d 100644 --- a/Code/Mantid/Framework/DataHandling/src/DownloadInstrument.cpp +++ b/Code/Mantid/Framework/DataHandling/src/DownloadInstrument.cpp @@ -349,7 +349,8 @@ int DownloadInstrument::doDownloadFile(const std::string &urlFile, const StringToStringMap &headers) { int retStatus = 0; InternetHelper inetHelper; - retStatus = inetHelper.downloadFile(urlFile, localFilePath, headers); + inetHelper.headers() = headers; + retStatus = inetHelper.downloadFile(urlFile, localFilePath); return retStatus; } diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h b/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h index d90c55c32bb9..7b349f5be947 100644 --- a/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h +++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h @@ -18,6 +18,8 @@ class HTTPClientSession; class HTTPResponse; // forward declaration class HTTPRequest; +// forward declaration +class HTMLForm; } } @@ -59,21 +61,44 @@ class MANTID_KERNEL_DLL InternetHelper { // Convenience typedef typedef std::map StringToStringMap; - virtual int - downloadFile(const std::string &urlFile, - const std::string &localFilePath = "", - const StringToStringMap &headers = StringToStringMap()); - virtual int - sendRequest(const std::string &url, std::ostream &responseStream, - const StringToStringMap &headers = StringToStringMap(), - const std::string &method = std::string(), - const std::string &body = std::string()); + //getters and setters + void setTimeout(int seconds); + int getTimeout(); + + void setMethod(const std::string& method); + const std::string& getMethod(); + + void setContentType(const std::string& contentType); + const std::string& getContentType(); + + void setContentLength(std::streamsize length); + std::streamsize getContentLength(); + + void setBody(const std::string& body); + void setBody(const std::stringstream& body); + void setBody(Poco::Net::HTMLForm& form); + const std::string getBody(); + + void addHeader(const std::string& key, const std::string& value); + void removeHeader (const std::string& key); + const std::string& getHeader (const std::string& key); + void clearHeaders(); + StringToStringMap& headers(); + void reset(); + + + //Proxy methods Kernel::ProxyInfo &getProxy(const std::string &url); void clearProxy(); void setProxy(const Kernel::ProxyInfo &proxy); - void setTimeout(int seconds); + //Execute call methods + virtual int + downloadFile(const std::string &urlFile, + const std::string &localFilePath = ""); + virtual int + sendRequest(const std::string &url, std::ostream &responseStream); protected: virtual int sendHTTPSRequest(const std::string &url, @@ -91,12 +116,14 @@ class MANTID_KERNEL_DLL InternetHelper { Poco::URI &uri, std::ostream &responseStream); int processRelocation(const Poco::Net::HTTPResponse &response, std::ostream &responseStream); + Kernel::ProxyInfo m_proxyInfo; bool m_isProxySet; int m_timeout; + std::streamsize m_contentLength; std::string m_method; std::string m_contentType; - std::string m_body; + std::stringstream m_body; StringToStringMap m_headers; Poco::Net::HTTPRequest *m_request; }; diff --git a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp index d55e4911f9dc..2da210836094 100644 --- a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp +++ b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp @@ -7,6 +7,7 @@ // Poco #include #include +#include #include #include #include @@ -72,9 +73,9 @@ bool isRelocated(const int response) { /** Constructor */ InternetHelper::InternetHelper() - : m_proxyInfo(), m_isProxySet(false), m_timeout(30), + : m_proxyInfo(), m_isProxySet(false), m_timeout(30), m_contentLength(0), m_method(HTTPRequest::HTTP_GET), m_contentType("application/json"), - m_request(NULL) {} + m_body(), m_request(NULL) {} //---------------------------------------------------------------------------------------------- /** Constructor @@ -82,7 +83,7 @@ InternetHelper::InternetHelper() InternetHelper::InternetHelper(const Kernel::ProxyInfo &proxy) : m_proxyInfo(proxy), m_isProxySet(true), m_timeout(30), m_method(HTTPRequest::HTTP_GET), m_contentType("application/json"), - m_request(NULL) {} + m_body(), m_request(NULL) {} //---------------------------------------------------------------------------------------------- /** Destructor @@ -103,15 +104,28 @@ void InternetHelper::setupProxyOnSession(HTTPClientSession &session, } void InternetHelper::createRequest(Poco::URI &uri) { + if (m_request != NULL) { + delete m_request; + } + m_request = new HTTPRequest(m_method, uri.getPathAndQuery(), HTTPMessage::HTTP_1_1); if (!m_contentType.empty()) { m_request->setContentType(m_contentType); } + m_request->set("User-Agent", "MANTID"); + if (m_contentLength > 0) { + m_request->setContentLength(m_contentLength); + } + for (auto itHeaders = m_headers.begin(); itHeaders != m_headers.end(); ++itHeaders) { m_request->set(itHeaders->first, itHeaders->second); + } + + if (m_method == "POST") { + m_request->setChunkedTransferEncoding(true); } } @@ -120,7 +134,6 @@ int InternetHelper::sendRequestAndProcess(HTTPClientSession &session, std::ostream &responseStream) { // create a request this->createRequest(uri); - m_request->setContentLength(m_body.length()); session.sendRequest(*m_request) << m_body; HTTPResponse res; @@ -162,28 +175,17 @@ int InternetHelper::processRelocation(const HTTPResponse &response, * @param body The request body to send. **/ int InternetHelper::sendRequest(const std::string &url, - std::ostream &responseStream, - const StringToStringMap &headers, - const std::string &method, - const std::string &body) { - // set instance variables from the input as appropriate - if (!method.empty()) { - m_method = method; - } - if (!headers.empty()) { - m_headers = headers; - } - if (!body.empty()) { - m_body = body; - } - + std::ostream &responseStream) { + // send the request Poco::URI uri(url); + int retval; if ((uri.getScheme() == "https") || (uri.getPort() == 443)) { - return sendHTTPSRequest(url, responseStream); + retval = sendHTTPSRequest(url, responseStream); } else { - return sendHTTPRequest(url, responseStream); + retval = sendHTTPRequest(url, responseStream); } + return retval; } /** Performs a request using http @@ -379,15 +381,14 @@ include in the request. behaviour. */ int InternetHelper::downloadFile(const std::string &urlFile, - const std::string &localFilePath, - const StringToStringMap &headers) { + const std::string &localFilePath) { int retStatus = 0; g_log.debug() << "DownloadFile : " << urlFile << " to file: " << localFilePath << std::endl; Poco::TemporaryFile tempFile; Poco::FileStream tempFileStream(tempFile.path()); - retStatus = sendRequest(urlFile, tempFileStream, headers); + retStatus = sendRequest(urlFile, tempFileStream); tempFileStream.close(); // if there have been no errors move it to the final location, and turn off @@ -403,5 +404,160 @@ int InternetHelper::downloadFile(const std::string &urlFile, **/ void InternetHelper::setTimeout(int seconds) { m_timeout = seconds; } + +/** Gets the timeout in seconds +* @returns The value in seconds for the timeout +**/ +int InternetHelper::getTimeout() { return m_timeout; } + +/** Sets the Method +* @param method A string of GET or POST, anything other than POST is considered GET +**/ +void InternetHelper::setMethod(const std::string& method) { + if (method == "POST") { + m_method = method; + } else { + m_method = "GET"; + } +} + +/** Gets the method +* @returns either "GET" or "POST" +**/ +const std::string& InternetHelper::getMethod() {return m_method; } + +/** Sets the Content Type +* @param contentType A string of the content type +**/ +void InternetHelper::setContentType(const std::string& contentType) { + m_contentType = contentType; +} + +/** Gets the Content Type +* @returns A string of the content type +**/ +const std::string& InternetHelper::getContentType() {return m_contentType; } + + + +/** Sets the content length +* @param length The content length in bytes +**/ +void InternetHelper::setContentLength(std::streamsize length) { m_contentLength = length; } + +/** Gets the content length +* @returns The content length in bytes +**/ +std::streamsize InternetHelper::getContentLength() { return m_contentLength; } + +/** Sets the body & content length for future requests, this will also +* set the method to POST is the body is not empty +* and GET if it is. +* @param body A string of the body +**/ +void InternetHelper::setBody(const std::string& body) { + //clear the old body + m_body.str("") ; + if (body.empty()) { + setMethod("GET"); + } else { + setMethod("POST"); + m_body << body; + } + setContentLength(body.size()); +} + +/** Sets the body & content length for future requests, this will also +* set the method to POST is the body is not empty +* and GET if it is. +* @param body A stringstream of the body +**/ +void InternetHelper::setBody(const std::stringstream& body) { + //clear the old body + m_body.str("") ; + //if empty + if (body.rdbuf()->in_avail() == 0) { + setMethod("GET"); + } else { + setMethod("POST"); + m_body << body.str(); + } + setContentLength(m_body.tellp()); +} + +/** Sets the body & content length for future requests, this will also +* set the method to POST is the body is not empty +* and GET if it is. +* @param body A HTMLform +**/ +void InternetHelper::setBody(Poco::Net::HTMLForm& form) { + + setMethod("POST"); + if (m_request == NULL) { + createRequest(Poco::URI("http://www.mantidproject.org")); + } + form.prepareSubmit(*m_request); + setContentType(m_request->getContentType()); + //clear the old body + m_body.str("") ; + + form.write(m_body); + setContentLength(m_body.tellp()); +} + + + +/** Gets the body set for future requests +* @returns A string of the content type +**/ +const std::string InternetHelper::getBody() {return m_body.str(); } + +void setBody(const std::string& body); + const std::string getBody(); + +/** Adds a header +* @param key The key to refer to the value +* @param value The value in seconds for the timeout +**/ +void InternetHelper::addHeader(const std::string& key, const std::string& value) { + m_headers.insert(std::pair(key,value)); +} + +/** Removes a header +* @param key The key to refer to the value +**/ +void InternetHelper::removeHeader (const std::string& key) { + m_headers.erase(key); +} + +/** Gets the value of a header +* @param key The key to refer to the value +* @returns the value as a string +**/ +const std::string& InternetHelper::getHeader (const std::string& key) { + return m_headers[key]; +} + +/** Clears all headers +**/ +void InternetHelper::clearHeaders() { m_headers.clear(); } + +/** Returns a reference to the headers map +**/ +std::map& InternetHelper::headers() { + return m_headers; +} + +/** Resets properties to defaults (except the proxy) +**/ +void InternetHelper::reset() { + m_headers.clear(); + m_timeout = 30; + m_body.str(""); + m_method = HTTPRequest::HTTP_GET; + m_contentType = "application/json"; + m_request = NULL ; +} + } // namespace Kernel } // namespace Mantid diff --git a/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h b/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h index 8ad8c31e512c..b07c1f69c978 100644 --- a/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h +++ b/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h @@ -109,6 +109,75 @@ class InternetHelperTest : public CxxTest::TestSuite { TS_ASSERT_EQUALS("HTTPS request succeeded", ss.str()); } + + void test_ContentType_GetSet() + { + MockedInternetHelper internetHelper; + TSM_ASSERT_EQUALS("Default content type is not application/json",internetHelper.getContentType(),"application/json"); + internetHelper.setContentType("test value"); + TSM_ASSERT_EQUALS("setContentType failed",internetHelper.getContentType(),"test value"); + } + + void test_Method_GetSet() + { + MockedInternetHelper internetHelper; + TSM_ASSERT_EQUALS("Default method is not GET",internetHelper.getMethod(),"GET"); + internetHelper.setMethod("POST"); + TSM_ASSERT_EQUALS("setMethod failed",internetHelper.getMethod(),"POST"); + } + + void test_Timeout_GetSet() + { + MockedInternetHelper internetHelper; + TSM_ASSERT_EQUALS("Default timeout is not 30",internetHelper.getTimeout(),30); + internetHelper.setTimeout(1); + TSM_ASSERT_EQUALS("setTimeout failed",internetHelper.getTimeout(),1); + } + + void test_Body_GetSet() + { + MockedInternetHelper internetHelper; + TSM_ASSERT_EQUALS("Default body is not empty",internetHelper.getBody(),""); + internetHelper.setBody("Test string"); + TSM_ASSERT_EQUALS("setBody failed",internetHelper.getBody(),"Test string"); + TSM_ASSERT_EQUALS("method is not POST",internetHelper.getMethod(),"POST"); + TSM_ASSERT_EQUALS("Contentlength is wrong",internetHelper.getContentLength(),11); + internetHelper.setBody(""); + TSM_ASSERT_EQUALS("setBody failed",internetHelper.getBody(),""); + TSM_ASSERT_EQUALS("method is not GET",internetHelper.getMethod(),"GET"); + TSM_ASSERT_EQUALS("Contentlength is wrong",internetHelper.getContentLength(),0); + } + + void test_BodyStream_GetSet() + { + MockedInternetHelper internetHelper; + std::stringstream ss; + ss << "Test string"; + TSM_ASSERT_EQUALS("Default body is not empty",internetHelper.getBody(),""); + internetHelper.setBody(ss); + TSM_ASSERT_EQUALS("setBody failed",internetHelper.getBody(),ss.str()); + TSM_ASSERT_EQUALS("method is not POST",internetHelper.getMethod(),"POST"); + TSM_ASSERT_EQUALS("Contentlength is wrong",internetHelper.getContentLength(),11); + ss.str(""); + internetHelper.setBody(ss); + TSM_ASSERT_EQUALS("setBody failed",internetHelper.getBody(),""); + TSM_ASSERT_EQUALS("method is not GET",internetHelper.getMethod(),"GET"); + TSM_ASSERT_EQUALS("Contentlength is wrong",internetHelper.getContentLength(),0); + } + + void test_Headers_GetSet() + { + MockedInternetHelper internetHelper; + TSM_ASSERT_EQUALS("Default headers are not empty",internetHelper.headers().size(),0); + internetHelper.addHeader("Test","value"); + internetHelper.addHeader("Test2","value2"); + TSM_ASSERT_EQUALS("addHeader failed",internetHelper.getHeader("Test"),"value"); + TSM_ASSERT_EQUALS("addHeader failed",internetHelper.getHeader("Test2"),"value2"); + internetHelper.removeHeader("Test"); + TSM_ASSERT_EQUALS("Remove failed",internetHelper.headers().size(),1); + internetHelper.clearHeaders(); + TSM_ASSERT_EQUALS("Clear failed",internetHelper.headers().size(),0); + } }; #endif /* MANTID_KERNEL_INTERNETSERVICETEST_H_ */ diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/src/SendUsage.cpp b/Code/Mantid/Framework/WorkflowAlgorithms/src/SendUsage.cpp index b5ee9826cf2d..ae6efa60dc60 100644 --- a/Code/Mantid/Framework/WorkflowAlgorithms/src/SendUsage.cpp +++ b/Code/Mantid/Framework/WorkflowAlgorithms/src/SendUsage.cpp @@ -6,7 +6,6 @@ #include "MantidKernel/InternetHelper.h" #include "MantidKernel/MantidVersion.h" #include "MantidKernel/ParaViewVersion.h" -#include #include namespace Mantid { @@ -35,9 +34,6 @@ const int STATUS_DEFAULT = -1; const std::string URL("http://reports.mantidproject.org/api/usage"); // const std::string URL("http://127.0.0.1:8000/api/usage"); // dev location -/// The string for post method -const std::string POST(Poco::Net::HTTPRequest::HTTP_POST); - /// @returns true if Kernel::ConfigService says the option is on. bool doSend() { // create a variable to pass in @@ -121,10 +117,10 @@ void SendUsage::sendReport(const std::string &json) { int status = STATUS_DEFAULT; try { - std::map htmlHeaders; Kernel::InternetHelper helper; std::stringstream responseStream; - status = helper.sendRequest(URL, responseStream, htmlHeaders, POST, json); + helper.setBody(json); + status = helper.sendRequest(URL, responseStream); g_log.debug() << "Call to \"" << URL << "\" responded with " << status << "\n" << responseStream.str() << "\n"; } From 308aa94bd1eb0d0e9b148dd0fc8a4a947133ba3f Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 14 Feb 2015 18:28:22 +0000 Subject: [PATCH 096/414] fix coverity issue 1075920 (null deref), re #11062 --- Code/Mantid/Framework/Algorithms/src/Integration.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/src/Integration.cpp b/Code/Mantid/Framework/Algorithms/src/Integration.cpp index 1cb9afa56820..03a00b76cde2 100644 --- a/Code/Mantid/Framework/Algorithms/src/Integration.cpp +++ b/Code/Mantid/Framework/Algorithms/src/Integration.cpp @@ -121,11 +121,13 @@ void Integration::exec() { if (axisIsText) { Mantid::API::TextAxis *newAxis = dynamic_cast(outputWorkspace->getAxis(1)); - newAxis->setLabel(outWI, localworkspace->getAxis(1)->label(i)); + if (newAxis) + newAxis->setLabel(outWI, localworkspace->getAxis(1)->label(i)); } else if (axisIsNumeric) { Mantid::API::NumericAxis *newAxis = dynamic_cast(outputWorkspace->getAxis(1)); - newAxis->setValue(outWI, (*(localworkspace->getAxis(1)))(i)); + if (newAxis) + newAxis->setValue(outWI, (*(localworkspace->getAxis(1)))(i)); } // This is the output From 7a4bd08cab5dd49cac4fa654059ae8f05d19a340 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 14 Feb 2015 18:29:14 +0000 Subject: [PATCH 097/414] fix coverity issues 1075928,29,30 (null derefs), re #11062 --- .../Algorithms/src/CreateWorkspace.cpp | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/src/CreateWorkspace.cpp b/Code/Mantid/Framework/Algorithms/src/CreateWorkspace.cpp index 34109440a281..de34cb087ff5 100644 --- a/Code/Mantid/Framework/Algorithms/src/CreateWorkspace.cpp +++ b/Code/Mantid/Framework/Algorithms/src/CreateWorkspace.cpp @@ -86,12 +86,23 @@ void CreateWorkspace::exec() { const Property *const dataXprop = getProperty("DataX"); const Property *const dataYprop = getProperty("DataY"); const Property *const dataEprop = getProperty("DataE"); - const std::vector &dataX = - *dynamic_cast *>(dataXprop); - const std::vector &dataY = - *dynamic_cast *>(dataYprop); - const std::vector &dataE = - *dynamic_cast *>(dataEprop); + + const ArrayProperty *pCheck = NULL; + + pCheck = dynamic_cast *>(dataXprop); + if (!pCheck) + throw std::invalid_argument("DataX cannot be casted to a double vector"); + const std::vector &dataX = *pCheck; + + pCheck = dynamic_cast *>(dataYprop); + if (!pCheck) + throw std::invalid_argument("DataY cannot be casted to a double vector"); + const std::vector &dataY = *pCheck; + + pCheck = dynamic_cast *>(dataEprop); + if (!pCheck) + throw std::invalid_argument("DataE cannot be casted to a double vector"); + const std::vector &dataE = *pCheck; const int nSpec = getProperty("NSpec"); const std::string xUnit = getProperty("UnitX"); From f260ce47f30f7a980bc52b87ac6d8029c82ca1a5 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 14 Feb 2015 18:30:03 +0000 Subject: [PATCH 098/414] fix coverity issue 1075935 (null deref), re #11062 --- Code/Mantid/Framework/API/src/PropertyNexus.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/API/src/PropertyNexus.cpp b/Code/Mantid/Framework/API/src/PropertyNexus.cpp index 1f2aac69306c..0290d469289b 100644 --- a/Code/Mantid/Framework/API/src/PropertyNexus.cpp +++ b/Code/Mantid/Framework/API/src/PropertyNexus.cpp @@ -193,7 +193,9 @@ Property *loadProperty(::NeXus::File *file, const std::string &group) { file->closeData(); file->closeGroup(); // add units - retVal->setUnits(unitsStr); + if (retVal) + retVal->setUnits(unitsStr); + return retVal; } From c35eb67b3fb3832f61bc458bfdd458c3a2a4b8da Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 14 Feb 2015 18:30:40 +0000 Subject: [PATCH 099/414] fix coverity issue 1075936 (null deref), re #11062 --- Code/Mantid/Framework/API/src/Algorithm.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/API/src/Algorithm.cpp b/Code/Mantid/Framework/API/src/Algorithm.cpp index e47704b9bc2c..4a41e7e1182d 100644 --- a/Code/Mantid/Framework/API/src/Algorithm.cpp +++ b/Code/Mantid/Framework/API/src/Algorithm.cpp @@ -1164,7 +1164,7 @@ bool Algorithm::checkGroups() { // Workspace groups are NOT returned by IWP->getWorkspace() most of the time // because WorkspaceProperty is templated by // and WorkspaceGroup does not subclass - if (!wsGroup && !prop->value().empty()) { + if (!wsGroup && prop && !prop->value().empty()) { // So try to use the name in the AnalysisDataService try { wsGroup = AnalysisDataService::Instance().retrieveWS( From fd65c2527a6314b0ee8e672f071778b90964ed7f Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 14 Feb 2015 20:15:02 +0000 Subject: [PATCH 100/414] fix coverity issue 1076307 (null deref), re #11062 --- .../Framework/DataHandling/src/LoadInstrument.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/Framework/DataHandling/src/LoadInstrument.cpp b/Code/Mantid/Framework/DataHandling/src/LoadInstrument.cpp index e6c1d39181ed..943e218a753f 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadInstrument.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadInstrument.cpp @@ -122,9 +122,14 @@ void LoadInstrument::exec() { // Initialize the parser. Avoid copying the xmltext out of the property // here. - parser.initialize( - m_filename, m_instName, - *dynamic_cast *>(InstrumentXML)); + const PropertyWithValue *xml = + dynamic_cast *>(InstrumentXML); + if (xml) { + parser.initialize(m_filename, m_instName, *xml); + } else { + throw std::invalid_argument("The instrument XML passed cannot be " + "casted to a standard string."); + } } // otherwise we need either Filename or InstrumentName to be set else { From ee7edf4a3daeafa2a751a034111e22ecd3ae4374 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 14 Feb 2015 20:15:35 +0000 Subject: [PATCH 101/414] fix coverity issues 1076305,6 (null deref), re #11062 --- .../Framework/DataHandling/src/ProcessDasNexusLog.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/DataHandling/src/ProcessDasNexusLog.cpp b/Code/Mantid/Framework/DataHandling/src/ProcessDasNexusLog.cpp index f3a74c85f6b8..9ce0da04e849 100644 --- a/Code/Mantid/Framework/DataHandling/src/ProcessDasNexusLog.cpp +++ b/Code/Mantid/Framework/DataHandling/src/ProcessDasNexusLog.cpp @@ -388,7 +388,9 @@ void ProcessDasNexusLog::convertToAbsoluteTime( Kernel::Property *log = ws->run().getProperty(logname); Kernel::TimeSeriesProperty *tslog = dynamic_cast *>(log); - std::vector times = tslog->timesAsVector(); + std::vector times; + if (tslog) + times = tslog->timesAsVector(); std::vector values = tslog->valuesAsVector(); // 2. Get converted @@ -445,7 +447,9 @@ void ProcessDasNexusLog::writeLogtoFile(API::MatrixWorkspace_sptr ws, Kernel::Property *log = ws->run().getProperty(logname); Kernel::TimeSeriesProperty *tslog = dynamic_cast *>(log); - std::vector times = tslog->timesAsVector(); + std::vector times; + if (tslog) + tslog->timesAsVector(); std::vector values = tslog->valuesAsVector(); // 2. Write out From 7387264c151faaa7434611eadf5e6db85ed5535a Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 14 Feb 2015 20:16:27 +0000 Subject: [PATCH 102/414] fix coverity issue 1076308 (null deref), re #11062 --- Code/Mantid/Framework/DataHandling/src/LoadNexusLogs.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/DataHandling/src/LoadNexusLogs.cpp b/Code/Mantid/Framework/DataHandling/src/LoadNexusLogs.cpp index 868805dea0ac..37f2e2131419 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadNexusLogs.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadNexusLogs.cpp @@ -173,7 +173,9 @@ void LoadNexusLogs::exec() { std::vector ptime; pval.reserve(event_frame_number.size()); ptime.reserve(event_frame_number.size()); - std::vector plogt = plog->timesAsVector(); + std::vector plogt; + if (plog) + plogt = plog->timesAsVector(); std::vector plogv = plog->valuesAsVector(); for (size_t i = 0; i < event_frame_number.size(); ++i) { ptime.push_back(plogt[event_frame_number[i]]); From 48820939de7665513f427b91ecadbffdceb02df7 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 14 Feb 2015 20:22:55 +0000 Subject: [PATCH 103/414] fix coverity issues 1076296, 98 (null deref), re #11062 --- .../Geometry/src/Instrument/Detector.cpp | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/Code/Mantid/Framework/Geometry/src/Instrument/Detector.cpp b/Code/Mantid/Framework/Geometry/src/Instrument/Detector.cpp index 545d6db6433f..3cd427268ece 100644 --- a/Code/Mantid/Framework/Geometry/src/Instrument/Detector.cpp +++ b/Code/Mantid/Framework/Geometry/src/Instrument/Detector.cpp @@ -45,10 +45,14 @@ Detector::~Detector() {} * @returns the detector id */ detid_t Detector::getID() const { - if (m_map) - return dynamic_cast(m_base)->getID(); - else - return m_id; + if (m_map) { + const Detector *d = dynamic_cast(m_base); + if (d) { + return d->getID(); + } + } + + return m_id; } /// Get the distance between the detector and another component @@ -137,10 +141,14 @@ bool Detector::isMasked() const { /// Is the detector a monitor? ///@return true if it is a monitor bool Detector::isMonitor() const { - if (m_map) - return dynamic_cast(m_base)->isMonitor(); - else - return m_isMonitor; + if (m_map) { + const Detector *d = dynamic_cast(m_base); + if (d) { + return d->isMonitor(); + } + } + + return m_isMonitor; } /** Sets the flag for whether this detector object is a monitor From 98947f77585af4e0d38012899a9233c4edcb8b54 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 14 Feb 2015 20:24:00 +0000 Subject: [PATCH 104/414] fix coverity issues 1076313 & 1231789 (null derefs), re #11062 --- Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp b/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp index b2bd92871d58..6588f6d4bc83 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp @@ -2153,7 +2153,8 @@ void LoadEventNexus::deleteBanks(API::MatrixWorkspace_sptr workspace, for (int row = 0; row < static_cast(grandchildren.size()); row++) { Detector *d = dynamic_cast( const_cast(grandchildren[row].get())); - inst->removeDetector(d); + if (d) + inst->removeDetector(d); } } IComponent *comp = dynamic_cast(detList[i].get()); @@ -2823,7 +2824,9 @@ LoadEventNexus::runLoadNexusLogs(const std::string &nexusfilename, Kernel::TimeSeriesProperty *log = dynamic_cast *>( localWorkspace->mutableRun().getProperty("proton_charge")); - const std::vector temp = log->timesAsVector(); + std::vector temp; + if (log) + temp = log->timesAsVector(); // if (returnpulsetimes) out = new BankPulseTimes(temp); if (returnpulsetimes) out = boost::make_shared(temp); From 0d10ba2d78dc6f88df3bc71a4dcd88c03c64fb8a Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Sun, 15 Feb 2015 08:19:19 +0000 Subject: [PATCH 105/414] refs #11056. Setup for new AddPeaksHKL algorithm --- Code/Mantid/Framework/API/test/MockObjects.h | 4 +- Code/Mantid/Framework/Crystal/CMakeLists.txt | 3 + .../Crystal/inc/MantidCrystal/AddPeakHKL.h | 56 ++++++++++++++++ .../Framework/Crystal/src/AddPeakHKL.cpp | 65 +++++++++++++++++++ .../Framework/Crystal/src/PredictPeaks.cpp | 2 +- .../Framework/Crystal/test/AddPeakHKLTest.h | 61 +++++++++++++++++ .../DataObjects/src/PeaksWorkspace.cpp | 7 ++ .../mantid/api/src/Exports/IPeak.cpp | 2 +- .../api/src/Exports/IPeaksWorkspace.cpp | 20 +++--- .../python/mantid/api/IPeaksWorkspaceTest.py | 16 ++++- .../src/WorkspaceCreationHelper.cpp | 2 + .../docs/source/algorithms/AddPeakHKL-v1.rst | 44 +++++++++++++ 12 files changed, 266 insertions(+), 16 deletions(-) create mode 100644 Code/Mantid/Framework/Crystal/inc/MantidCrystal/AddPeakHKL.h create mode 100644 Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp create mode 100644 Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h create mode 100644 Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst diff --git a/Code/Mantid/Framework/API/test/MockObjects.h b/Code/Mantid/Framework/API/test/MockObjects.h index a87670dc88ec..591c063b6e13 100644 --- a/Code/Mantid/Framework/API/test/MockObjects.h +++ b/Code/Mantid/Framework/API/test/MockObjects.h @@ -103,9 +103,9 @@ namespace MOCK_METHOD0(findDetector, bool()); MOCK_METHOD2(setQSampleFrame, - void(Mantid::Kernel::V3D QSampleFrame, double detectorDistance)); + void(Mantid::Kernel::V3D QSampleFrame, boost::optional detectorDistance)); MOCK_METHOD2(setQLabFrame, - void(Mantid::Kernel::V3D QLabFrame, double detectorDistance)); + void(Mantid::Kernel::V3D QLabFrame, boost::optional detectorDistance)); MOCK_METHOD1(setWavelength, void(double wavelength)); MOCK_CONST_METHOD0(getWavelength, diff --git a/Code/Mantid/Framework/Crystal/CMakeLists.txt b/Code/Mantid/Framework/Crystal/CMakeLists.txt index 5498af2dfec0..24d7be132d25 100644 --- a/Code/Mantid/Framework/Crystal/CMakeLists.txt +++ b/Code/Mantid/Framework/Crystal/CMakeLists.txt @@ -1,5 +1,6 @@ set ( SRC_FILES + src/AddPeakHKL.cpp src/AnvredCorrection.cpp src/CalculatePeaksHKL.cpp src/CalculateUMatrix.cpp @@ -69,6 +70,7 @@ set ( SRC_FILES set ( SRC_UNITY_IGNORE_FILES ) set ( INC_FILES + inc/MantidCrystal/AddPeakHKL.h inc/MantidCrystal/AnvredCorrection.h inc/MantidCrystal/BackgroundStrategy.h inc/MantidCrystal/CalculatePeaksHKL.h @@ -140,6 +142,7 @@ set ( INC_FILES ) set ( TEST_FILES + AddPeakHKLTest.h AnvredCorrectionTest.h CalculatePeaksHKLTest.h CalculateUMatrixTest.h diff --git a/Code/Mantid/Framework/Crystal/inc/MantidCrystal/AddPeakHKL.h b/Code/Mantid/Framework/Crystal/inc/MantidCrystal/AddPeakHKL.h new file mode 100644 index 000000000000..2762b8122eae --- /dev/null +++ b/Code/Mantid/Framework/Crystal/inc/MantidCrystal/AddPeakHKL.h @@ -0,0 +1,56 @@ +#ifndef MANTID_CRYSTAL_ADDPEAKHKL_H_ +#define MANTID_CRYSTAL_ADDPEAKHKL_H_ + +#include "MantidKernel/System.h" +#include "MantidAPI/Algorithm.h" + +namespace Mantid +{ +namespace Crystal +{ + + /** AddPeakHKL : TODO: DESCRIPTION + + Copyright © 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source + + This file is part of Mantid. + + Mantid is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + Mantid is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + File change history is stored at: + Code Documentation is available at: + */ + class DLLExport AddPeakHKL : public API::Algorithm + { + public: + AddPeakHKL(); + virtual ~AddPeakHKL(); + + virtual const std::string name() const; + virtual int version() const; + virtual const std::string category() const; + virtual const std::string summary() const; + + private: + void init(); + void exec(); + + + }; + + +} // namespace Crystal +} // namespace Mantid + +#endif /* MANTID_CRYSTAL_ADDPEAKHKL_H_ */ \ No newline at end of file diff --git a/Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp b/Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp new file mode 100644 index 000000000000..382354fdb9a6 --- /dev/null +++ b/Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp @@ -0,0 +1,65 @@ +#include "MantidCrystal/AddPeakHKL.h" + +namespace Mantid +{ +namespace Crystal +{ + + using Mantid::Kernel::Direction; + using Mantid::API::WorkspaceProperty; + + // Register the algorithm into the AlgorithmFactory + DECLARE_ALGORITHM(AddPeakHKL) + + + + //---------------------------------------------------------------------------------------------- + /** Constructor + */ + AddPeakHKL::AddPeakHKL() + { + } + + //---------------------------------------------------------------------------------------------- + /** Destructor + */ + AddPeakHKL::~AddPeakHKL() + { + } + + + //---------------------------------------------------------------------------------------------- + + /// Algorithms name for identification. @see Algorithm::name + const std::string AddPeakHKL::name() const { return "AddPeakHKL"; } + + /// Algorithm's version for identification. @see Algorithm::version + int AddPeakHKL::version() const { return 1;}; + + /// Algorithm's category for identification. @see Algorithm::category + const std::string AddPeakHKL::category() const { return TODO: FILL IN A CATEGORY;} + + /// Algorithm's summary for use in the GUI and help. @see Algorithm::summary + const std::string AddPeakHKL::summary() const { return TODO: FILL IN A SUMMARY;}; + + //---------------------------------------------------------------------------------------------- + /** Initialize the algorithm's properties. + */ + void AddPeakHKL::init() + { + declareProperty(new WorkspaceProperty<>("InputWorkspace","",Direction::Input), "An input workspace."); + declareProperty(new WorkspaceProperty<>("OutputWorkspace","",Direction::Output), "An output workspace."); + } + + //---------------------------------------------------------------------------------------------- + /** Execute the algorithm. + */ + void AddPeakHKL::exec() + { + // TODO Auto-generated execute stub + } + + + +} // namespace Crystal +} // namespace Mantid \ No newline at end of file diff --git a/Code/Mantid/Framework/Crystal/src/PredictPeaks.cpp b/Code/Mantid/Framework/Crystal/src/PredictPeaks.cpp index 541403979d91..ba77553c1c38 100644 --- a/Code/Mantid/Framework/Crystal/src/PredictPeaks.cpp +++ b/Code/Mantid/Framework/Crystal/src/PredictPeaks.cpp @@ -145,7 +145,7 @@ void PredictPeaks::doHKL(const double h, const double k, const double l, PARALLEL_CRITICAL(PredictPeaks_numInRange) { numInRange++; } // Create the peak using the Q in the lab framewith all its info: - Peak p(inst, q); + Peak p(inst, q, boost::optional()); if (p.findDetector()) { // Only add peaks that hit the detector p.setGoniometerMatrix(gonio); diff --git a/Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h b/Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h new file mode 100644 index 000000000000..c1bbe8f084d1 --- /dev/null +++ b/Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h @@ -0,0 +1,61 @@ +#ifndef MANTID_CRYSTAL_ADDPEAKHKLTEST_H_ +#define MANTID_CRYSTAL_ADDPEAKHKLTEST_H_ + +#include + +#include "MantidCrystal/AddPeakHKL.h" + +using Mantid::Crystal::AddPeakHKL; +using namespace Mantid::API; + +class AddPeakHKLTest : public CxxTest::TestSuite +{ +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static AddPeakHKLTest *createSuite() { return new AddPeakHKLTest(); } + static void destroySuite( AddPeakHKLTest *suite ) { delete suite; } + + + void test_Init() + { + AddPeakHKL alg; + TS_ASSERT_THROWS_NOTHING( alg.initialize() ) + TS_ASSERT( alg.isInitialized() ) + } + + void test_exec() + { + // Name of the output workspace. + std::string outWSName("AddPeakHKLTest_OutputWS"); + + AddPeakHKL alg; + TS_ASSERT_THROWS_NOTHING( alg.initialize() ) + TS_ASSERT( alg.isInitialized() ) + TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("REPLACE_PROPERTY_NAME_HERE!!!!", "value") ); + TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("OutputWorkspace", outWSName) ); + TS_ASSERT_THROWS_NOTHING( alg.execute(); ); + TS_ASSERT( alg.isExecuted() ); + + // Retrieve the workspace from data service. TODO: Change to your desired type + Workspace_sptr ws; + TS_ASSERT_THROWS_NOTHING( ws = AnalysisDataService::Instance().retrieveWS(outWSName) ); + TS_ASSERT(ws); + if (!ws) return; + + // TODO: Check the results + + // Remove workspace from the data service. + AnalysisDataService::Instance().remove(outWSName); + } + + void test_Something() + { + TSM_ASSERT( "You forgot to write a test!", 0); + } + + +}; + + +#endif /* MANTID_CRYSTAL_ADDPEAKHKLTEST_H_ */ \ No newline at end of file diff --git a/Code/Mantid/Framework/DataObjects/src/PeaksWorkspace.cpp b/Code/Mantid/Framework/DataObjects/src/PeaksWorkspace.cpp index 93ee5c6577c9..83aabf18e3fd 100644 --- a/Code/Mantid/Framework/DataObjects/src/PeaksWorkspace.cpp +++ b/Code/Mantid/Framework/DataObjects/src/PeaksWorkspace.cpp @@ -397,6 +397,10 @@ PeaksWorkspace::peakInfo(Kernel::V3D qFrame, bool labCoords) const { */ Peak *PeaksWorkspace::createPeakHKL(V3D HKL) const { + /* + The following allows us to add peaks where we have a single UB to work from. + */ + Geometry::OrientedLattice lattice = this->sample().getOrientedLattice(); Geometry::Goniometer goniometer = this->run().getGoniometer(); @@ -412,6 +416,9 @@ Peak *PeaksWorkspace::createPeakHKL(V3D HKL) const // Set the goniometer peak->setGoniometerMatrix(goniometer.getR()); + // Take the run number from this + peak->setRunNumber(this->getRunNumber()); + return peak; } diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp index 7d2623a13ef3..0d6e83ecca35 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp @@ -50,7 +50,7 @@ void export_IPeak() .def("setQLabFrame", (void (IPeak::*)(Mantid::Kernel::V3D))&IPeak::setQLabFrame, "Set the peak using the peak's position in reciprocal space, in the lab frame.") .def("setQLabFrame", setQLabFrame, "Set the peak using the peak's position in reciprocal space, in the lab frame. Detector distance explicitly supplied.") // two argument overload .def("setQSampleFrame", (void (IPeak::*)(Mantid::Kernel::V3D))&IPeak::setQSampleFrame, "Set the peak using the peak's position in reciprocal space, in the sample frame.") - .def("setQSampleFrame", &IPeak::setQSampleFrame, "Set the peak using the peak's position in reciprocal space, in the sample frame.") + .def("setQSampleFrame", setQSampleFrame, "Set the peak using the peak's position in reciprocal space, in the sample frame.") .def("setWavelength", &IPeak::setWavelength, "Set the incident wavelength of the neutron. Calculates the energy from this assuming elastic scattering.") .def("getWavelength", &IPeak::getWavelength, "Return the incident wavelength") .def("getScattering", &IPeak::getScattering, "Calculate the scattering angle of the peak") diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp index 2b8f12e0975f..965bf50050c3 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp @@ -4,6 +4,8 @@ #include "MantidPythonInterface/kernel/Converters/PyObjectToV3D.h" #include #include +#include +#include using namespace Mantid::API; using Mantid::PythonInterface::Registry::DataItemInterface; @@ -12,21 +14,21 @@ using namespace boost::python; namespace { /// Create a peak via it's HKL value from a list or numpy array -void createPeakHKL(IPeaksWorkspace & self, const object& data) +IPeak* createPeakHKL(IPeaksWorkspace & self, const object& data) { - self.createPeakHKL(Mantid::PythonInterface::Converters(data)); + return self.createPeakHKL(Mantid::PythonInterface::Converters::PyObjectToV3D(data)()); } /// Create a peak via it's QLab value from a list or numpy array -void createPeakQLab(IPeaksWorkspace & self, const object& data) +IPeak* createPeakQLab(IPeaksWorkspace & self, const object& data) { - self.createPeak(Mantid::PythonInterface::Converters(data)); + return self.createPeak(Mantid::PythonInterface::Converters::PyObjectToV3D(data)(), boost::optional()); } /// Create a peak via it's QLab value from a list or numpy array -void createPeakQLabWithDistance(IPeaksWorkspace & self, const object& data, double detectorDistance) +IPeak* createPeakQLabWithDistance(IPeaksWorkspace & self, const object& data, double detectorDistance) { - self.createPeak(Mantid::PythonInterface::Converters(data), distance); + return self.createPeak(Mantid::PythonInterface::Converters::PyObjectToV3D(data)(), detectorDistance); } } @@ -39,9 +41,9 @@ void export_IPeaksWorkspace() .def("addPeak", &IPeaksWorkspace::addPeak, "Add a peak to the workspace") .def("removePeak", &IPeaksWorkspace::removePeak, "Remove a peak from the workspace") .def("getPeak", &IPeaksWorkspace::getPeakPtr, return_internal_reference<>(), "Returns a peak at the given index" ) - .def("createPeak", createPeakQLab, return_internal_reference<>(), "Create a Peak and return it from its coordinates in the QLab frame") - .def("createPeak", createPeakQLabWithDistance, return_internal_reference<>(), "Create a Peak and return it from its coordinates in the QLab frame, detector-sample distance explicitly provided") - .def("createPeakHKL", createPeakHKL, return_internal_reference<>(), "Create a Peak and return it from its coordinates in the HKL frame") + .def("createPeak", createPeakQLab, return_value_policy(), "Create a Peak and return it from its coordinates in the QLab frame") + .def("createPeak", createPeakQLabWithDistance, return_value_policy(), "Create a Peak and return it from its coordinates in the QLab frame, detector-sample distance explicitly provided") + .def("createPeakHKL", createPeakHKL, return_value_policy(), "Create a Peak and return it from its coordinates in the HKL frame") .def("hasIntegratedPeaks", &IPeaksWorkspace::hasIntegratedPeaks, "Determine if the peaks have been integrated") .def("getRun", &IPeaksWorkspace::mutableRun, return_internal_reference<>(), "Return the Run object for this workspace") diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py index 71dee292185b..d8afffeba711 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py @@ -1,7 +1,8 @@ import unittest from testhelpers import run_algorithm, WorkspaceCreationHelper from mantid.kernel import V3D -from mantid.api import IPeaksWorkspace +from mantid.geometry import OrientedLattice +from mantid.api import IPeaksWorkspace, IPeak class IPeaksWorkspaceTest(unittest.TestCase): """ @@ -38,6 +39,7 @@ def test_interface(self): # Create a new peak at some Q in the lab frame qlab = V3D(1,2,3) p = pws.createPeak(qlab, 1.54) + p.getQLabFrame() self.assertAlmostEquals( p.getQLabFrame().X(), 1.0, 3) # Now try to add the peak back @@ -50,7 +52,15 @@ def test_interface(self): # Peaks workspace will not be integrated by default. self.assertTrue(not pws.hasIntegratedPeaks()) - + + def test_createPeakHKL(self): + pws = WorkspaceCreationHelper.createPeaksWorkspace(0) + lattice = pws.mutableSample().getOrientedLattice() + + # Simple test that the creational method is exposed + p = pws.createPeakHKL([1,1,1]) + self.assertTrue(IPeak != None) + def test_peak_setQLabFrame(self): pws = WorkspaceCreationHelper.createPeaksWorkspace(1) p = pws.getPeak(0) @@ -64,7 +74,7 @@ def test_peak_setQLabFrame(self): except Exception: self.fail("Tried setQLabFrame with one V3D argument and a double distance") - def test_peak_setQSampleFrame(self): + def test_peak_setQSampleFrame(self): pws = WorkspaceCreationHelper.createPeaksWorkspace(1) p = pws.getPeak(0) try: diff --git a/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp b/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp index 9e2b671e577f..0005f3da7cee 100644 --- a/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp +++ b/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp @@ -1193,6 +1193,8 @@ createPeaksWorkspace(const int numPeaks) { peaksWS->addPeak(peak); } + Mantid::Geometry::OrientedLattice lattice; + peaksWS->mutableSample().setOrientedLattice(&lattice); return peaksWS; } diff --git a/Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst b/Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst new file mode 100644 index 000000000000..3ac2fb16b715 --- /dev/null +++ b/Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst @@ -0,0 +1,44 @@ + +.. algorithm:: + +.. summary:: + +.. alias:: + +.. properties:: + +Description +----------- + +TODO: Enter a full rst-markup description of your algorithm here. + + +Usage +----- +.. Try not to use files in your examples, + but if you cannot avoid it then the (small) files must be added to + autotestdata\UsageData and the following tag unindented + .. include:: ../usagedata-note.txt + +**Example - AddPeakHKL** + +.. testcode:: AddPeakHKLExample + + # Create a host workspace + ws = CreateWorkspace(DataX=range(0,3), DataY=(0,2)) + or + ws = CreateSampleWorkspace() + + wsOut = AddPeakHKL() + + # Print the result + print "The output workspace has %i spectra" % wsOut.getNumberHistograms() + +Output: + +.. testoutput:: AddPeakHKLExample + + The output workspace has ?? spectra + +.. categories:: + From 5c96dae1ac54cac86671b32e471c8ec2ae8ba81c Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Sun, 15 Feb 2015 08:28:09 +0000 Subject: [PATCH 106/414] Alter the mantidinstaller script to be able to run standalone. It already contains the logic to install/uninstall Mantid so we don't want to duplicate it for the Windows build script Refs #10870 --- .../SystemTests/scripts/mantidinstaller.py | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py b/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py index f78094738b9d..e365ed240559 100644 --- a/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py +++ b/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py @@ -23,6 +23,8 @@ def stop(installer): def log(txt): ''' Write text to the script log file ''' + if scriptLog is None: + return if txt and len(txt) > 0: scriptLog.write(txt) if not txt.endswith('\n'): @@ -242,3 +244,32 @@ def do_install(self): def do_uninstall(self): run('sudo rm -fr /Applications/MantidPlot.app/') + +#------------------------------------------------------------------------------- +# Main +#------------------------------------------------------------------------------- +# If called as a standalone script then this can be used to install/uninstall +# Mantid +if __name__ == "__main__": + import optparse + parser = optparse.OptionParser("Usage: %prog ", + description="Commands available: install, uninstall") + (options, args) = parser.parse_args() + # All arguments are required + if len(args) != 2: + parser.print_help() + sys.exit(1) + + command, package_dir = args[0], args[1] + package_dir = os.path.abspath(package_dir) + print package_dir + installer = get_installer(package_dir) + if command.lower() == "install": + print "Installing package '%s'" % installer.mantidInstaller + installer.install() + elif command.lower() == "uninstall": + print "Removing package '%s'" % installer.mantidInstaller + installer.uninstall() + else: + raise RuntimeError("Invalid command '%s'. Options are: install, uninstall" % command) + From 2c544868a426d78d9b8f331f93fb4705db6af5f6 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Sun, 15 Feb 2015 11:20:17 +0000 Subject: [PATCH 107/414] Merge parts of script that deal with the clean build Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript b/Code/Mantid/Build/Jenkins/buildscript index 2558d3ecbcff..6a4ffd903096 100755 --- a/Code/Mantid/Build/Jenkins/buildscript +++ b/Code/Mantid/Build/Jenkins/buildscript @@ -86,14 +86,6 @@ if [[ ${JOB_NAME} == *pull_requests* ]]; then BUILDPKG=true fi -############################################################################### -# Clean build directory if required -############################################################################### -if [[ "$CLEANBUILD" == true ]]; then - # Removing the build directory entirely guarantees a completely clean build - rm -rf $WORKSPACE/build -fi - ############################################################################### # Packaging options ############################################################################### @@ -115,8 +107,11 @@ if [[ "$BUILDPKG" == true ]]; then fi ############################################################################### -# Create the build directory if it doesn't exist +# Setup the build directory ############################################################################### +if [[ "$CLEANBUILD" == true ]]; then + rm -rf $WORKSPACE/build +fi [ -d $WORKSPACE/build ] || mkdir $WORKSPACE/build cd $WORKSPACE/build From 007bf35428c070070286297c4aa4c0d45f71bd1c Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Sun, 15 Feb 2015 11:22:06 +0000 Subject: [PATCH 108/414] Add documentation tests to Windows pull request build Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript.bat | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Code/Mantid/Build/Jenkins/buildscript.bat b/Code/Mantid/Build/Jenkins/buildscript.bat index bdc52542d22c..b260bb128654 100755 --- a/Code/Mantid/Build/Jenkins/buildscript.bat +++ b/Code/Mantid/Build/Jenkins/buildscript.bat @@ -110,3 +110,21 @@ if "%BUILDPKG%" EQU "yes" ( ::if ERRORLEVEL 1 exit /B %ERRORLEVEL% cpack -C %BUILD_CONFIG% --config CPackConfig.cmake ) + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Run the doc tests when doing a pull request build. Run from a package +:: from a package to have at least one Linux checks it install okay +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +if "%JOB_NAME%"=="%JOB_NAME:pull_requests=%" ( + set SYSTEMTEST_DIR=%WORKSPACE%\Code\Mantid\Testing\SystemTest + :: Install package + python %SYSTEMTEST_DIR%\scripts\mantidinstaller.py install %WORKSPACE%\build + cd %WORKSPACE%\build\docs + :: Run tests + C:\MantidInstall\bin\MantidPlot.exe -xq runsphinx_doctest.py + if ERRORLEVEl 1 exit /B %ERRORLEVEL% + :: Remove + cd %WORKSPACE%\build + python %SYSTEMTEST_DIR%\scripts\mantidinstaller.py uninstall %WORKSPACE%\build +) + From 912e39a2d07e5fcef7f38b54f72fe4c493803f2d Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 15 Feb 2015 17:41:49 +0000 Subject: [PATCH 109/414] fix coverity issues 1075319, 20 (initialize), re #11061 --- Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp b/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp index 81558d7eb491..dcff64737513 100644 --- a/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp +++ b/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp @@ -45,11 +45,14 @@ Logger g_log("NexusFileIO"); } /// Empty default constructor -NexusFileIO::NexusFileIO() : m_nexuscompression(NX_COMP_LZW), m_progress(0) {} +NexusFileIO::NexusFileIO() : fileID(), m_filehandle(NULL), + m_nexuscompression(NX_COMP_LZW), m_progress(0), m_filename() { +} /// Constructor that supplies a progress object -NexusFileIO::NexusFileIO(Progress *prog) - : m_nexuscompression(NX_COMP_LZW), m_progress(prog) {} +NexusFileIO::NexusFileIO(Progress *prog) : fileID(), m_filehandle(NULL), + m_nexuscompression(NX_COMP_LZW), m_progress(prog), m_filename() { +} void NexusFileIO::resetProgress(Progress *prog) { m_progress = prog; } From 7900eeffb3c2fe5c0a8e6532788f564a71f05c52 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 15 Feb 2015 17:42:18 +0000 Subject: [PATCH 110/414] fix coverity issue 1075388 (initialize), re #11061 --- Code/Mantid/Framework/DataObjects/src/EventWorkspace.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/DataObjects/src/EventWorkspace.cpp b/Code/Mantid/Framework/DataObjects/src/EventWorkspace.cpp index a99d81b44f5b..bec4ade53280 100644 --- a/Code/Mantid/Framework/DataObjects/src/EventWorkspace.cpp +++ b/Code/Mantid/Framework/DataObjects/src/EventWorkspace.cpp @@ -35,7 +35,9 @@ using namespace Mantid::Kernel; //---- Constructors //------------------------------------------------------------------- -EventWorkspace::EventWorkspace() : mru(new EventWorkspaceMRU) {} +EventWorkspace::EventWorkspace() : data(), m_noVectors(), + mru(new EventWorkspaceMRU) { +} EventWorkspace::~EventWorkspace() { delete mru; From 28db6201aef6d1dd354904c6e3f3355a3b98b177 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 15 Feb 2015 17:42:40 +0000 Subject: [PATCH 111/414] fix coverity issue 1075400 (initialize), re #11061 --- Code/Mantid/Framework/DataHandling/src/LoadRaw3.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/DataHandling/src/LoadRaw3.cpp b/Code/Mantid/Framework/DataHandling/src/LoadRaw3.cpp index 4e7b88629261..421add0dc041 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadRaw3.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadRaw3.cpp @@ -31,8 +31,11 @@ using namespace API; /// Constructor LoadRaw3::LoadRaw3() - : m_filename(), m_noTimeRegimes(0), m_prog(0.0), m_prog_start(0.0), - m_prog_end(1.0), m_lengthIn(0), m_timeChannelsVec(), m_total_specs(0) {} + : m_filename(), m_numberOfSpectra(), m_cache_options(), + m_specTimeRegimes(), m_noTimeRegimes(0), m_prog(0.0), + m_prog_start(0.0), m_prog_end(1.0), m_lengthIn(0), + m_timeChannelsVec(), m_total_specs(0), m_periodList() { +} LoadRaw3::~LoadRaw3() {} From d21be66e395efc147509ceb0611e0437e1f387ed Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 15 Feb 2015 17:43:06 +0000 Subject: [PATCH 112/414] fix coverity issue 1147106 (initialize), re #11061 --- Code/Mantid/Framework/DataHandling/src/LoadAscii2.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/DataHandling/src/LoadAscii2.cpp b/Code/Mantid/Framework/DataHandling/src/LoadAscii2.cpp index 191e995b9e38..37dc4a4e6436 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadAscii2.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadAscii2.cpp @@ -25,7 +25,10 @@ using namespace Kernel; using namespace API; /// Empty constructor -LoadAscii2::LoadAscii2() : m_columnSep(), m_separatorIndex() {} +LoadAscii2::LoadAscii2() : m_columnSep(), m_separatorIndex(), m_comment(), + m_baseCols(0), m_specNo(0), m_lastBins(0), m_curBins(0), m_spectraStart(), + m_spectrumIDcount(0), m_lineNo(0), m_spectra(), m_curSpectra(NULL) { +} /** * Return the confidence with with this algorithm can load the file From 10fc43d6249bd5b1e7e9e726590eff2906d217d8 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 15 Feb 2015 17:44:53 +0000 Subject: [PATCH 113/414] fix coverity issues 1076078, 9 (pass by ref), re #11061 --- .../Framework/CurveFitting/inc/MantidCurveFitting/LeBailFit.h | 2 +- Code/Mantid/Framework/CurveFitting/src/LeBailFit.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/LeBailFit.h b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/LeBailFit.h index eb70dd8af7d6..6080044f484a 100644 --- a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/LeBailFit.h +++ b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/LeBailFit.h @@ -253,7 +253,7 @@ class DLLExport LeBailFit : public API::Algorithm { bool prevBetterRwp); /// Limit proposed value in the specified boundary - double limitProposedValueInBound(Parameter param, double newvalue, + double limitProposedValueInBound(const Parameter ¶m, double newvalue, double direction, int choice); /// Book keep the (sopposed) best MC result diff --git a/Code/Mantid/Framework/CurveFitting/src/LeBailFit.cpp b/Code/Mantid/Framework/CurveFitting/src/LeBailFit.cpp index 295468f47e91..1f5be4d8da23 100644 --- a/Code/Mantid/Framework/CurveFitting/src/LeBailFit.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/LeBailFit.cpp @@ -2297,7 +2297,7 @@ bool LeBailFit::proposeNewValues(vector mcgroup, Rfactor r, * * @return :: new value in boundary */ -double LeBailFit::limitProposedValueInBound(Parameter param, double newvalue, +double LeBailFit::limitProposedValueInBound(const Parameter ¶m, double newvalue, double direction, int choice) { if (choice == 0) { // Half distance From 7cac90bbcff0d77436cef074c435b979b1c1e420 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 15 Feb 2015 17:45:38 +0000 Subject: [PATCH 114/414] fix coverity issue 1076125 (constness - hide/overwrite), re #11061 --- Code/Mantid/MantidPlot/src/Plot.cpp | 24 +++++++++++++++--------- Code/Mantid/MantidPlot/src/Plot.h | 18 +++++++++--------- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Plot.cpp b/Code/Mantid/MantidPlot/src/Plot.cpp index 8ab3ae206a62..e44b275dd3b8 100644 --- a/Code/Mantid/MantidPlot/src/Plot.cpp +++ b/Code/Mantid/MantidPlot/src/Plot.cpp @@ -756,12 +756,17 @@ void Plot::showEvent (QShowEvent * event) \brief Paint the plot into a given rectangle. Paint the contents of a QwtPlot instance into a given rectangle (Qwt modified code). + Note that this method is const so that it properly overrides + QwtPlot::print (coverity issue 1076125). This however requires + several const_casts in the code, as constness either is not + specified in some methods called or it is actually arguable. + @param painter :: Painter @param plotRect :: Bounding rectangle @param pfilter :: Print filter */ void Plot::print(QPainter *painter, const QRect &plotRect, - const QwtPlotPrintFilter &pfilter) + const QwtPlotPrintFilter &pfilter) const { int axisId; @@ -787,7 +792,7 @@ void Plot::print(QPainter *painter, const QRect &plotRect, // reset the widget attributes again. This way we produce a lot of // useless layout events ... - pfilter.apply((QwtPlot *)this); + pfilter.apply((QwtPlot *)const_cast(this)); int baseLineDists[QwtPlot::axisCnt]; if ( !(pfilter.options() & 16) ){ @@ -795,7 +800,7 @@ void Plot::print(QPainter *painter, const QRect &plotRect, // the scale on the frame of the canvas. for (axisId = 0; axisId < QwtPlot::axisCnt; axisId++ ){ - QwtScaleWidget *scaleWidget = (QwtScaleWidget *)axisWidget(axisId); + QwtScaleWidget *scaleWidget = const_cast(axisWidget(axisId)); if ( scaleWidget ){ baseLineDists[axisId] = scaleWidget->margin(); scaleWidget->setMargin(0); @@ -811,7 +816,7 @@ void Plot::print(QPainter *painter, const QRect &plotRect, if ( !(pfilter.options() & QwtPlotPrintFilter::PrintLegend) ) layoutOptions |= QwtPlotLayout::IgnoreLegend; - ((QwtPlot *)this)->plotLayout()->activate(this, + ((QwtPlot *)const_cast(this))->plotLayout()->activate(this, QwtPainter::metricsMap().deviceToLayout(plotRect), layoutOptions); @@ -875,7 +880,7 @@ void Plot::print(QPainter *painter, const QRect &plotRect, for ( axisId = 0; axisId < QwtPlot::axisCnt; axisId++ ){ - QwtScaleWidget *scaleWidget = (QwtScaleWidget *)axisWidget(axisId); + QwtScaleWidget *scaleWidget = const_cast(axisWidget(axisId)); if (scaleWidget){ int baseDist = scaleWidget->margin(); @@ -919,21 +924,22 @@ void Plot::print(QPainter *painter, const QRect &plotRect, - ((QwtPlot *)this)->plotLayout()->invalidate(); + ((QwtPlot *)const_cast(this))->plotLayout()->invalidate(); // reset all widgets with their original attributes. if ( !(pfilter.options() & 16) ){ // restore the previous base line dists for (axisId = 0; axisId < QwtPlot::axisCnt; axisId++ ){ - QwtScaleWidget *scaleWidget = (QwtScaleWidget *)axisWidget(axisId); + QwtScaleWidget *scaleWidget = + const_cast(axisWidget(axisId)); if ( scaleWidget ) scaleWidget->setMargin(baseLineDists[axisId]); } } - pfilter.reset((QwtPlot *)this); + pfilter.reset((QwtPlot *)const_cast(this)); painter->restore(); - setTitle(t);//hack used to avoid bug in Qwt::printTitle(): the title attributes are overwritten + const_cast(this)->setTitle(t);//hack used to avoid bug in Qwt::printTitle(): the title attributes are overwritten } diff --git a/Code/Mantid/MantidPlot/src/Plot.h b/Code/Mantid/MantidPlot/src/Plot.h index 7d4e57bfa9dd..9aecdb0bf689 100644 --- a/Code/Mantid/MantidPlot/src/Plot.h +++ b/Code/Mantid/MantidPlot/src/Plot.h @@ -90,21 +90,21 @@ class Plot: public QwtPlot void axisLabelFormat(int axis, char &f, int &prec) const; - int axisLabelFormat(int axis); - int axisLabelPrecision(int axis); + int axisLabelFormat(int axis); + int axisLabelPrecision(int axis); - QColor frameColor(); - const QColor & paletteBackgroundColor() const; + QColor frameColor(); + const QColor & paletteBackgroundColor() const; using QwtPlot::print; // Avoid Intel compiler warning - void print(QPainter *, const QRect &rect, const QwtPlotPrintFilter & = QwtPlotPrintFilter()); - void updateLayout(); + void print(QPainter *, const QRect &rect, const QwtPlotPrintFilter & = QwtPlotPrintFilter()) const; + void updateLayout(); void updateCurveLabels(); - // pass through method that is public on the base class in later qwt versions - void updateAxes() { QwtPlot::updateAxes(); } + // pass through method that is public on the base class in later qwt versions + void updateAxes() { QwtPlot::updateAxes(); } - void reverseCurveOrder(); // Created in connection with waterfall plots. Called from Graph method of same name. + void reverseCurveOrder(); // Created in connection with waterfall plots. Called from Graph method of same name. signals: void dragMousePress(QPoint); From ceb348e0e0b0eda5865bed8a25654087fbcbba57 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 15 Feb 2015 17:56:39 +0000 Subject: [PATCH 115/414] fix coverity issue 1076079 (pass by ref), re #11061 --- Code/Mantid/Framework/Crystal/inc/MantidCrystal/SaveIsawUB.h | 2 +- Code/Mantid/Framework/Crystal/src/SaveIsawUB.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/Crystal/inc/MantidCrystal/SaveIsawUB.h b/Code/Mantid/Framework/Crystal/inc/MantidCrystal/SaveIsawUB.h index f801c296730d..6ee866ca117f 100644 --- a/Code/Mantid/Framework/Crystal/inc/MantidCrystal/SaveIsawUB.h +++ b/Code/Mantid/Framework/Crystal/inc/MantidCrystal/SaveIsawUB.h @@ -64,7 +64,7 @@ class DLLExport SaveIsawUB : public API::Algorithm { void exec(); // Calculates the error in the volume - double getErrorVolume(Geometry::OrientedLattice lattice); + double getErrorVolume(const Geometry::OrientedLattice &lattice); }; } // namespace Mantid diff --git a/Code/Mantid/Framework/Crystal/src/SaveIsawUB.cpp b/Code/Mantid/Framework/Crystal/src/SaveIsawUB.cpp index 4f9e74320185..a2ba70830a4f 100644 --- a/Code/Mantid/Framework/Crystal/src/SaveIsawUB.cpp +++ b/Code/Mantid/Framework/Crystal/src/SaveIsawUB.cpp @@ -54,7 +54,7 @@ void SaveIsawUB::init() { "Path to an ISAW-style UB matrix text file."); } -double SaveIsawUB::getErrorVolume(OrientedLattice lattice) { +double SaveIsawUB::getErrorVolume(const OrientedLattice &lattice) { double Volume; double latticeParams[6] = {lattice.a(), lattice.b(), lattice.c(), lattice.alpha(), lattice.beta(), lattice.gamma()}; From cbaa20900c567d62862363b0feac1a6a671ea144 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 15 Feb 2015 17:57:29 +0000 Subject: [PATCH 116/414] fix coverity issue 1075946 (delete[]), re #11061 --- Code/Mantid/MantidPlot/src/Interpolation.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Interpolation.cpp b/Code/Mantid/MantidPlot/src/Interpolation.cpp index 3a6bf0b26826..db4dfc68dfbd 100644 --- a/Code/Mantid/MantidPlot/src/Interpolation.cpp +++ b/Code/Mantid/MantidPlot/src/Interpolation.cpp @@ -177,8 +177,8 @@ int Interpolation::sortedCurveData(QwtPlotCurve *c, double start, double end, do for (int i = i_start; i <= i_end; i++){ xtemp[j] = c->x(i); if (i > i_start && xtemp[j] == pr_x){ - delete (*x); - delete (*y); + delete[] (*x); + delete[] (*y); delete[] xtemp; delete[] ytemp; return -1;//this kind of data causes division by zero in GSL interpolation routines From 11db12067ab2cdc34d72b21e59eb37b5abb3c065 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 15 Feb 2015 17:58:36 +0000 Subject: [PATCH 117/414] fix coverity issue 1075410 (initialize), re #11061 --- .../DataHandling/src/LoadEventNexus.cpp | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp b/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp index b2bd92871d58..93a987548c92 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp @@ -932,13 +932,19 @@ class LoadBankFromDiskTask : public Task { //---------------------------------------------------------------------------------------------- /** Empty default constructor */ -LoadEventNexus::LoadEventNexus() - : IFileLoader(), - discarded_events(0), - m_file(NULL), - m_instrument_loaded_correctly(false), - m_logs_loaded_correctly(false), - event_id_is_spec(false) {} +LoadEventNexus::LoadEventNexus() : IFileLoader(), + m_filename(), filter_tof_min(0), filter_tof_max(0), m_specList(), + m_specMin(0), m_specMax(0), filter_time_start(), filter_time_stop(), + chunk(0), totalChunks(0), firstChunkForBank(0), eventsPerChunk(0), + m_tofMutex(), longest_tof(0), shortest_tof(0), bad_tofs(0), + discarded_events(0), precount(0), compressTolerance(0), eventVectors(), + m_eventVectorMutex(), eventid_max(0), pixelID_to_wi_vector(), + pixelID_to_wi_offset(), m_bankPulseTimes(), m_allBanksPulseTimes(), + m_top_entry_name(), m_file(NULL), splitProcessing(false), + m_haveWeights(false), weightedEventVectors(), + m_instrument_loaded_correctly(false), loadlogs(false), + m_logs_loaded_correctly(false), event_id_is_spec(false) { +} //---------------------------------------------------------------------------------------------- /** Destructor */ From 83389ae59ab62df5624b7b6d8d685307250f29c2 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 15 Feb 2015 17:59:07 +0000 Subject: [PATCH 118/414] fix coverity issue 1241920 (initialize), re #11061 --- .../DataHandling/inc/MantidDataHandling/LoadFITS.h | 2 +- Code/Mantid/Framework/DataHandling/src/LoadFITS.cpp | 12 ++++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadFITS.h b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadFITS.h index 048970b8f801..f22452fabd9e 100644 --- a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadFITS.h +++ b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadFITS.h @@ -76,7 +76,7 @@ namespace DataHandling { class DLLExport LoadFITS : public API::IFileLoader { public: - LoadFITS() {} + LoadFITS(); virtual ~LoadFITS() {} /// Algorithm's name for identification overriding a virtual method diff --git a/Code/Mantid/Framework/DataHandling/src/LoadFITS.cpp b/Code/Mantid/Framework/DataHandling/src/LoadFITS.cpp index a72f3182f2c4..5d21f759abc3 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadFITS.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadFITS.cpp @@ -40,6 +40,16 @@ namespace DataHandling { // Register the algorithm into the AlgorithmFactory DECLARE_FILELOADER_ALGORITHM(LoadFITS); +/** + * Constructor. Just initialize everything to prevent issues. + */ +LoadFITS::LoadFITS(): m_headerScaleKey(), m_headerOffsetKey(), + m_headerBitDepthKey(), m_headerRotationKey(), + m_headerImageKeyKey(), m_mapFile(), + m_headerAxisNameKeys(), m_baseName(), + m_spectraCount(0), m_progress(NULL) { +} + /** * Return the confidence with with this algorithm can load the file * @param descriptor A descriptor for the file @@ -123,8 +133,6 @@ void LoadFITS::exec() { std::vector paths; string fName = getPropertyValue("Filename"); boost::split(paths, fName, boost::is_any_of(",")); - m_baseName = ""; - m_spectraCount = 0; // If paths contains a non fits file, assume (for now) that it contains // information about the rotations From 768d77d121e6a1a6e82eedf74d9926019dca5826 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 15 Feb 2015 18:14:54 +0000 Subject: [PATCH 119/414] fix coverity issue 1075406 (init in construtor), re #11061 --- Code/Mantid/Framework/DataHandling/src/LoadISISNexus2.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/DataHandling/src/LoadISISNexus2.cpp b/Code/Mantid/Framework/DataHandling/src/LoadISISNexus2.cpp index 24c18a7d081a..ca7d7a0dcf2b 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadISISNexus2.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadISISNexus2.cpp @@ -51,7 +51,9 @@ LoadISISNexus2::LoadISISNexus2() m_monBlockInfo(), m_loadBlockInfo(), m_have_detector(false), m_load_selected_spectra(false), m_specInd2specNum_map(), m_spec2det_map(), m_entrynumber(0), m_tof_data(), m_proton_charge(0.), m_spec(), - m_monitors(), m_logCreator(), m_progress() {} + m_spec_end(NULL), m_monitors(), m_logCreator(), m_progress(), + m_cppFile() { +} /** * Return the confidence criteria for this algorithm can load the file From 759f9820901cce5155b687597cca0ec2e4700ed6 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Sun, 15 Feb 2015 18:27:38 +0000 Subject: [PATCH 120/414] Move default external data location to HOME Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript | 6 +++--- Code/Mantid/Build/Jenkins/buildscript.bat | 7 ++++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript b/Code/Mantid/Build/Jenkins/buildscript index 6a4ffd903096..fe0dd370e919 100755 --- a/Code/Mantid/Build/Jenkins/buildscript +++ b/Code/Mantid/Build/Jenkins/buildscript @@ -58,11 +58,11 @@ fi ############################################################################### # Set up the location for the local object store outside of the build and # source tree, which can be shared by multiple builds. -# It defaults to the parent directory of the workspace but can be overridden -# by setting the MANTID_DATA_STORE environment variable. +# It defaults to a MantidExternalData directory within the HOME directory. +# It can be overridden by setting the MANTID_DATA_STORE environment variable. ############################################################################### if [ -z "$MANTID_DATA_STORE" ]; then - export MANTID_DATA_STORE=$(dirname $WORKSPACE) + export MANTID_DATA_STORE=$HOME/MantidExternalData fi ############################################################################### diff --git a/Code/Mantid/Build/Jenkins/buildscript.bat b/Code/Mantid/Build/Jenkins/buildscript.bat index b260bb128654..766b7efbb126 100755 --- a/Code/Mantid/Build/Jenkins/buildscript.bat +++ b/Code/Mantid/Build/Jenkins/buildscript.bat @@ -22,11 +22,12 @@ set PATH=%WORKSPACE%\Code\Third_Party\lib\win64;%WORKSPACE%\Code\Third_Party\lib ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Set up the location for local object store outside of the build and source :: tree, which can be shared by multiple builds. -:: It defaults to the parent directory of the workspace but can be overridden -:: by setting the MANTID_DATA_STORE environment variable. +:: It defaults to a MantidExternalData directory within the USERPROFILE +:: directory. It can be overridden by setting the MANTID_DATA_STORE environment +:: variable. ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: if NOT DEFINED MANTID_DATA_STORE ( - for %%F in ("%WORKSPACE%") do set MANTID_DATA_STORE=%%~dpF + set MANTID_DATA_STORE=%USERPROFILE%\MantidExternalData ) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: From d0c3785bb25d53d6e58aeff38b5da6cc94f7f627 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Sun, 15 Feb 2015 18:29:16 +0000 Subject: [PATCH 121/414] Temporary rule to remove build directory if old layout in use Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript | 9 +++++++++ Code/Mantid/Build/Jenkins/buildscript.bat | 8 ++++++++ 2 files changed, 17 insertions(+) diff --git a/Code/Mantid/Build/Jenkins/buildscript b/Code/Mantid/Build/Jenkins/buildscript index fe0dd370e919..fa12e930d27b 100755 --- a/Code/Mantid/Build/Jenkins/buildscript +++ b/Code/Mantid/Build/Jenkins/buildscript @@ -82,6 +82,15 @@ if [[ ${JOB_NAME} == *clean* ]]; then CLEANBUILD=true BUILDPKG=true fi + +if [[ -e $WORKSPACE/build/CMakeCache.txt ]] + # Temporary while the builds flick between old & new TestingTools locations + grep 'Code/Mantid/TestingTools/cxxtest' $WORKSPACE/build/CMakeCache.txt > /dev/null + if [ $? -eq 0 ]; then + rm -fr $WORKSPACE/build + fi +fi + if [[ ${JOB_NAME} == *pull_requests* ]]; then BUILDPKG=true fi diff --git a/Code/Mantid/Build/Jenkins/buildscript.bat b/Code/Mantid/Build/Jenkins/buildscript.bat index 766b7efbb126..1489530f8573 100755 --- a/Code/Mantid/Build/Jenkins/buildscript.bat +++ b/Code/Mantid/Build/Jenkins/buildscript.bat @@ -37,6 +37,14 @@ if "%JOB_NAME%"=="%JOB_NAME:clean=%" ( set CLEANBUILD=yes set BUILDPKG=yes ) + +if EXIST %WORKSPACE%\build\CMakeCache.txt ( + TYPE %WORKSPACE%\build\CMakeCache.txt | FINDSTR "Code/Mantid/TestingTools/cxxtest" + if %ERRORLEVEL% EQU 0 ( + rmdir /S /Q %WORKSPACE%\build + ) +) + if "%JOB_NAME%"=="%JOB_NAME:pull_requests=%" ( set BUILDPKG=yes ) From 7652f02b218454bd2df084f76832d58289c000db Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 15 Feb 2015 18:43:00 +0000 Subject: [PATCH 122/414] fix coverity issue 1075409 (init in construtor), re #11061 --- .../Framework/DataHandling/src/LoadEventPreNexus.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus.cpp b/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus.cpp index a6d61d8b2900..d8d0ab699c66 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus.cpp @@ -78,8 +78,15 @@ static const double TOF_CONVERSION = .1; static const double CURRENT_CONVERSION = 1.e-6 / 3600.; LoadEventPreNexus::LoadEventPreNexus() - : Mantid::API::IFileLoader(), eventfile(NULL), - max_events(0) {} + : Mantid::API::IFileLoader(), + prog(NULL), spectra_list(), pulsetimes(), event_indices(), proton_charge(), + proton_charge_tot(0), pixel_to_wkspindex(), pixelmap(), detid_max(), + eventfile(NULL), num_events(0), num_pulses(0), numpixel(0), + num_good_events(0), num_error_events(0), num_ignored_events(0), + first_event(0), max_events(0), using_mapping_file(false), + loadOnlySomeSpectra(false), spectraLoadMap(), longest_tof(0), + shortest_tof(0), parallelProcessing(false) { +} LoadEventPreNexus::~LoadEventPreNexus() { delete this->eventfile; } From fe3e5a64976565940a6e4bb41d6646651ff20afe Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 15 Feb 2015 18:43:15 +0000 Subject: [PATCH 123/414] fix coverity issue 1075408 (init in construtor), re #11061 --- .../Framework/DataHandling/src/LoadEventPreNexus2.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus2.cpp b/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus2.cpp index 0443bce0df6d..70aec93f7f76 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus2.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus2.cpp @@ -224,8 +224,15 @@ int LoadEventPreNexus2::confidence(Kernel::FileDescriptor &descriptor) const { /** Constructor */ LoadEventPreNexus2::LoadEventPreNexus2() - : Mantid::API::IFileLoader(), eventfile(NULL), - max_events(0) {} + : Mantid::API::IFileLoader(), + prog(NULL), spectra_list(), pulsetimes(), event_indices(), proton_charge(), + proton_charge_tot(0), pixel_to_wkspindex(), pixelmap(), detid_max(), + eventfile(NULL), num_events(0), num_pulses(0), numpixel(0), + num_good_events(0), num_error_events(0), num_ignored_events(0), + first_event(0), max_events(0), using_mapping_file(false), + loadOnlySomeSpectra(false), spectraLoadMap(), longest_tof(0), + shortest_tof(0), parallelProcessing(false) { +} //---------------------------------------------------------------------------------------------- /** Desctructor From efb1f91b6cf7c913f64acf4ae041aef22dab019a Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Sun, 15 Feb 2015 20:39:24 +0000 Subject: [PATCH 124/414] Fix errors in build script Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript | 2 +- Code/Mantid/Build/Jenkins/buildscript.bat | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript b/Code/Mantid/Build/Jenkins/buildscript index fa12e930d27b..3259bf2ae6d1 100755 --- a/Code/Mantid/Build/Jenkins/buildscript +++ b/Code/Mantid/Build/Jenkins/buildscript @@ -83,7 +83,7 @@ if [[ ${JOB_NAME} == *clean* ]]; then BUILDPKG=true fi -if [[ -e $WORKSPACE/build/CMakeCache.txt ]] +if [[ -e $WORKSPACE/build/CMakeCache.txt ]]; then # Temporary while the builds flick between old & new TestingTools locations grep 'Code/Mantid/TestingTools/cxxtest' $WORKSPACE/build/CMakeCache.txt > /dev/null if [ $? -eq 0 ]; then diff --git a/Code/Mantid/Build/Jenkins/buildscript.bat b/Code/Mantid/Build/Jenkins/buildscript.bat index 1489530f8573..151378aa1c70 100755 --- a/Code/Mantid/Build/Jenkins/buildscript.bat +++ b/Code/Mantid/Build/Jenkins/buildscript.bat @@ -70,7 +70,7 @@ cd %WORKSPACE%\build :: Clean up any artifacts from last build so that if it fails :: they don't get archived again. ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -del *.exe +del /Q *.exe ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Check the required build configuration From bb2726ec76c284b76f552a543c68155446d8e5ea Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Sun, 15 Feb 2015 20:46:17 +0000 Subject: [PATCH 125/414] Don't use readlink in buildscript. The OS X version doesn't support the same options as GNU readline Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript b/Code/Mantid/Build/Jenkins/buildscript index 3259bf2ae6d1..d4cdf2f66f07 100755 --- a/Code/Mantid/Build/Jenkins/buildscript +++ b/Code/Mantid/Build/Jenkins/buildscript @@ -9,7 +9,7 @@ # BUILD_THREADS & PARAVIEW_DIR should be set in the configuration of each # slave. ############################################################################### -SCRIPT_DIR=$(dirname $(readlink -f "$0")) +SCRIPT_DIR=$(dirname "$0") ############################################################################### # Print out the versions of things we are using From a3b71fed103fdcdcee908649daeb04252dc09123 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Sun, 15 Feb 2015 21:14:34 +0000 Subject: [PATCH 126/414] refs #11056. Test and implement. --- .../Crystal/inc/MantidCrystal/AddPeakHKL.h | 4 +- .../Framework/Crystal/src/AddPeakHKL.cpp | 25 +++-- .../Framework/Crystal/test/AddPeakHKLTest.h | 99 ++++++++++++++----- .../docs/source/algorithms/AddPeakHKL-v1.rst | 4 +- 4 files changed, 97 insertions(+), 35 deletions(-) diff --git a/Code/Mantid/Framework/Crystal/inc/MantidCrystal/AddPeakHKL.h b/Code/Mantid/Framework/Crystal/inc/MantidCrystal/AddPeakHKL.h index 2762b8122eae..055eadd3b7af 100644 --- a/Code/Mantid/Framework/Crystal/inc/MantidCrystal/AddPeakHKL.h +++ b/Code/Mantid/Framework/Crystal/inc/MantidCrystal/AddPeakHKL.h @@ -9,7 +9,7 @@ namespace Mantid namespace Crystal { - /** AddPeakHKL : TODO: DESCRIPTION + /** AddPeakHKL : Algorithm to add a peaks to a PeaksWorkspace in the HKL frame Copyright © 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source @@ -53,4 +53,4 @@ namespace Crystal } // namespace Crystal } // namespace Mantid -#endif /* MANTID_CRYSTAL_ADDPEAKHKL_H_ */ \ No newline at end of file +#endif /* MANTID_CRYSTAL_ADDPEAKHKL_H_ */ diff --git a/Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp b/Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp index 382354fdb9a6..78c563d096e9 100644 --- a/Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp +++ b/Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp @@ -1,12 +1,17 @@ #include "MantidCrystal/AddPeakHKL.h" +#include "MantidAPI/IPeaksWorkspace.h" +#include "MantidAPI/IPeak.h" +#include "MantidKernel/ArrayProperty.h" +#include "MantidKernel/ArrayLengthValidator.h" +#include "MantidKernel/V3D.h" namespace Mantid { namespace Crystal { - using Mantid::Kernel::Direction; - using Mantid::API::WorkspaceProperty; + using namespace Mantid::Kernel; + using namespace Mantid::API; // Register the algorithm into the AlgorithmFactory DECLARE_ALGORITHM(AddPeakHKL) @@ -37,18 +42,18 @@ namespace Crystal int AddPeakHKL::version() const { return 1;}; /// Algorithm's category for identification. @see Algorithm::category - const std::string AddPeakHKL::category() const { return TODO: FILL IN A CATEGORY;} + const std::string AddPeakHKL::category() const { return "Crystal";} /// Algorithm's summary for use in the GUI and help. @see Algorithm::summary - const std::string AddPeakHKL::summary() const { return TODO: FILL IN A SUMMARY;}; + const std::string AddPeakHKL::summary() const { return "Add a peak in the hkl frame";}; //---------------------------------------------------------------------------------------------- /** Initialize the algorithm's properties. */ void AddPeakHKL::init() { - declareProperty(new WorkspaceProperty<>("InputWorkspace","",Direction::Input), "An input workspace."); - declareProperty(new WorkspaceProperty<>("OutputWorkspace","",Direction::Output), "An output workspace."); + declareProperty(new WorkspaceProperty("Workspace","",Direction::InOut), "An input workspace."); + declareProperty(new ArrayProperty("HKL", boost::make_shared > (3)), "HKL point to add"); } //---------------------------------------------------------------------------------------------- @@ -56,10 +61,14 @@ namespace Crystal */ void AddPeakHKL::exec() { - // TODO Auto-generated execute stub + IPeaksWorkspace_sptr peakWS = this->getProperty("Workspace"); + const std::vector hklValue = this->getProperty("HKL"); + IPeak * peak = peakWS->createPeakHKL(V3D(hklValue[0], hklValue[1], hklValue[2])); + peakWS->addPeak(*peak); + delete peak; } } // namespace Crystal -} // namespace Mantid \ No newline at end of file +} // namespace Mantid diff --git a/Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h b/Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h index c1bbe8f084d1..278cb40f270a 100644 --- a/Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h +++ b/Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h @@ -2,11 +2,17 @@ #define MANTID_CRYSTAL_ADDPEAKHKLTEST_H_ #include - #include "MantidCrystal/AddPeakHKL.h" +#include "MantidKernel/V3D.h" +#include "MantidAPI/AnalysisDataService.h" +#include "MantidDataObjects/PeaksWorkspace.h" +#include "MantidGeometry/Crystal/OrientedLattice.h" +#include "MantidTestHelpers/ComponentCreationHelper.h" using Mantid::Crystal::AddPeakHKL; +using namespace Mantid::Kernel; using namespace Mantid::API; +using namespace Mantid::DataObjects; class AddPeakHKLTest : public CxxTest::TestSuite { @@ -24,38 +30,83 @@ class AddPeakHKLTest : public CxxTest::TestSuite TS_ASSERT( alg.isInitialized() ) } - void test_exec() + void test_hkl_validation() { - // Name of the output workspace. - std::string outWSName("AddPeakHKLTest_OutputWS"); - AddPeakHKL alg; - TS_ASSERT_THROWS_NOTHING( alg.initialize() ) - TS_ASSERT( alg.isInitialized() ) - TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("REPLACE_PROPERTY_NAME_HERE!!!!", "value") ); - TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("OutputWorkspace", outWSName) ); - TS_ASSERT_THROWS_NOTHING( alg.execute(); ); - TS_ASSERT( alg.isExecuted() ); + alg.initialize(); + std::vector hkl_bad(4); // Too big! + TS_ASSERT_THROWS( alg.setProperty("HKL", hkl_bad), std::invalid_argument& ); - // Retrieve the workspace from data service. TODO: Change to your desired type - Workspace_sptr ws; - TS_ASSERT_THROWS_NOTHING( ws = AnalysisDataService::Instance().retrieveWS(outWSName) ); - TS_ASSERT(ws); - if (!ws) return; + std::vector hkl_good(3, 0); // Right size. + TS_ASSERT_THROWS_NOTHING( alg.setProperty("HKL", hkl_good) ); + } - // TODO: Check the results - // Remove workspace from the data service. - AnalysisDataService::Instance().remove(outWSName); - } - - void test_Something() + void test_exec() { - TSM_ASSERT( "You forgot to write a test!", 0); + // Create simple fictional instrument + const V3D source(0,0,0); + const V3D sample(15, 0, 0); + const V3D detectorPos(20, 5, 0); + const V3D beam1 = sample - source; + const V3D beam2 = detectorPos - sample; + auto minimalInstrument = ComponentCreationHelper::createMinimalInstrument( source, sample, detectorPos ); + + // Derive distances and angles + const double l1 = beam1.norm(); + const double l2 = beam2.norm(); + const V3D qLabDir = (beam1/l1) - (beam2/l2); + + const double microSecsInSec = 1e6; + + // Derive QLab for diffraction + const double wavenumber_in_angstrom_times_tof_in_microsec = + (Mantid::PhysicalConstants::NeutronMass * (l1 + l2) * 1e-10 * microSecsInSec) / + Mantid::PhysicalConstants::h_bar; + V3D qLab = qLabDir * wavenumber_in_angstrom_times_tof_in_microsec; + + Mantid::Geometry::OrientedLattice orientedLattice(1, 1, 1, 90, 90, 90); // U is identity, real and reciprocal lattice vectors are identical. + Mantid::Geometry::Goniometer goniometer; // identity + V3D hkl = qLab / (2 * M_PI); // Given our settings above, this is the simplified relationship between qLab and hkl. + + // Now create a peaks workspace around the simple fictional instrument + PeaksWorkspace_sptr ws = boost::make_shared(); + ws->setInstrument(minimalInstrument); + ws->mutableSample().setOrientedLattice(&orientedLattice); + ws->mutableRun().setGoniometer(goniometer, false); + + Mantid::API::AnalysisDataService::Instance().add("peaks_ws",ws); + AddPeakHKL alg; + alg.initialize(); + std::vector hklVec; + hklVec.push_back(hkl.X()); + hklVec.push_back(hkl.Y()); + hklVec.push_back(hkl.Z()); + alg.setProperty("HKL", hklVec); + alg.setProperty("Workspace", ws); + alg.execute(); + ws = Mantid::API::AnalysisDataService::Instance().retrieveWS("peaks_ws"); + + // Get the peak just added. + const Peak& peak = ws->getPeak(0); + + /* + Now we check we have made a self - consistent peak + */ + TSM_ASSERT_EQUALS("New peak should have HKL we demanded.", hkl, peak.getHKL()); + TSM_ASSERT_EQUALS("New peak should have QLab we expected.", qLab, peak.getQLabFrame()); + TSM_ASSERT_EQUALS("QSample and QLab should be identical given the identity goniometer settings.", peak.getQLabFrame(), peak.getQSampleFrame()); + auto detector = peak.getDetector(); + TSM_ASSERT("No detector", detector); + TSM_ASSERT_EQUALS("This detector id does not match what we expect from the instrument definition", 1, detector->getID()); + TSM_ASSERT_EQUALS("Thie detector position is wrong", detectorPos, detector->getPos()); + TSM_ASSERT_EQUALS("Goniometer has not been set properly", goniometer.getR(), peak.getGoniometerMatrix()); + } + }; -#endif /* MANTID_CRYSTAL_ADDPEAKHKLTEST_H_ */ \ No newline at end of file +#endif /* MANTID_CRYSTAL_ADDPEAKHKLTEST_H_ */ diff --git a/Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst b/Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst index 3ac2fb16b715..066ed24f5669 100644 --- a/Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst +++ b/Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst @@ -10,7 +10,9 @@ Description ----------- -TODO: Enter a full rst-markup description of your algorithm here. +Add a peak in the HKL frame to an existing :ref:`PeaksWorkspace `. The OrientedLattice must be provided and the Goniometer should be set correctly before running the algorithm. + +This algorithm will Usage From 716b62eda1327be30119a2de8a1b54e9455d87ca Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Mon, 16 Feb 2015 08:49:20 +0000 Subject: [PATCH 127/414] Ignore grep return code and compare the output The build scripts are run such that any non-zero return code exits the script immediately. Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript b/Code/Mantid/Build/Jenkins/buildscript index d4cdf2f66f07..2418323e4320 100755 --- a/Code/Mantid/Build/Jenkins/buildscript +++ b/Code/Mantid/Build/Jenkins/buildscript @@ -85,8 +85,8 @@ fi if [[ -e $WORKSPACE/build/CMakeCache.txt ]]; then # Temporary while the builds flick between old & new TestingTools locations - grep 'Code/Mantid/TestingTools/cxxtest' $WORKSPACE/build/CMakeCache.txt > /dev/null - if [ $? -eq 0 ]; then + TESTINGTOOLS_DIR=$(grep 'Code/Mantid/TestingTools/cxxtest' $WORKSPACE/build/CMakeCache.txt || true) + if [ ! -z "$TESTINGTOOLS_DIR" ]; then rm -fr $WORKSPACE/build fi fi From 6c24e71adba371c8f6585f55099f51b5b3c6905e Mon Sep 17 00:00:00 2001 From: Nick Draper Date: Mon, 16 Feb 2015 09:08:16 +0000 Subject: [PATCH 128/414] re #11091 added another test --- .../Kernel/test/InternetHelperTest.h | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h b/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h index b07c1f69c978..c0928fd98cb1 100644 --- a/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h +++ b/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h @@ -9,6 +9,9 @@ #include "MantidKernel/ProxyInfo.h" #include +#include +#include "Poco/Net/PartSource.h" +#include "Poco/Net/StringPartSource.h" #include #include @@ -147,7 +150,7 @@ class InternetHelperTest : public CxxTest::TestSuite { TSM_ASSERT_EQUALS("method is not GET",internetHelper.getMethod(),"GET"); TSM_ASSERT_EQUALS("Contentlength is wrong",internetHelper.getContentLength(),0); } - + void test_BodyStream_GetSet() { MockedInternetHelper internetHelper; @@ -165,6 +168,38 @@ class InternetHelperTest : public CxxTest::TestSuite { TSM_ASSERT_EQUALS("Contentlength is wrong",internetHelper.getContentLength(),0); } + void test_BodyForm_GetSet() + { + MockedInternetHelper internetHelper; + Poco::Net::HTMLForm form(Poco::Net::HTMLForm::ENCODING_MULTIPART); + form.set("field1", "value1"); + form.set("field2", "value 2"); + form.set("field3", "value=3"); + form.set("field4", "value&4"); + + form.addPart("attachment1", new Poco::Net::StringPartSource("This is an attachment")); + Poco::Net::StringPartSource* pSPS = new Poco::Net::StringPartSource("This is another attachment", "text/plain", "att2.txt"); + pSPS->headers().set("Content-ID", "1234abcd"); + form.addPart("attachment2", pSPS); + TSM_ASSERT_EQUALS("Default body is not empty",internetHelper.getBody(),""); + TSM_ASSERT_EQUALS("method is not GET",internetHelper.getMethod(),"GET"); + internetHelper.setBody(form); + std::string body = internetHelper.getBody(); + TSM_ASSERT_DIFFERS("setBody failed \"--MIME_boundary\"",body.find("--MIME_boundary"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"This is an attachment\"",body.find("This is an attachment"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"This is another attachment\"",body.find("This is another attachment"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"field1\"",body.find("field1"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"field2\"",body.find("field2"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"field3\"",body.find("field3"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"field4\"",body.find("field4"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"value1\"",body.find("value1"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"value 2\"",body.find("value 2"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"value=3\"",body.find("value=3"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"value&4\"",body.find("value&4"),std::string::npos); + TSM_ASSERT_EQUALS("method is not POST",internetHelper.getMethod(),"POST"); + TSM_ASSERT_LESS_THAN("Contentlength is wrong",700,internetHelper.getContentLength()); + } + void test_Headers_GetSet() { MockedInternetHelper internetHelper; From 0bb3ef24a7b374ae237eeece07ab549741323f26 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 09:28:52 +0000 Subject: [PATCH 129/414] Initial work on UI for CalculateSampleTrenamission algo Refs #11072 --- .../MantidQt/CustomInterfaces/CMakeLists.txt | 4 + .../SampleTransmission.h | 55 ++++++ .../SampleTransmission.ui | 187 ++++++++++++++++++ .../src/SampleTransmission.cpp | 107 ++++++++++ 4 files changed, 353 insertions(+) create mode 100644 Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h create mode 100644 Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui create mode 100644 Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp diff --git a/Code/Mantid/MantidQt/CustomInterfaces/CMakeLists.txt b/Code/Mantid/MantidQt/CustomInterfaces/CMakeLists.txt index dd7c0b528b97..ea898a3f890a 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/CMakeLists.txt +++ b/Code/Mantid/MantidQt/CustomInterfaces/CMakeLists.txt @@ -63,6 +63,7 @@ set ( SRC_FILES src/ReflLegacyTransferStrategy.cpp src/ReflMainViewPresenter.cpp src/ReflSearchModel.cpp + src/SampleTransmission.cpp src/SANSAddFiles.cpp src/SANSDiagnostics.cpp src/SANSEventSlicing.cpp @@ -151,6 +152,7 @@ set ( INC_FILES inc/MantidQtCustomInterfaces/QReflTableModel.h inc/MantidQtCustomInterfaces/QtReflMainView.h inc/MantidQtCustomInterfaces/QtReflOptionsDialog.h + inc/MantidQtCustomInterfaces/SampleTransmission.h inc/MantidQtCustomInterfaces/SANSAddFiles.h inc/MantidQtCustomInterfaces/SANSDiagnostics.h inc/MantidQtCustomInterfaces/SANSEventSlicing.h @@ -223,6 +225,7 @@ set ( MOC_FILES inc/MantidQtCustomInterfaces/Background.h inc/MantidQtCustomInterfaces/QReflTableModel.h inc/MantidQtCustomInterfaces/QtReflMainView.h inc/MantidQtCustomInterfaces/QtReflOptionsDialog.h + inc/MantidQtCustomInterfaces/SampleTransmission.h inc/MantidQtCustomInterfaces/SANSAddFiles.h inc/MantidQtCustomInterfaces/SANSPlotSpecial.h inc/MantidQtCustomInterfaces/SANSRunWindow.h @@ -273,6 +276,7 @@ set ( UI_FILES inc/MantidQtCustomInterfaces/AddWorkspace.ui inc/MantidQtCustomInterfaces/ReflMainWidget.ui inc/MantidQtCustomInterfaces/ReflOptionsDialog.ui inc/MantidQtCustomInterfaces/ReflWindow.ui + inc/MantidQtCustomInterfaces/SampleTransmission.ui inc/MantidQtCustomInterfaces/SANSPlotSpecial.ui inc/MantidQtCustomInterfaces/SANSRunWindow.ui inc/MantidQtCustomInterfaces/SANSEventSlicing.ui diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h new file mode 100644 index 000000000000..7b4f1a931193 --- /dev/null +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h @@ -0,0 +1,55 @@ +#ifndef MANTIDQTCUSTOMINTERFACES_SAMPLETRANSMISSION_H_ +#define MANTIDQTCUSTOMINTERFACES_SAMPLETRANSMISSION_H_ + +//---------------------- +// Includes +//---------------------- +#include "ui_SampleTransmission.h" +#include "MantidQtAPI/AlgorithmRunner.h" +#include "MantidQtAPI/UserSubWindow.h" +#include "MantidQtAPI/WorkspaceObserver.h" +#include "MantidAPI/MatrixWorkspace.h" + + +namespace MantidQt +{ +namespace CustomInterfaces +{ + class SampleTransmission : public MantidQt::API::UserSubWindow + { + Q_OBJECT + + public: + /// The name of the interface as registered into the factory + static std::string name() { return "Sample Transmission Calculator"; } + // This interface's categories. + static QString categoryInfo() { return "General"; } + + public: + /// Default Constructor + SampleTransmission(QWidget *parent = 0); + + private slots: + /// Runs the calculation + void calculate(); + /// Handle completion of the calculation algorithm + void algorithmComplete(bool error); + + private: + /// Initialize the layout + virtual void initLayout(); + /// Validates UI input + bool validate(); + + private: + /// The form generated by Qt Designer + Ui::SampleTransmission m_uiForm; + /// Algorithm runner + API::AlgorithmRunner * m_algRunner; + + }; + +} +} + +#endif //MANTIDQTCUSTOMINTERFACES_SAMPLETRANSMISSION_H_ diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui new file mode 100644 index 000000000000..39ad60454078 --- /dev/null +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui @@ -0,0 +1,187 @@ + + + SampleTransmission + + + + 0 + 0 + 492 + 245 + + + + Sample Transmission Calculator + + + + + + + Input Wavelength Range + + + + + + + Single + + + + + Multiple + + + + + + + + Type: + + + + + + + + 0 + 0 + + + + 0 + + + + + + + Low: + + + + + + + + + + Width: + + + + + + + + + + High: + + + + + + + + + + + + + + + + + + + + + + + + Sample Details + + + + + + Thickness + + + + + + + Number Density + + + + + + + Chemical Formula + + + + + + + + + + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Calculate + + + + + + + + + + + + cbBinningType + currentIndexChanged(int) + swBinningTypes + setCurrentIndex(int) + + + 98 + 54 + + + 308 + 54 + + + + + diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp new file mode 100644 index 000000000000..9b9eb182ff44 --- /dev/null +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp @@ -0,0 +1,107 @@ +//---------------------- +// Includes +//---------------------- +#include "MantidQtCustomInterfaces/SampleTransmission.h" + +#include "MantidAPI/AlgorithmManager.h" + + +namespace +{ + Mantid::Kernel::Logger g_log("SampleTransmission"); +} + +//Add this class to the list of specialised dialogs in this namespace +namespace MantidQt +{ +namespace CustomInterfaces +{ + DECLARE_SUBWINDOW(SampleTransmission); +} +} + +using namespace MantidQt::CustomInterfaces; +using namespace Mantid::API; + + +//---------------------- +// Public member functions +//---------------------- +///Constructor +SampleTransmission::SampleTransmission(QWidget *parent) : + UserSubWindow(parent), + m_algRunner(new API::AlgorithmRunner(this)) +{ + connect(m_algRunner, SIGNAL(algorithmComplete(bool)), this, SLOT(algorithmComplete(bool))); +} + + +/** + * Set up the dialog layout. + */ +void SampleTransmission::initLayout() +{ + m_uiForm.setupUi(this); + connect(m_uiForm.pbCalculate, SIGNAL(clicked()), this, SLOT(calculate())); +} + + +/** + * Validate user input. + * Outputs any warnings to the results log at warning level. + * + * @return Result of validation + */ +bool SampleTransmission::validate() +{ + //TODO + return false; +} + + +/** + * Performs a calculation with the current settings + */ +void SampleTransmission::calculate() +{ + // Create the transmission calculation algorithm + IAlgorithm_sptr transCalcAlg = AlgorithmManager::Instance().create("CalculateSampleTransmission"); + transCalcAlg->initialize(); + + // Set the wavelength binning based on type set in UI + int wavelengthBinning = m_uiForm.cbBinningType->currentIndex(); + switch(wavelengthBinning) + { + // Multiple + case 0: + //TODO + transCalcAlg->setProperty("WavelengthRange", ""); + break; + + // Single + case 1: + transCalcAlg->setProperty("WavelengthRange", m_uiForm.leMultiple->text().toStdString()); + break; + } + + // Set sample material properties + transCalcAlg->setProperty("ChemicalFormula", m_uiForm.leChemicalFormula->text().toStdString()); + transCalcAlg->setProperty("NumberDensity", m_uiForm.spNumberDensity->value()); + transCalcAlg->setProperty("Thickness", m_uiForm.spThickness->value()); + + transCalcAlg->setProperty("OutputWorkspace", "CalculatedSampleTransmission"); + + // Run algorithm + m_algRunner->startAlgorithm(transCalcAlg); +} + + +/** + * Handles completion of the calculation algorithm. + * + * @param error If the algorithm exited with an error + */ +void SampleTransmission::algorithmComplete(bool error) +{ + //TODO +} From b788d915ef4abf4ab694b2f70af12fb82980ba0b Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 09:35:50 +0000 Subject: [PATCH 130/414] Label the spectra in the output WS Refs #11072 --- .../plugins/algorithms/CalculateSampleTransmission.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py index c88d3bf4f803..f8614e0bc6a7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py @@ -50,7 +50,8 @@ def PyExec(self): self._setup() # Create the workspace and set the sample material - CreateWorkspace(OutputWorkspace=self._output_ws, NSpec=2, DataX=[0, 0], DataY=[0, 0]) + CreateWorkspace(OutputWorkspace=self._output_ws, NSpec=2, DataX=[0, 0], DataY=[0, 0], + VerticalAxisUnit='Text', VerticalAxisValues='Transmission,Scattering') Rebin(InputWorkspace=self._output_ws, OutputWorkspace=self._output_ws, Params=self._bin_params) SetSampleMaterial(InputWorkspace=self._output_ws, ChemicalFormula=self._chamical_formula) ConvertToPointData(InputWorkspace=self._output_ws, OutputWorkspace=self._output_ws) From f7ca977d66b6f13923d84a44a533d07877fadcab Mon Sep 17 00:00:00 2001 From: Nick Draper Date: Mon, 16 Feb 2015 09:48:22 +0000 Subject: [PATCH 131/414] re #11091 added missing include --- .../Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h | 1 + Code/Mantid/Framework/Kernel/src/InternetHelper.cpp | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h b/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h index 7b349f5be947..3263ae07fcfa 100644 --- a/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h +++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h @@ -6,6 +6,7 @@ #include "MantidKernel/ProxyInfo.h" #include +#include namespace Poco { // forward declaration diff --git a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp index 2da210836094..92c9af6dfebd 100644 --- a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp +++ b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp @@ -75,7 +75,7 @@ bool isRelocated(const int response) { InternetHelper::InternetHelper() : m_proxyInfo(), m_isProxySet(false), m_timeout(30), m_contentLength(0), m_method(HTTPRequest::HTTP_GET), m_contentType("application/json"), - m_body(), m_request(NULL) {} + m_body(), m_headers(), m_request(NULL) {} //---------------------------------------------------------------------------------------------- /** Constructor @@ -83,7 +83,7 @@ InternetHelper::InternetHelper() InternetHelper::InternetHelper(const Kernel::ProxyInfo &proxy) : m_proxyInfo(proxy), m_isProxySet(true), m_timeout(30), m_method(HTTPRequest::HTTP_GET), m_contentType("application/json"), - m_body(), m_request(NULL) {} + m_body(), m_headers(), m_request(NULL) {} //---------------------------------------------------------------------------------------------- /** Destructor From 4812d3ae946e2fa9190fc0d9b9dc41c19786c5da Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Mon, 16 Feb 2015 09:56:56 +0000 Subject: [PATCH 132/414] refs #11056. Usage + documentation. --- .../docs/source/algorithms/AddPeakHKL-v1.rst | 42 +++++++++++++------ 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst b/Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst index 066ed24f5669..ab768f8c24c9 100644 --- a/Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst +++ b/Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst @@ -12,35 +12,51 @@ Description Add a peak in the HKL frame to an existing :ref:`PeaksWorkspace `. The OrientedLattice must be provided and the Goniometer should be set correctly before running the algorithm. -This algorithm will +The peak is added to the existing PeaksWorkspace. Run information and goniometer setting and the UB matrix are taken from the provided PeaksWorkspace. Usage ----- -.. Try not to use files in your examples, - but if you cannot avoid it then the (small) files must be added to - autotestdata\UsageData and the following tag unindented - .. include:: ../usagedata-note.txt **Example - AddPeakHKL** .. testcode:: AddPeakHKLExample - # Create a host workspace - ws = CreateWorkspace(DataX=range(0,3), DataY=(0,2)) - or - ws = CreateSampleWorkspace() + import os + import numpy + import mantid.kernel - wsOut = AddPeakHKL() + # Create an instrument workspace + inst_dir = config.getInstrumentDirectory() + sxd_ws = LoadEmptyInstrument(os.path.join(inst_dir, "SXD_Definition.xml")) + AddSampleLog(sxd_ws, 'run_number', '1', 'Number') - # Print the result - print "The output workspace has %i spectra" % wsOut.getNumberHistograms() + # Create a peaks workspace from the instrument workspace + peak_ws = CreatePeaksWorkspace(InstrumentWorkspace=sxd_ws, NumberOfPeaks=0) + peak_ws.mutableRun().addProperty('run_number', sxd_ws.run().getProperty('run_number'), True) + + # Apply a UB + ub = numpy.array([[-0.15097235, 0.09164432, 0.00519473], [ 0.0831895, 0.14123681, -0.06719047], [-0.03845029, -0.05534039, -0.1633801 ]]) + SetUB(peak_ws, UB=ub) + + # Add a new peak + AddPeakHKL(peak_ws, [2, 0, -4]) + + # Get info on newly added peak + peak = peak_ws.getPeak(0) + print 'Peak wavelength', round(peak.getWavelength(), 4) + print 'Peak detector id', peak.getDetectorID() + print 'Peak run number', peak.getRunNumber() + print 'Peak HKL', peak.getHKL() Output: .. testoutput:: AddPeakHKLExample - The output workspace has ?? spectra + Peak wavelength 1.8423 + Peak detector id 25766 + Peak run number 1 + Peak HKL [2,0,-4] .. categories:: From ceb9a8de1b4a99b269e34798e65abb071aac1fc7 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 10:03:07 +0000 Subject: [PATCH 133/414] Add validation to sample transmission UI Refs #11072 --- .../SampleTransmission.ui | 50 ++++++++++++------ .../UserInputValidator.h | 4 ++ .../src/SampleTransmission.cpp | 52 ++++++++++++++++--- .../src/UserInputValidator.cpp | 41 +++++++++++++-- 4 files changed, 120 insertions(+), 27 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui index 39ad60454078..eea5ecafef60 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui @@ -7,7 +7,7 @@ 0 0 492 - 245 + 247 @@ -92,6 +92,13 @@ + + + + + + +
@@ -105,20 +112,40 @@ Sample Details - - + + - Thickness + Number Density - - + + + + + + + + - Number Density + Thickness + + + + + + + + + + + + + + @@ -126,15 +153,6 @@ - - - - - - - - -
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/UserInputValidator.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/UserInputValidator.h index 8356e3821fc0..1d8a98ddce7c 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/UserInputValidator.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/UserInputValidator.h @@ -80,8 +80,12 @@ namespace MantidQt bool isAllInputValid(); private: + /// Sets a validation label + void setErrorLabel(QLabel * errorLabel, bool valid); + /// Any raised error messages. QStringList m_errorMessages; + }; } } diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp index 9b9eb182ff44..ffc0e6dbec33 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp @@ -4,6 +4,7 @@ #include "MantidQtCustomInterfaces/SampleTransmission.h" #include "MantidAPI/AlgorithmManager.h" +#include "MantidQtCustomInterfaces/UserInputValidator.h" namespace @@ -54,8 +55,37 @@ void SampleTransmission::initLayout() */ bool SampleTransmission::validate() { - //TODO - return false; + UserInputValidator uiv; + + // Valudate input binning + int wavelengthBinning = m_uiForm.cbBinningType->currentIndex(); + switch(wavelengthBinning) + { + // Single + case 0: + uiv.checkBins(m_uiForm.spSingleLow->value(), + m_uiForm.spSingleWidth->value(), + m_uiForm.spSingleHigh->value()); + break; + + // Multiple + case 1: + uiv.checkFieldIsNotEmpty("Multiple binning", + m_uiForm.leMultiple, + m_uiForm.valMultiple); + break; + } + + // Validate chemical formula + uiv.checkFieldIsNotEmpty("Chemical Formula", + m_uiForm.leChemicalFormula, + m_uiForm.valChemicalFormula); + + // Give error message + if(!uiv.isAllInputValid()) + g_log.error(uiv.generateErrorMessage().toStdString()); + + return uiv.isAllInputValid(); } @@ -64,6 +94,10 @@ bool SampleTransmission::validate() */ void SampleTransmission::calculate() { + // Do not try to run with invalid input + if(!validate()) + return; + // Create the transmission calculation algorithm IAlgorithm_sptr transCalcAlg = AlgorithmManager::Instance().create("CalculateSampleTransmission"); transCalcAlg->initialize(); @@ -72,13 +106,19 @@ void SampleTransmission::calculate() int wavelengthBinning = m_uiForm.cbBinningType->currentIndex(); switch(wavelengthBinning) { - // Multiple + // Single case 0: - //TODO - transCalcAlg->setProperty("WavelengthRange", ""); + { + QStringList params; + params << m_uiForm.spSingleLow->text() + << m_uiForm.spSingleWidth->text() + << m_uiForm.spSingleHigh->text(); + QString binString = params.join(","); + transCalcAlg->setProperty("WavelengthRange", binString.toStdString()); break; + } - // Single + // Multiple case 1: transCalcAlg->setProperty("WavelengthRange", m_uiForm.leMultiple->text().toStdString()); break; diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp index ae7bba5358be..aa880db60af9 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp @@ -45,13 +45,13 @@ namespace MantidQt { if(field->text() == "") { - errorLabel->setText("*"); + setErrorLabel(errorLabel, false); m_errorMessages.append(name + " has been left blank."); return false; } else { - errorLabel->setText(""); + setErrorLabel(errorLabel, true); return true; } } @@ -72,12 +72,12 @@ namespace MantidQt if( fieldState == QValidator::Acceptable ) { - errorLabel->setText(""); + setErrorLabel(errorLabel, true); return true; } else { - errorLabel->setText("*"); + setErrorLabel(errorLabel, false); m_errorMessages.append(errorMessage); return false; } @@ -273,7 +273,7 @@ namespace MantidQt if( m_errorMessages.isEmpty() ) return ""; - return "Please correct the following:\n\n" + m_errorMessages.join("\n"); + return "Please correct the following:\n" + m_errorMessages.join("\n"); } /** @@ -285,5 +285,36 @@ namespace MantidQt { return m_errorMessages.isEmpty(); } + + /** + * Sets a validation label that is displyed next to the widget on the UI. + * + * @param errorLabel Label to change + * @param valid If the input was valid + */ + void UserInputValidator::setErrorLabel(QLabel * errorLabel, bool valid) + { + // Do nothing if no error label was provided + if(errorLabel == NULL) + return; + + if(!valid) + { + // Set the label to be red + QPalette palette = errorLabel->palette(); + palette.setColor(errorLabel->foregroundRole(), Qt::red); + errorLabel->setPalette(palette); + + errorLabel->setText("*"); + } + else + { + errorLabel->setText(""); + } + + // Only show the label if input is invalid + errorLabel->setVisible(!valid); + } + } } From 096f9835a3de34f1f8713cc0513845ff83f07e30 Mon Sep 17 00:00:00 2001 From: Nick Draper Date: Mon, 16 Feb 2015 10:21:35 +0000 Subject: [PATCH 134/414] re #11091 change stringstream to ostringstream usage --- .../Kernel/inc/MantidKernel/InternetHelper.h | 4 ++-- Code/Mantid/Framework/Kernel/src/InternetHelper.cpp | 13 ++----------- .../Framework/Kernel/test/InternetHelperTest.h | 2 +- 3 files changed, 5 insertions(+), 14 deletions(-) diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h b/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h index 3263ae07fcfa..d55696f3d102 100644 --- a/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h +++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h @@ -76,7 +76,7 @@ class MANTID_KERNEL_DLL InternetHelper { std::streamsize getContentLength(); void setBody(const std::string& body); - void setBody(const std::stringstream& body); + void setBody(const std::ostringstream& body); void setBody(Poco::Net::HTMLForm& form); const std::string getBody(); @@ -124,7 +124,7 @@ class MANTID_KERNEL_DLL InternetHelper { std::streamsize m_contentLength; std::string m_method; std::string m_contentType; - std::stringstream m_body; + std::ostringstream m_body; StringToStringMap m_headers; Poco::Net::HTTPRequest *m_request; }; diff --git a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp index 92c9af6dfebd..f99b99b28e25 100644 --- a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp +++ b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp @@ -472,17 +472,8 @@ void InternetHelper::setBody(const std::string& body) { * and GET if it is. * @param body A stringstream of the body **/ -void InternetHelper::setBody(const std::stringstream& body) { - //clear the old body - m_body.str("") ; - //if empty - if (body.rdbuf()->in_avail() == 0) { - setMethod("GET"); - } else { - setMethod("POST"); - m_body << body.str(); - } - setContentLength(m_body.tellp()); +void InternetHelper::setBody(const std::ostringstream& body) { + setBody(body.str()); } /** Sets the body & content length for future requests, this will also diff --git a/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h b/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h index c0928fd98cb1..b82081ae5a29 100644 --- a/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h +++ b/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h @@ -154,7 +154,7 @@ class InternetHelperTest : public CxxTest::TestSuite { void test_BodyStream_GetSet() { MockedInternetHelper internetHelper; - std::stringstream ss; + std::ostringstream ss; ss << "Test string"; TSM_ASSERT_EQUALS("Default body is not empty",internetHelper.getBody(),""); internetHelper.setBody(ss); From e62e0e280fab8cf7d671cd759ab39b509722c7f5 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Mon, 16 Feb 2015 10:27:48 +0000 Subject: [PATCH 135/414] proper fix for 1076305, throw exception, re #10602 --- .../DataHandling/src/ProcessDasNexusLog.cpp | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Code/Mantid/Framework/DataHandling/src/ProcessDasNexusLog.cpp b/Code/Mantid/Framework/DataHandling/src/ProcessDasNexusLog.cpp index 9ce0da04e849..31e715bb976c 100644 --- a/Code/Mantid/Framework/DataHandling/src/ProcessDasNexusLog.cpp +++ b/Code/Mantid/Framework/DataHandling/src/ProcessDasNexusLog.cpp @@ -388,9 +388,10 @@ void ProcessDasNexusLog::convertToAbsoluteTime( Kernel::Property *log = ws->run().getProperty(logname); Kernel::TimeSeriesProperty *tslog = dynamic_cast *>(log); - std::vector times; - if (tslog) - times = tslog->timesAsVector(); + if (!tslog) + throw std::runtime_error("Invalid time series log: it could not be cast " + "(interpreted) as a time series property"); + std::vector times = tslog->timesAsVector(); std::vector values = tslog->valuesAsVector(); // 2. Get converted @@ -447,9 +448,10 @@ void ProcessDasNexusLog::writeLogtoFile(API::MatrixWorkspace_sptr ws, Kernel::Property *log = ws->run().getProperty(logname); Kernel::TimeSeriesProperty *tslog = dynamic_cast *>(log); - std::vector times; - if (tslog) - tslog->timesAsVector(); + if (!tslog) + throw std::runtime_error("Invalid time series log: it could not be cast " + "(interpreted) as a time series property"); + std::vector times = tslog->timesAsVector(); std::vector values = tslog->valuesAsVector(); // 2. Write out From b9ab94a80c0c5de5587fffe0bfa679075bdb26bf Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Mon, 16 Feb 2015 10:42:42 +0000 Subject: [PATCH 136/414] fix 1076308, exception and only if proton_log really used, re #10602 --- .../Framework/DataHandling/src/LoadNexusLogs.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Code/Mantid/Framework/DataHandling/src/LoadNexusLogs.cpp b/Code/Mantid/Framework/DataHandling/src/LoadNexusLogs.cpp index 37f2e2131419..ebbde7d28c0d 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadNexusLogs.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadNexusLogs.cpp @@ -133,9 +133,6 @@ void LoadNexusLogs::exec() { // the code below will allow current SANS2D files to load if (workspace->mutableRun().hasProperty("proton_log")) { std::vector event_frame_number; - Kernel::TimeSeriesProperty *plog = - dynamic_cast *>( - workspace->mutableRun().getProperty("proton_log")); this->getLogger().notice() << "Using old ISIS proton_log and event_frame_number indirection..." << std::endl; @@ -167,15 +164,19 @@ void LoadNexusLogs::exec() { file.openPath("/" + entry_name); if (!event_frame_number.empty()) // ISIS indirection - see above comments { + Kernel::TimeSeriesProperty *plog = + dynamic_cast *>( + workspace->mutableRun().getProperty("proton_log")); + if (!plog) + throw std::runtime_error("Could not cast (interpret) proton_log as a time " + "series property. Cannot continue."); Kernel::TimeSeriesProperty *pcharge = new Kernel::TimeSeriesProperty("proton_charge"); std::vector pval; std::vector ptime; pval.reserve(event_frame_number.size()); ptime.reserve(event_frame_number.size()); - std::vector plogt; - if (plog) - plogt = plog->timesAsVector(); + std::vector plogt = plog->timesAsVector(); std::vector plogv = plog->valuesAsVector(); for (size_t i = 0; i < event_frame_number.size(); ++i) { ptime.push_back(plogt[event_frame_number[i]]); From 4adc1e9d5755f75dd4dd0f99a484166c8b05724c Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 10:49:03 +0000 Subject: [PATCH 137/414] Add more UI validation and improve sizing Refs #11072 --- .../SampleTransmission.h | 2 +- .../SampleTransmission.ui | 120 ++++++++++++++---- .../UserInputValidator.h | 8 +- .../src/SampleTransmission.cpp | 19 ++- .../src/UserInputValidator.cpp | 28 ++++ 5 files changed, 146 insertions(+), 31 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h index 7b4f1a931193..66bb3b810dee 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h @@ -39,7 +39,7 @@ namespace CustomInterfaces /// Initialize the layout virtual void initLayout(); /// Validates UI input - bool validate(); + bool validate(bool silent = false); private: /// The form generated by Qt Designer diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui index eea5ecafef60..3ee2c04bab41 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui @@ -6,14 +6,26 @@ 0 0 - 492 - 247 + 500 + 275 + + + 0 + 0 + + Sample Transmission Calculator + + + 0 + 0 + + @@ -21,6 +33,12 @@ Input Wavelength Range + + 0 + + + 0 + @@ -63,7 +81,14 @@ - + + + -99.989999999999995 + + + 0.100000000000000 + + @@ -73,7 +98,14 @@ - + + + -99.989999999999995 + + + 0.100000000000000 + + @@ -83,7 +115,14 @@ - + + + -99.989999999999995 + + + 0.100000000000000 + + @@ -119,12 +158,6 @@
- - - - - - @@ -132,20 +165,6 @@ - - - - - - - - - - - - - - @@ -153,9 +172,60 @@ + + + + 0.100000000000000 + + + + + + + 0.100000000000000 + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + Qt::Vertical + + + + 20 + 40 + + + + diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/UserInputValidator.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/UserInputValidator.h index 1d8a98ddce7c..0a9c44070a14 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/UserInputValidator.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/UserInputValidator.h @@ -71,18 +71,20 @@ namespace MantidQt bool checkRangeIsEnclosed(const QString & outerName, std::pair outer, const QString & innerName, std::pair inner); /// Check that the given range can be split evenly into bins of the given width. bool checkBins(double lower, double binWidth, double upper, double tolerance = 0.00000001); + /// Checks two values are not equal + bool checkNotEqual(const QString & name, double x, double y = 0.0, double tolerance = 0.00000001); /// Add a custom error message to the list. void addErrorMessage(const QString & message); + /// Sets a validation label + void setErrorLabel(QLabel * errorLabel, bool valid); + /// Returns an error message which contains all the error messages raised by the check functions. QString generateErrorMessage(); /// Checks to see if all input is valid bool isAllInputValid(); private: - /// Sets a validation label - void setErrorLabel(QLabel * errorLabel, bool valid); - /// Any raised error messages. QStringList m_errorMessages; diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp index ffc0e6dbec33..71909d56369d 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp @@ -44,6 +44,8 @@ void SampleTransmission::initLayout() { m_uiForm.setupUi(this); connect(m_uiForm.pbCalculate, SIGNAL(clicked()), this, SLOT(calculate())); + + validate(true); } @@ -51,9 +53,10 @@ void SampleTransmission::initLayout() * Validate user input. * Outputs any warnings to the results log at warning level. * + * @param silent If the results should not be logged * @return Result of validation */ -bool SampleTransmission::validate() +bool SampleTransmission::validate(bool silent) { UserInputValidator uiv; @@ -81,8 +84,16 @@ bool SampleTransmission::validate() m_uiForm.leChemicalFormula, m_uiForm.valChemicalFormula); + // Ensure number density is not zero + uiv.setErrorLabel(m_uiForm.valNumberDensity, + uiv.checkNotEqual("Number Density", m_uiForm.spNumberDensity->value())); + + // Ensure thickness is not zero + uiv.setErrorLabel(m_uiForm.valThickness, + uiv.checkNotEqual("Thickness", m_uiForm.spThickness->value())); + // Give error message - if(!uiv.isAllInputValid()) + if(!silent && !uiv.isAllInputValid()) g_log.error(uiv.generateErrorMessage().toStdString()); return uiv.isAllInputValid(); @@ -143,5 +154,9 @@ void SampleTransmission::calculate() */ void SampleTransmission::algorithmComplete(bool error) { + // Ignore errors + if(error) + return; + //TODO } diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp index aa880db60af9..57b4ef5c3c3a 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp @@ -21,6 +21,8 @@ namespace // anonymous pair.second = temp; } } + + Mantid::Kernel::Logger g_log("UserInputValidator"); } // anonymous namespace namespace MantidQt @@ -254,6 +256,32 @@ namespace MantidQt return true; } + /** + * Checks two values are not equal. + * + * @param name Name of value + * @param x First value + * @param y Second value (defaults to zero) + * @param tolerance Tolerance to which to compare + * @return True if input was valid + */ + bool UserInputValidator::checkNotEqual(const QString & name, double x, double y, double tolerance) + { + double delta = x - y; + + if(std::abs(delta) <= tolerance) + { + std::stringstream msg; + msg << name.toStdString() << " (" << x << ")" + << " should not be equal to " << y << "."; + QString msgStr = QString::fromStdString(msg.str()); + m_errorMessages.append(msgStr); + return false; + } + + return true; + } + /** * Add a custom error message to the list. * From 5bb7b4cffe34136111e14e06de0c6147831e2d89 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 10:42:03 +0000 Subject: [PATCH 138/414] Refs #11094 Resolves Coverity 1076227 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index a13343453c9d..05cdf866b18e 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -4004,14 +4004,18 @@ void ApplicationWindow::removeCurves(const QString& name) foreach(MdiSubWindow *w, windows){ if (w->isA("MultiLayer")) { - QList layers = dynamic_cast(w)->layersList(); + auto ml = dynamic_cast(w); + if(!ml) + return; + QList layers = ml->layersList(); foreach(Graph *g, layers) - g->removeCurves(name); + g->removeCurves(name); } else if (w->isA("Graph3D")) { - if ( (dynamic_cast(w)->formula()).contains(name) ) - dynamic_cast(w)->clearData(); + auto g3d = dynamic_cast(w); + if(g3d && g3d->formula().contains(name)) + g3d->clearData(); } } QApplication::restoreOverrideCursor(); From 147322223323972f90d7f58891c090892df1b967 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 10:43:10 +0000 Subject: [PATCH 139/414] Refs #11094 Resolves Coverity 1076226 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 05cdf866b18e..97298496fe58 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -6245,6 +6245,9 @@ void ApplicationWindow::rename() void ApplicationWindow::renameWindow() { WindowListItem *it = dynamic_cast(lv->currentItem()); + if (!it) + return; + MdiSubWindow *w = it->window(); if (!w) return; From 9995dbdddf687ebee29f363b4fc59d4b79740680 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 10:45:19 +0000 Subject: [PATCH 140/414] Refs #11094 Resolves Coverity 1076225 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 97298496fe58..5796d1c78ba7 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -6263,8 +6263,15 @@ void ApplicationWindow::renameWindow(Q3ListViewItem *item, int, const QString &t if (!item) return; - MdiSubWindow *w = dynamic_cast(item)->window(); - if (!w || text == w->objectName()) + WindowListItem *wli = dynamic_cast(item); + if (!wli) + return; + + MdiSubWindow *w = wli->window(); + if (!w) + return; + + if(text == w->objectName()) return; if(!setWindowName(w, text)) From 35f4a4010ca18769dc2594758bb83b68fe0156e0 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 10:46:19 +0000 Subject: [PATCH 141/414] Refs #11094 Resolves Coverity 1076224 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 5796d1c78ba7..3ac0a97d20ef 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -8760,6 +8760,9 @@ void ApplicationWindow::resizeActiveWindow() void ApplicationWindow::resizeWindow() { WindowListItem *it = dynamic_cast(lv->currentItem()); + if (!it) + return; + MdiSubWindow *w = it->window(); if (!w) return; From 7a4bcc849d64533a19390cd83c07d324dea106f1 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 10:47:42 +0000 Subject: [PATCH 142/414] Refs #11094 Resolves Coverity 1076223 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 3ac0a97d20ef..40a1a7d10a43 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -9582,7 +9582,11 @@ void ApplicationWindow::savedProject() foreach(MdiSubWindow *w, folderWindows) { if (w->isA("Matrix")) - (dynamic_cast(w))->undoStack()->setClean(); + { + Matrix* m = dynamic_cast(w); + if (m) + m->undoStack()->setClean(); + } } f = f->folderBelow(); } From c10576d64318a9cf234b9657b95ca81c432e767a Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 10:50:02 +0000 Subject: [PATCH 143/414] Refs #11094 Resolves Coverity 1076222 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 40a1a7d10a43..e814e0f03d7d 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -4026,9 +4026,13 @@ void ApplicationWindow::updateCurves(Table *t, const QString& name) QList windows = windowsList(); foreach(MdiSubWindow *w, windows){ if (w->isA("MultiLayer")){ - QList layers = dynamic_cast(w)->layersList(); - foreach(Graph *g, layers) - g->updateCurvesData(t, name); + MultiLayer* ml = dynamic_cast(w); + if(ml) + { + QList layers = ml->layersList(); + foreach(Graph *g, layers) + g->updateCurvesData(t, name); + } } else if (w->isA("Graph3D")){ Graph3D* g = dynamic_cast(w); if ((g->formula()).contains(name)) From befa32a573655aaba01bfa3cb2a608ee149d3f92 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 10:50:26 +0000 Subject: [PATCH 144/414] Refs #11094 Resolves Coverity 1076221 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index e814e0f03d7d..3c91c53b085d 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -4035,7 +4035,7 @@ void ApplicationWindow::updateCurves(Table *t, const QString& name) } } else if (w->isA("Graph3D")){ Graph3D* g = dynamic_cast(w); - if ((g->formula()).contains(name)) + if (g && (g->formula()).contains(name)) g->updateData(t); } } From dc9ea061c835b58c5bb50e7c5f403680cbc767a1 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 10:55:01 +0000 Subject: [PATCH 145/414] Refs #11094 Resolves Coverity 10762{19,20} --- .../MantidPlot/src/ApplicationWindow.cpp | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 3c91c53b085d..95488b19afa3 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -8394,11 +8394,20 @@ void ApplicationWindow::copySelection() if (!m) return; - if (m->inherits("Table")) - dynamic_cast(m)->copySelection(); + if (m->inherits("Table")) + { + Table* table = dynamic_cast(m); + if(table) + table->copySelection(); + } else if (m->isA("Matrix")) - dynamic_cast(m)->copySelection(); - else if (m->isA("MultiLayer")){ + { + Matrix* matrix = dynamic_cast(m); + if(matrix) + matrix->copySelection(); + } + else if (m->isA("MultiLayer")) + { MultiLayer* plot = dynamic_cast(m); if (!plot || plot->layers() == 0) return; @@ -8410,7 +8419,9 @@ void ApplicationWindow::copySelection() if (g->activeTool()){ if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector) { - dynamic_cast(g->activeTool())->copySelection(); + RangeSelectorTool* rst = dynamic_cast(g->activeTool()); + if(rst) + rst->copySelection(); } } else if (g->markerSelected()){ copyMarker(); @@ -8422,7 +8433,11 @@ void ApplicationWindow::copySelection() plot->copyAllLayers(); } else if (m->isA("Note")) - dynamic_cast(m)->editor()->copy(); + { + Note* note = dynamic_cast(m); + if(note) + note->editor()->copy(); + } else mantidUI->copyValues();//Mantid } From 119ae339cf2ec1b3a5b0a9157afefdbf46c77504 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 10:56:16 +0000 Subject: [PATCH 146/414] Refs #11094 Resolves Coverity 1076218 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 95488b19afa3..21647a699896 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -7707,7 +7707,11 @@ void ApplicationWindow::printAllPlots() foreach(MdiSubWindow *w, windows){ if (w->isA("MultiLayer") && printer.newPage()) - dynamic_cast(w)->printAllLayers(paint); + { + MultiLayer* ml = dynamic_cast(w); + if (ml) + ml->printAllLayers(paint); + } } paint->end(); delete paint; From a9f367cf48783c4c4d3aad4cf891872590c153a8 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 10:56:55 +0000 Subject: [PATCH 147/414] Refs #11094 Resolves Coverity 1076217 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 21647a699896..87c144d44041 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -6220,8 +6220,11 @@ void ApplicationWindow::saveProjectAs(const QString& fileName, bool compress) QFileInfo fi(fn); QString baseName = fi.baseName(); FolderListItem *item = dynamic_cast(folders->firstChild()); - item->setText(0, baseName); - item->folder()->setObjectName(baseName); + if(item) + { + item->setText(0, baseName); + item->folder()->setObjectName(baseName); + } } } } From b33e0371ffef1ef4283cd99049930760d7148e78 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:01:11 +0000 Subject: [PATCH 148/414] Refs #11094 Resolves Coverity 1076216 --- .../MantidPlot/src/ApplicationWindow.cpp | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 87c144d44041..1722ace56f68 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -7831,20 +7831,33 @@ void ApplicationWindow::showFFTDialog() FFTDialog *sd = 0; if (w->isA("MultiLayer")) { - Graph* g = dynamic_cast(w)->activeGraph(); - if ( g && g->validCurvesDataSize() ){ + MultiLayer* ml = dynamic_cast(w); + if(!ml) + return; + + Graph* g = ml->activeGraph(); + if(!g) + return; + + if (g->validCurvesDataSize() ){ sd = new FFTDialog(FFTDialog::onGraph, this); sd->setAttribute(Qt::WA_DeleteOnClose); sd->setGraph(g); } } else if (w->inherits("Table")) { + Table* t = dynamic_cast(w); + if(!t) + return; sd = new FFTDialog(FFTDialog::onTable, this); sd->setAttribute(Qt::WA_DeleteOnClose); - sd->setTable(dynamic_cast(w)); + sd->setTable(t); } else if (w->inherits("Matrix")) { + Matrix* m = dynamic_cast(w); + if(!m) + return; sd = new FFTDialog(FFTDialog::onMatrix, this); sd->setAttribute(Qt::WA_DeleteOnClose); - sd->setMatrix(dynamic_cast(w)); + sd->setMatrix(m); } if (sd) From e19f7cf0181ae79b784662b68f82ecb2edc5d20b Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:03:02 +0000 Subject: [PATCH 149/414] Refs #11094 Resolves Coverity 1076215 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 1722ace56f68..95353f48f538 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -7769,7 +7769,11 @@ void ApplicationWindow::showFitDialog() if(w->isA("MultiLayer")) plot = dynamic_cast(w); else if(w->inherits("Table")) - plot = multilayerPlot(dynamic_cast(w), dynamic_cast(w)->drawableColumnSelection(), Graph::LineSymbols); + { + Table* t = dynamic_cast(w); + if(t) + plot = multilayerPlot(t, t->drawableColumnSelection(), Graph::LineSymbols); + } if (!plot) return; From 7afda07cc6155e74992dd4eaa494c4c0fae3397f Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:04:08 +0000 Subject: [PATCH 150/414] Refs #11094 Resolves Coverity 1076214 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 95353f48f538..b4a40e85711e 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -8966,7 +8966,9 @@ void ApplicationWindow::activateWindow(Q3ListViewItem * lbi) if (!lbi || lbi->rtti() == FolderListItem::RTTI) return; - activateWindow(dynamic_cast(lbi)->window()); + WindowListItem* wli = dynamic_cast(lbi); + if(wli) + activateWindow(wli->window()); } void ApplicationWindow::maximizeWindow(Q3ListViewItem * lbi) From 7e12b3e10cc7b607d72c8dfa4704f60e72fe4a53 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:13:58 +0000 Subject: [PATCH 151/414] Refs #11094 Resolves Coverity 10762{11,13} --- .../MantidPlot/src/ApplicationWindow.cpp | 34 ++++++++++++++----- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index b4a40e85711e..4a3a69779b8d 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -8380,22 +8380,36 @@ void ApplicationWindow::clearSelection() return; if (m->inherits("Table")) - dynamic_cast(m)->clearSelection(); + { + auto t = dynamic_cast(m); + if(t) + t->clearSelection(); + } else if (m->isA("Matrix")) - dynamic_cast(m)->clearSelection(); + { + auto matrix = dynamic_cast(m); + if(matrix) + matrix->clearSelection(); + } else if (m->isA("MultiLayer")) { - Graph* g = dynamic_cast(m)->activeGraph(); + auto ml = dynamic_cast(m); + if(!ml) + return; + + Graph* g = ml->activeGraph(); if (!g) return; if (g->activeTool()) { - if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector) - dynamic_cast(g->activeTool())->clearSelection(); + auto rst = dynamic_cast(g->activeTool()); + auto lbt = dynamic_cast(g->activeTool()); - if (g->activeTool()->rtti() == PlotToolInterface::Rtti_LabelTool) - dynamic_cast(g->activeTool())->removeTextBox(); + if(rst) + rst->clearSelection(); + else if(lbt) + lbt->removeTextBox(); } else if (g->titleSelected()) @@ -8404,7 +8418,11 @@ void ApplicationWindow::clearSelection() g->removeMarker(); } else if (m->isA("Note")) - dynamic_cast(m)->editor()->clear(); + { + auto note = dynamic_cast(m); + if(note) + note->editor()->clear(); + } emit modified(); } From e6689c6e669def6bfe61971edb930532f21cc883 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:18:47 +0000 Subject: [PATCH 152/414] Refs #11094 Resolves Coverity 1076212 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 4a3a69779b8d..b56c0f9aa862 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -8902,7 +8902,8 @@ void ApplicationWindow::setActiveWindow(MdiSubWindow* w) void ApplicationWindow::activateWindow() { WindowListItem *it = dynamic_cast(lv->currentItem()); - activateWindow(it->window()); + if(it) + activateWindow(it->window()); } /** From 81bebab1c34da1becc959f564f96186b52ecd10d Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:20:56 +0000 Subject: [PATCH 153/414] Refs #11094 Resolves Coverity 1076210 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index b56c0f9aa862..70afa4f8cbd4 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -10001,7 +10001,10 @@ QStringList ApplicationWindow::dependingPlots(const QString& name) QList windows = windowsList(); foreach(MdiSubWindow *w, windows){ if (w->isA("MultiLayer")){ - QList layers = dynamic_cast(w)->layersList(); + auto ml = dynamic_cast(w); + if(!ml) + return plots; + QList layers = ml->layersList(); foreach(Graph *g, layers){ onPlot = g->curvesList(); onPlot = onPlot.grep (name,TRUE); @@ -10009,7 +10012,8 @@ QStringList ApplicationWindow::dependingPlots(const QString& name) plots << w->objectName(); } }else if (w->isA("Graph3D")){ - if ((dynamic_cast(w)->formula()).contains(name,TRUE) && plots.contains(w->objectName())<=0) + auto g3d = dynamic_cast(w); + if (g3d && (g3d->formula()).contains(name,TRUE) && plots.contains(w->objectName())<=0) plots << w->objectName(); } } From c54a505cdefb549db9454308c15187375afb0d28 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:23:28 +0000 Subject: [PATCH 154/414] Refs #11094 Resolves Coverity 1076209 --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 70afa4f8cbd4..3a2c1b240fe0 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -8985,7 +8985,7 @@ void ApplicationWindow::activateWindow(Q3ListViewItem * lbi) if (!lbi || lbi->rtti() == FolderListItem::RTTI) return; - WindowListItem* wli = dynamic_cast(lbi); + auto wli = dynamic_cast(lbi); if(wli) activateWindow(wli->window()); } @@ -8998,7 +8998,9 @@ void ApplicationWindow::maximizeWindow(Q3ListViewItem * lbi) if (!lbi || lbi->rtti() == FolderListItem::RTTI) return; - maximizeWindow(dynamic_cast(lbi)->window()); + auto wli = dynamic_cast(lbi); + if(wli) + maximizeWindow(wli->window()); } void ApplicationWindow::maximizeWindow(MdiSubWindow *w) From b295d10ba64159716905e9b157d948d2dde63db3 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:33:52 +0000 Subject: [PATCH 155/414] Refs #11094 Resolve Coverity issues in pasteSelection --- .../MantidPlot/src/ApplicationWindow.cpp | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 3a2c1b240fe0..e850b8d67160 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -8554,11 +8554,23 @@ void ApplicationWindow::pasteSelection() return; if (m->inherits("Table")) - dynamic_cast(m)->pasteSelection(); + { + auto table = dynamic_cast(m); + if(table) + table->pasteSelection(); + } else if (m->isA("Matrix")) - dynamic_cast(m)->pasteSelection(); + { + auto matrix = dynamic_cast(m); + if(matrix) + matrix->pasteSelection(); + } else if (m->isA("Note")) - dynamic_cast(m)->editor()->paste(); + { + auto note = dynamic_cast(m); + if(note) + note->editor()->paste(); + } else if (m->isA("MultiLayer")){ MultiLayer* plot = dynamic_cast(m); if (!plot) From 98ffcabc7a82c23f4ee1996450068738dc1bb9b4 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 11:37:08 +0000 Subject: [PATCH 156/414] Added output as tree widget Refs #11072 --- .../SampleTransmission.ui | 54 ++++++++++++++----- .../src/SampleTransmission.cpp | 40 +++++++++++++- .../src/UserInputValidator.cpp | 2 - 3 files changed, 81 insertions(+), 15 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui index 3ee2c04bab41..7e61fa9f9d3a 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui @@ -6,8 +6,8 @@ 0 0 - 500 - 275 + 550 + 450 @@ -214,17 +214,47 @@ - - - Qt::Vertical - - - - 20 - 40 - + + + Output - + + + + + + 0 + 0 + + + + + 0 + 0 + 0 + + + + true + + + + + + + + Property + + + + + Value + + + + + + diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp index 71909d56369d..801f58119682 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp @@ -4,6 +4,7 @@ #include "MantidQtCustomInterfaces/SampleTransmission.h" #include "MantidAPI/AlgorithmManager.h" +#include "MantidKernel/Statistics.h" #include "MantidQtCustomInterfaces/UserInputValidator.h" @@ -154,9 +155,46 @@ void SampleTransmission::calculate() */ void SampleTransmission::algorithmComplete(bool error) { + using namespace Mantid::Kernel; + // Ignore errors if(error) return; - //TODO + MatrixWorkspace_sptr ws = + AnalysisDataService::Instance().retrieveWS("CalculatedSampleTransmission"); + + // Fill the output table + m_uiForm.twResults->clear(); + + double scattering = ws->dataY(1)[0]; + QTreeWidgetItem *scatteringItem = new QTreeWidgetItem(); + scatteringItem->setText(0, "Scattering"); + scatteringItem->setText(1, QString::number(scattering)); + m_uiForm.twResults->addTopLevelItem(scatteringItem); + + QTreeWidgetItem *transmissionItem = new QTreeWidgetItem(); + transmissionItem->setText(0, "Transmission"); + m_uiForm.twResults->addTopLevelItem(transmissionItem); + transmissionItem->setExpanded(true); + + std::vector transmissionData = ws->dataY(0); + Statistics stats = getStatistics(transmissionData); + + QMap transmissionStats; + transmissionStats["Min"] = stats.minimum; + transmissionStats["Max"] = stats.maximum; + transmissionStats["Mean"] = stats.mean; + transmissionStats["Median"] = stats.median; + transmissionStats["Std. Dev."] = stats.standard_deviation; + + for(auto it = transmissionStats.begin(); it != transmissionStats.end(); ++it) + { + QTreeWidgetItem *item = new QTreeWidgetItem(); + item->setText(0, it.key()); + item->setText(1, QString::number(it.value())); + transmissionItem->addChild(item); + } + + //TODO: plot } diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp index 57b4ef5c3c3a..649917e064f7 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp @@ -21,8 +21,6 @@ namespace // anonymous pair.second = temp; } } - - Mantid::Kernel::Logger g_log("UserInputValidator"); } // anonymous namespace namespace MantidQt From a59cb98b6753261ecb3ed7939a4fedf4377875e9 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:38:44 +0000 Subject: [PATCH 157/414] Refs #11094 Resolve Coverity issues in changeMatrixName --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index e850b8d67160..c5353dbffa2d 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -2242,16 +2242,22 @@ void ApplicationWindow::changeMatrixName(const QString& oldName, const QString& foreach(MdiSubWindow *w, windows){ if (w->isA("Graph3D")) { - QString s = dynamic_cast(w)->formula(); + auto g3d = dynamic_cast(w); + if(!g3d) + return; + QString s = g3d->formula(); if (s.contains(oldName)) { s.replace(oldName, newName); - dynamic_cast(w)->setPlotAssociation(s); + g3d->setPlotAssociation(s); } } else if (w->isA("MultiLayer")) { - QList layers = dynamic_cast(w)->layersList(); + auto ml = dynamic_cast(w); + if(!ml) + return; + QList layers = ml->layersList(); foreach(Graph *g, layers){ for (int i=0; icurves(); i++){ QwtPlotItem *sp = dynamic_cast(g->plotItem(i)); From 2dbf18db0e00a25139dcda7cfb8647aaa9a6aed4 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Mon, 16 Feb 2015 11:41:27 +0000 Subject: [PATCH 158/414] refs #11056. No default OL in test creation. Also fix segfault on PeaksViewer menu option, when no peaks are present, requesting size of the peak information. --- .../test/python/mantid/api/IPeaksWorkspaceTest.py | 6 +++--- .../test/testhelpers/WorkspaceCreationHelperModule.cpp | 4 +++- .../inc/MantidTestHelpers/WorkspaceCreationHelper.h | 2 +- .../Framework/TestHelpers/src/WorkspaceCreationHelper.cpp | 8 +++++--- .../MantidQt/SliceViewer/src/ConcretePeaksPresenter.cpp | 4 ++-- 5 files changed, 14 insertions(+), 10 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py index d8afffeba711..be86773d8241 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py @@ -54,7 +54,7 @@ def test_interface(self): self.assertTrue(not pws.hasIntegratedPeaks()) def test_createPeakHKL(self): - pws = WorkspaceCreationHelper.createPeaksWorkspace(0) + pws = WorkspaceCreationHelper.createPeaksWorkspace(0, True) lattice = pws.mutableSample().getOrientedLattice() # Simple test that the creational method is exposed @@ -62,7 +62,7 @@ def test_createPeakHKL(self): self.assertTrue(IPeak != None) def test_peak_setQLabFrame(self): - pws = WorkspaceCreationHelper.createPeaksWorkspace(1) + pws = WorkspaceCreationHelper.createPeaksWorkspace(1, True) p = pws.getPeak(0) try: p.setQLabFrame(V3D(1,1,1)) @@ -75,7 +75,7 @@ def test_peak_setQLabFrame(self): self.fail("Tried setQLabFrame with one V3D argument and a double distance") def test_peak_setQSampleFrame(self): - pws = WorkspaceCreationHelper.createPeaksWorkspace(1) + pws = WorkspaceCreationHelper.createPeaksWorkspace(1, True) p = pws.getPeak(0) try: p.setQSampleFrame(V3D(1,1,1)) diff --git a/Code/Mantid/Framework/PythonInterface/test/testhelpers/WorkspaceCreationHelperModule.cpp b/Code/Mantid/Framework/PythonInterface/test/testhelpers/WorkspaceCreationHelperModule.cpp index 28e4e94c7e5f..032de062643f 100644 --- a/Code/Mantid/Framework/PythonInterface/test/testhelpers/WorkspaceCreationHelperModule.cpp +++ b/Code/Mantid/Framework/PythonInterface/test/testhelpers/WorkspaceCreationHelperModule.cpp @@ -69,10 +69,12 @@ BOOST_PYTHON_MODULE(WorkspaceCreationHelper) //=================================== Peak Workspaces =================================== - // Forces the returns the be IEventWorkspace_sptr + // Forces the returns the be IPeaks_sptr typedef IPeaksWorkspace_sptr (*Signature1_Peaks)(const int); + typedef IPeaksWorkspace_sptr (*Signature2_Peaks)(const int, const bool); def("createPeaksWorkspace", (Signature1_Peaks)&createPeaksWorkspace); + def("createPeaksWorkspace", (Signature2_Peaks)&createPeaksWorkspace); //=================================== MD Workspaces =================================== diff --git a/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/WorkspaceCreationHelper.h b/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/WorkspaceCreationHelper.h index ab03c4524252..82afcca56f62 100644 --- a/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/WorkspaceCreationHelper.h +++ b/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/WorkspaceCreationHelper.h @@ -294,7 +294,7 @@ Mantid::DataObjects::RebinnedOutput_sptr CreateRebinnedOutputWorkspace(); /// Create a simple peaks workspace containing the given number of peaks boost::shared_ptr -createPeaksWorkspace(const int numPeaks = 2); +createPeaksWorkspace(const int numPeaks = 2, const bool createOrientedLattice=false); /**Build table workspace with preprocessed detectors for existign worksapce with * instrument */ boost::shared_ptr diff --git a/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp b/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp index 0005f3da7cee..aba40ce1d8ac 100644 --- a/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp +++ b/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp @@ -1182,7 +1182,7 @@ RebinnedOutput_sptr CreateRebinnedOutputWorkspace() { } Mantid::DataObjects::PeaksWorkspace_sptr -createPeaksWorkspace(const int numPeaks) { +createPeaksWorkspace(const int numPeaks, const bool createOrientedLattice) { PeaksWorkspace_sptr peaksWS(new PeaksWorkspace()); Instrument_sptr inst = ComponentCreationHelper::createTestInstrumentRectangular2(1, 10); @@ -1193,8 +1193,10 @@ createPeaksWorkspace(const int numPeaks) { peaksWS->addPeak(peak); } - Mantid::Geometry::OrientedLattice lattice; - peaksWS->mutableSample().setOrientedLattice(&lattice); + if(createOrientedLattice) { + Mantid::Geometry::OrientedLattice lattice; + peaksWS->mutableSample().setOrientedLattice(&lattice); + } return peaksWS; } diff --git a/Code/Mantid/MantidQt/SliceViewer/src/ConcretePeaksPresenter.cpp b/Code/Mantid/MantidQt/SliceViewer/src/ConcretePeaksPresenter.cpp index aa5929add3b7..0eebd21b630b 100644 --- a/Code/Mantid/MantidQt/SliceViewer/src/ConcretePeaksPresenter.cpp +++ b/Code/Mantid/MantidQt/SliceViewer/src/ConcretePeaksPresenter.cpp @@ -451,7 +451,7 @@ void ConcretePeaksPresenter::setPeakSizeIntoProjection(const double fraction) { double ConcretePeaksPresenter::getPeakSizeOnProjection() const { double result = 0; - if (m_viewPeaks != NULL && m_viewPeaks->positionOnly()) { + if (m_viewPeaks != NULL && (m_peaksWS->getNumberPeaks() > 0) && m_viewPeaks->positionOnly()) { result = m_viewPeaks->getOccupancyInView(); } return result; @@ -459,7 +459,7 @@ double ConcretePeaksPresenter::getPeakSizeOnProjection() const { double ConcretePeaksPresenter::getPeakSizeIntoProjection() const { double result = 0; - if (m_viewPeaks != NULL && m_viewPeaks->positionOnly()) { + if (m_viewPeaks != NULL && (m_peaksWS->getNumberPeaks() > 0) && m_viewPeaks->positionOnly()) { result = m_viewPeaks->getOccupancyIntoView(); } return result; From 1c1f601a9ccc431cfba91538c8bdfed3b0e27b7c Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 11:52:39 +0000 Subject: [PATCH 159/414] Small fixes to UI nad algorithm, added basic doc page Refs #11072 --- .../algorithms/CalculateSampleTransmission.py | 4 ++-- .../SampleTransmission.ui | 12 ++++++++++++ .../CustomInterfaces/src/SampleTransmission.cpp | 4 +++- .../interfaces/SampleTransmissionCalculator.rst | 17 +++++++++++++++++ 4 files changed, 34 insertions(+), 3 deletions(-) create mode 100644 Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py index f8614e0bc6a7..6fb0029cecaf 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py @@ -53,7 +53,7 @@ def PyExec(self): CreateWorkspace(OutputWorkspace=self._output_ws, NSpec=2, DataX=[0, 0], DataY=[0, 0], VerticalAxisUnit='Text', VerticalAxisValues='Transmission,Scattering') Rebin(InputWorkspace=self._output_ws, OutputWorkspace=self._output_ws, Params=self._bin_params) - SetSampleMaterial(InputWorkspace=self._output_ws, ChemicalFormula=self._chamical_formula) + SetSampleMaterial(InputWorkspace=self._output_ws, ChemicalFormula=self._chemical_formula) ConvertToPointData(InputWorkspace=self._output_ws, OutputWorkspace=self._output_ws) ws = mtd[self._output_ws] @@ -79,7 +79,7 @@ def _setup(self): """ self._bin_params = self.getPropertyValue('WavelengthRange') - self._chamical_formula = self.getPropertyValue('ChemicalFormula') + self._chemical_formula = self.getPropertyValue('ChemicalFormula') self._density = self.getProperty('NumberDensity').value self._thickness = self.getProperty('Thickness').value self._output_ws = self.getPropertyValue('OutputWorkspace') diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui index 7e61fa9f9d3a..14a70b09d4ff 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui @@ -174,16 +174,28 @@ + + Ã…^3 + 0.100000000000000 + + 0.100000000000000 + + + cm + 0.100000000000000 + + 0.100000000000000 + diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp index 801f58119682..47d60bd70c6b 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp @@ -196,5 +196,7 @@ void SampleTransmission::algorithmComplete(bool error) transmissionItem->addChild(item); } - //TODO: plot + m_uiForm.twResults->resizeColumnToContents(0); + + //TODO: Preview plot } diff --git a/Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst b/Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst new file mode 100644 index 000000000000..aaa50194e0bf --- /dev/null +++ b/Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst @@ -0,0 +1,17 @@ +Data Comparison +=============== + +.. contents:: Table of Contents + :local: + +Overview +-------- + +.. interface:: Sample Transmission Calculator + :align: right + +The sample transmission calculator allows the calculation fo the sample +transmission and scattering over a given wavelength range for a particular +sample material and geometry. + +.. categories:: Interfaces General From ecab55f8a0a209902bd61f2844066a1f271694c5 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 11:59:09 +0000 Subject: [PATCH 160/414] Fix documentation warning Fixes a warning caused by a title underline being too short --- Code/Mantid/docs/source/concepts/Using_XML_Schema.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/docs/source/concepts/Using_XML_Schema.rst b/Code/Mantid/docs/source/concepts/Using_XML_Schema.rst index 78346d7a107c..bab531897bbb 100644 --- a/Code/Mantid/docs/source/concepts/Using_XML_Schema.rst +++ b/Code/Mantid/docs/source/concepts/Using_XML_Schema.rst @@ -1,7 +1,7 @@ .. _Using_XML_Schema: Using XML Schemas -============= +================= This page gives instructions on how to configure various editing programs for writing XML with schema validation. This helps by finding errors in From e17288d8f23eca85b9e7493565e67957980086d9 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:45:16 +0000 Subject: [PATCH 161/414] Refs #11094 Resolve Coverity issues in clone --- .../MantidPlot/src/ApplicationWindow.cpp | 46 +++++++++++++++---- 1 file changed, 37 insertions(+), 9 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index c5353dbffa2d..38e52b2ce479 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -8651,18 +8651,26 @@ MdiSubWindow* ApplicationWindow::clone(MdiSubWindow* w) if (w->isA("MultiLayer")){ MultiLayer *g = dynamic_cast(w); + if(!g) + return NULL; nw = multilayerPlot(generateUniqueName(tr("Graph")), 0, g->getRows(), g->getCols()); - dynamic_cast(nw)->copy(g); + auto nwg = dynamic_cast(nw); + if(nwg) + nwg->copy(g); } else if (w->inherits("Table")){ Table *t = dynamic_cast(w); + if(!t) + return NULL; QString caption = generateUniqueName(tr("Table")); nw = newTable(caption, t->numRows(), t->numCols()); } else if (w->isA("Graph3D")){ Graph3D *g = dynamic_cast(w); + if(!g) + return NULL; if (!g->hasData()){ QApplication::restoreOverrideCursor(); QMessageBox::warning(this, tr("MantidPlot - Duplicate error"), tr("Empty 3D surface plots cannot be duplicated!"));//Mantid - return 0; + return NULL; } QString caption = generateUniqueName(tr("Graph")); @@ -8695,15 +8703,32 @@ MdiSubWindow* ApplicationWindow::clone(MdiSubWindow* w) if (status == MdiSubWindow::Maximized) nw->hide(); - dynamic_cast(nw)->copy(g); + auto g3d = dynamic_cast(nw); + if(g3d) + g3d->copy(g); customToolBars(nw); } else if (w->isA("Matrix")){ - nw = newMatrix((dynamic_cast(w))->numRows(), (dynamic_cast(w))->numCols()); - dynamic_cast(nw)->copy(dynamic_cast(w)); + auto matrix = dynamic_cast(w); + if(!matrix) + return NULL; + nw = newMatrix(matrix->numRows(), matrix->numCols()); + auto nwmatrix = dynamic_cast(nw); + if(nwmatrix) + nwmatrix->copy(matrix); } else if (w->isA("Note")){ + auto note = dynamic_cast(w); + if(!note) + return NULL; + nw = newNote(); - if (nw) - dynamic_cast(nw)->setText(dynamic_cast(w)->text()); + if(!nw) + return NULL; + + auto nwnote = dynamic_cast(nw); + if(!nwnote) + return NULL; + + nwnote->setText(note->text()); } if (nw){ @@ -8711,13 +8736,16 @@ MdiSubWindow* ApplicationWindow::clone(MdiSubWindow* w) if (status == MdiSubWindow::Maximized) nw->showMaximized(); } else if (w->isA("Graph3D")){ - dynamic_cast(nw)->setIgnoreFonts(true); + auto g3d = dynamic_cast(nw); + if(!g3d) + return NULL; + g3d->setIgnoreFonts(true); if (status != MdiSubWindow::Maximized){ nw->resize(w->size()); nw->showNormal(); } else nw->showMaximized(); - dynamic_cast(nw)->setIgnoreFonts(false); + g3d->setIgnoreFonts(false); } else { nw->resize(w->size()); nw->showNormal(); From d0887d2a9b2004814d4cdcd5b1f752b198933a10 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:45:51 +0000 Subject: [PATCH 162/414] Refs #11094 Resolve Coverity issues in custom3DActions --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 38e52b2ce479..a70d091c71ef 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -10877,6 +10877,8 @@ void ApplicationWindow::custom3DActions(MdiSubWindow *w) if (w && w->isA("Graph3D")) { Graph3D* plot = dynamic_cast(w); + if(!plot) + return; actionAnimate->setOn(plot->isAnimated()); actionPerspective->setOn(!plot->isOrthogonal()); switch(plot->plotStyle()) From f2d97c7e4d0233dd529e8988605fb1e52f7461fe Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:48:33 +0000 Subject: [PATCH 163/414] Refs #11094 Resolve Coverity issues in customizeTables --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index a70d091c71ef..13a5fb0997f1 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -3021,7 +3021,11 @@ void ApplicationWindow::customizeTables(const QColor& bgColor,const QColor& text QList windows = windowsList(); foreach(MdiSubWindow *w, windows){ if (w->inherits("Table")) - customTable(dynamic_cast(w)); + { + auto table = dynamic_cast(w); + if(table) + customTable(table); + } } } From 9e97a67a5d3cce55e02f1046ca1a8848e2e0e9c9 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:51:51 +0000 Subject: [PATCH 164/414] Refs #11094 Resolve Coverity issues in defineErrorBars --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 13a5fb0997f1..1eca59a84ae4 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -3895,7 +3895,11 @@ void ApplicationWindow::defineErrorBars(const QString& name, int type, const QSt if (!w) return; - Graph* g = dynamic_cast(w)->activeGraph(); + auto ml = dynamic_cast(w); + if(!ml) + return; + + Graph* g = ml->activeGraph(); if (!g) return; @@ -3913,6 +3917,9 @@ void ApplicationWindow::defineErrorBars(const QString& name, int type, const QSt } DataCurve *master_curve = dynamic_cast(g->curve(name)); + if(!master_curve) + return; + QString xColName = master_curve->xColumnName(); if (xColName.isEmpty()) return; From 604db70e1064ce1f8800dd18011dbfb1b3fb9067 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:54:13 +0000 Subject: [PATCH 165/414] Refs #11094 Resolve Coverity issues in deleteFitTables --- .../MantidPlot/src/ApplicationWindow.cpp | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 1eca59a84ae4..5ba78bc2d2d7 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -13645,12 +13645,24 @@ void ApplicationWindow::deleteFitTables() foreach(QWidget *ml, *mLst){ if (ml->isA("MultiLayer")){ - QList layers = dynamic_cast(ml)->layersList(); + auto cml = dynamic_cast(ml); + if(!cml) + continue; + + QList layers = cml->layersList(); foreach(Graph *g, layers){ QList curves = g->fitCurvesList(); foreach(QwtPlotCurve *c, curves){ - if (dynamic_cast(c)->type() != Graph::Function){ - Table *t = dynamic_cast(c)->table(); + auto curve = dynamic_cast(c); + if(!curve) + continue; + + if(curve->type() != Graph::Function) + { + auto dc = dynamic_cast(c); + if(!dc) + continue; + Table *t = dc->table(); if (!t) continue; From 331b218413ce71082f51a514b5e91dfed3180c79 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:56:51 +0000 Subject: [PATCH 166/414] Refs #11094 Resolve Coverity issues in deleteSelectedItems --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 5ba78bc2d2d7..677c25df8fab 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -9868,11 +9868,17 @@ void ApplicationWindow::deleteSelectedItems() folders->blockSignals(true); foreach(item, lst){ if (item->rtti() == FolderListItem::RTTI){ - Folder *f = dynamic_cast(item)->folder(); + auto fli = dynamic_cast(item); + if(!fli) + continue; + Folder *f = fli->folder(); if (deleteFolder(f)) delete item; - } else - dynamic_cast(item)->window()->close(); + } else { + auto wli = dynamic_cast(item); + if(wli) + wli->window()->close(); + } } folders->blockSignals(false); } From 7fed047a520869cabf244d7869b892415292e8a9 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 11:57:55 +0000 Subject: [PATCH 167/414] Refs #11094 Resolve Coverity issues in depending3DPlots --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 677c25df8fab..1d1a2d9b9eb2 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -10053,8 +10053,12 @@ QStringList ApplicationWindow::depending3DPlots(Matrix *m) QStringList plots; QList windows = windowsList(); foreach(MdiSubWindow *w, windows){ - if (w->isA("Graph3D") && dynamic_cast(w)->matrix() == m) - plots << w->objectName(); + if (w->isA("Graph3D")) + { + auto g3d = dynamic_cast(w); + if(g3d && g3d->matrix() == m) + plots << w->objectName(); + } } return plots; } From 999fbb70dd4109cd6b4e388b848802845770cc50 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 12:11:53 +0000 Subject: [PATCH 168/414] By default do not touch default instrument. Verified that first time setup and config UIs still work. Refs #11049 --- Code/Mantid/MantidPlot/src/ConfigDialog.cpp | 5 ++--- .../Indirect/IndirectTransmissionCalc.ui | 5 ----- .../Mantid/MantidQt/MantidWidgets/src/InstrumentSelector.cpp | 2 +- 3 files changed, 3 insertions(+), 9 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ConfigDialog.cpp b/Code/Mantid/MantidPlot/src/ConfigDialog.cpp index be208dd139f8..cafb5a066b9b 100644 --- a/Code/Mantid/MantidPlot/src/ConfigDialog.cpp +++ b/Code/Mantid/MantidPlot/src/ConfigDialog.cpp @@ -662,13 +662,12 @@ void ConfigDialog::initMantidPage() grid->addWidget(new QLabel("Facility"), 0, 0); grid->addWidget(facility, 0, 1); - defInstr = new MantidQt::MantidWidgets::InstrumentSelector(); + // Here we only want the default instrument updated if the user clicks Ok/Apply + defInstr->updateInstrumentOnSelection(false); grid->addWidget(new QLabel("Default Instrument"), 2, 0); grid->addWidget(defInstr, 2, 1); grid->setRowStretch(3,1); - //Here we only want the default instrument updated if the user clicks Ok/Apply - disconnect(defInstr, SIGNAL(currentIndexChanged(const QString&)), defInstr, SLOT(updateDefaultInstrument(const QString &))); //Ignore paraview. ckIgnoreParaView = new QCheckBox("Ignore ParaView"); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.ui index 32c2578b8209..44809830545b 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.ui @@ -169,11 +169,6 @@ - - MantidQt::MantidWidgets::InstrumentSelector - QComboBox -
MantidQtMantidWidgets/InstrumentSelector.h
-
MantidQt::MantidWidgets::IndirectInstrumentConfig QComboBox diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/InstrumentSelector.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/InstrumentSelector.cpp index 4b9a072704eb..166517650604 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/InstrumentSelector.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/InstrumentSelector.cpp @@ -37,7 +37,7 @@ namespace MantidWidgets */ InstrumentSelector::InstrumentSelector(QWidget *parent, bool init) : QComboBox(parent), m_changeObserver(*this, &InstrumentSelector::handleConfigChange), - m_techniques(), m_currentFacility(NULL), m_init(init), m_storeChanges(true), + m_techniques(), m_currentFacility(NULL), m_init(init), m_storeChanges(false), m_updateOnFacilityChange(true), m_selectedInstrument() { setEditable(false); From 9b374086281d1b5c193a40cf26677243075db429 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 12:14:14 +0000 Subject: [PATCH 169/414] Refs #11094 Resolve Coverity issues in dropFolderItems --- .../MantidPlot/src/ApplicationWindow.cpp | 31 +++++++++++++------ 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 1d1a2d9b9eb2..6e396166e42f 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -15161,21 +15161,27 @@ void ApplicationWindow::dropFolderItems(Q3ListViewItem *dest) if (!dest || draggedItems.isEmpty ()) return; - Folder *dest_f = dynamic_cast(dest)->folder(); + auto dfli = dynamic_cast(dest); + if(!dfli) + return; + Folder *dest_f = dfli->folder(); Q3ListViewItem *it; QStringList subfolders = dest_f->subfolders(); foreach(it, draggedItems){ if (it->rtti() == FolderListItem::RTTI){ - Folder *f = dynamic_cast(it)->folder(); + auto itfli = dynamic_cast(it); + if(!itfli) + continue; + Folder *f = itfli->folder(); FolderListItem *src = f->folderListItem(); if (dest_f == f){ QMessageBox::critical(this, "MantidPlot - Error", tr("Cannot move an object to itself!"));//Mantid return; } - if (dynamic_cast(dest)->isChildOf(src)){ + if (dfli->isChildOf(src)){ QMessageBox::critical(this,"MantidPlot - Error",tr("Cannot move a parent folder into a child folder!"));//Mantid draggedItems.clear(); folders->setCurrentItem(currentFolder()->folderListItem()); @@ -15192,17 +15198,22 @@ void ApplicationWindow::dropFolderItems(Q3ListViewItem *dest) QMessageBox::critical(this, tr("MantidPlot") +" - " + tr("Skipped moving folder"),//Mantid tr("The destination folder already contains a folder called '%1'! Folder skipped!").arg(f->objectName())); } else - moveFolder(src, dynamic_cast(dest)); + moveFolder(src, dfli); } else { if (dest_f == currentFolder()) return; - MdiSubWindow *w = dynamic_cast(it)->window(); - if (w){ - currentFolder()->removeWindow(w); - w->hide(); - dest_f->addWindow(w); - delete it; + auto wli = dynamic_cast(it); + if(wli) + { + MdiSubWindow *w = wli->window(); + if (w) + { + currentFolder()->removeWindow(w); + w->hide(); + dest_f->addWindow(w); + delete it; + } } } } From ddb2668056a13397eafbb660542112b08462b9b3 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 12:17:09 +0000 Subject: [PATCH 170/414] Refs #11094 Resolve Coverity issues in dependingPlots --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 6e396166e42f..05033e4d0cfe 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -10082,7 +10082,7 @@ QStringList ApplicationWindow::dependingPlots(const QString& name) } }else if (w->isA("Graph3D")){ auto g3d = dynamic_cast(w); - if (g3d && (g3d->formula()).contains(name,TRUE) && plots.contains(w->objectName())<=0) + if (g3d && (g3d->formula()).contains(name,TRUE) && !plots.contains(w->objectName())) plots << w->objectName(); } } From a50619eeeb1ae9c7aa120008aa7fe864620c05c9 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 12:18:57 +0000 Subject: [PATCH 171/414] Refs #11094 Resolve Coverity issues in editSurfacePlot --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 05033e4d0cfe..5b593a5ab154 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -2458,6 +2458,9 @@ void ApplicationWindow::editSurfacePlot() return; Graph3D* g = dynamic_cast(w); + if(!g) + return; + SurfaceDialog* sd = new SurfaceDialog(this); sd->setAttribute(Qt::WA_DeleteOnClose); From 07a1a269237c8b9dde5847edc683478db1ccba40 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 12:21:21 +0000 Subject: [PATCH 172/414] Refs #11094 Resolve Coverity issues in exportAllGraphs --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 5b593a5ab154..7ae97e918997 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -5922,6 +5922,8 @@ void ApplicationWindow::exportAllGraphs() if (w->isA("MultiLayer")) { plot3D = 0; plot2D = dynamic_cast(w); + if(!plot2D) + continue; if (plot2D->isEmpty()) { QApplication::restoreOverrideCursor(); QMessageBox::warning(this, tr("MantidPlot - Warning"),//Mantid @@ -5933,6 +5935,8 @@ void ApplicationWindow::exportAllGraphs() } else if (w->isA("Graph3D")) { plot2D = 0; plot3D = dynamic_cast(w); + if(!plot3D) + continue; } else continue; @@ -5943,8 +5947,7 @@ void ApplicationWindow::exportAllGraphs() QString msg = tr("A file called:

%1

already exists. ""Do you want to overwrite it?").arg(file_name); QMessageBox msgBox(QMessageBox::Question, tr("MantidPlot - Overwrite file?"), msg,//Mantid - QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::Cancel, - dynamic_cast(this)); + QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::Cancel, this); msgBox.exec(); switch(msgBox.standardButton(msgBox.clickedButton())){ case QMessageBox::Yes: From dbc9d4579b096711ccf4412c8ad7e5b624d968ba Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 12:27:32 +0000 Subject: [PATCH 173/414] Refs #11094 Resolve Coverity issues in exportAllTables --- .../MantidPlot/src/ApplicationWindow.cpp | 41 ++++++++----------- 1 file changed, 17 insertions(+), 24 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 7ae97e918997..df9466f3f6e4 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -6522,35 +6522,28 @@ void ApplicationWindow::exportAllTables(const QString& sep, bool colNames, bool if (w->inherits("Table") || w->isA("Matrix")){ QString fileName = dir + "/" + w->objectName() + ".txt"; QFile f(fileName); - if (f.exists(fileName) && confirmOverwrite){ + if (f.exists(fileName) && confirmOverwrite) + { QApplication::restoreOverrideCursor(); - switch(QMessageBox::question(this, tr("MantidPlot - Overwrite file?"),//Mantid + auto result = QMessageBox::question(this, tr("MantidPlot - Overwrite file?"), tr("A file called:

%1

already exists. " - "Do you want to overwrite it?").arg(fileName), tr("&Yes"), tr("&All"), tr("&Cancel"), 0, 1)) - { - case 0: - if (w->inherits("Table")) - success = (dynamic_cast(w))->exportASCII(fileName, sep, colNames, colComments, expSelection); - else if (w->isA("Matrix")) - success = (dynamic_cast(w))->exportASCII(fileName, sep, expSelection); - break; + "Do you want to overwrite it?").arg(fileName), + tr("&Yes"), tr("&All"), tr("&Cancel"), 0, 1); - case 1: + if(result == 1) confirmOverwrite = false; - if (w->inherits("Table")) - success = (dynamic_cast(w))->exportASCII(fileName, sep, colNames, colComments, expSelection); - else if (w->isA("Matrix")) - success = (dynamic_cast(w))->exportASCII(fileName, sep, expSelection); - break; - - case 2: + else if(result == 2) return; - break; - } - } else if (w->inherits("Table")) - success = (dynamic_cast(w))->exportASCII(fileName, sep, colNames, colComments, expSelection); - else if (w->isA("Matrix")) - success = (dynamic_cast(w))->exportASCII(fileName, sep, expSelection); + + } + + auto table = dynamic_cast(w); + auto matrix = dynamic_cast(w); + + if(table) + success = table->exportASCII(fileName, sep, colNames, colComments, expSelection); + else if(matrix) + success = matrix->exportASCII(fileName, sep, expSelection); if (!success) break; From db2301e388d687e2003fdf0d1fcadcaa5f3c223a Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:13:31 +0000 Subject: [PATCH 174/414] Refs #11094 Resolve Coverity issues in exportPDF --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index df9466f3f6e4..2beb4f8c1fe1 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -7660,7 +7660,9 @@ void ApplicationWindow::exportPDF() if (!w) return; - if (w->isA("MultiLayer") && (dynamic_cast(w))->isEmpty()){ + auto ml = dynamic_cast(w); + + if (w->isA("MultiLayer") && ml && ml->isEmpty()) { QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid tr("

There are no plot layers available in this window.

")); return; From 68015ac732e749fb37a3c492a648465d534ca322 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:14:15 +0000 Subject: [PATCH 175/414] Refs #11094 Resolve Coverity issues in folderItemChanged --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 2beb4f8c1fe1..a961e2d2d9aa 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -14876,7 +14876,13 @@ void ApplicationWindow::folderItemChanged(Q3ListViewItem *it) return; it->setOpen(true); - changeFolder (dynamic_cast(it)->folder()); + + auto fli = dynamic_cast(it); + + if(!fli) + return; + + changeFolder(fli->folder()); folders->setFocus(); } From 5c2e27556cc4afa6fd27bb1dc4e329c3c763757e Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:15:39 +0000 Subject: [PATCH 176/414] Refs #11094 Resolve Coverity issues in folderItemDoubleClicked --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index a961e2d2d9aa..5dca54916abb 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -14866,7 +14866,11 @@ void ApplicationWindow::folderItemDoubleClicked(Q3ListViewItem *it) if (!it || it->rtti() != FolderListItem::RTTI) return; - FolderListItem *item = dynamic_cast(it)->folder()->folderListItem(); + auto fli = dynamic_cast(it); + if(!fli) + return; + + FolderListItem *item = fli->folder()->folderListItem(); folders->setCurrentItem(item); } From 2474d52321b37122269146b36d0569206ae1c7ce Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:16:44 +0000 Subject: [PATCH 177/414] Refs #11094 Resolve Coverity issues in goToRow --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 5dca54916abb..f4bdaee93ddc 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -15368,10 +15368,13 @@ void ApplicationWindow::goToRow() if ( !ok ) return; - if (w->inherits("Table")) - dynamic_cast(w)->goToRow(row); - else if (w->isA("Matrix")) - (dynamic_cast(w))->goToRow(row); + auto table = dynamic_cast(w); + auto matrix = dynamic_cast(w); + + if(table) + table->goToRow(row); + else if(matrix) + matrix->goToRow(row); } } From ed90dbb22b20d56ce6dc4055f05a62a49eb5a36e Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:17:49 +0000 Subject: [PATCH 178/414] Refs #11094 Resolve Coverity issues in hideSelectedWindows --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index f4bdaee93ddc..41c637efb7e7 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -15795,7 +15795,11 @@ void ApplicationWindow::hideSelectedWindows() folders->blockSignals(true); foreach(item, lst){ if (item->rtti() != FolderListItem::RTTI) - hideWindow(dynamic_cast(item)->window()); + { + auto wli = dynamic_cast(item); + if(wli) + hideWindow(wli->window()); + } } folders->blockSignals(false); } From d9b0d184340b65e9964228e85334727305750b8c Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:18:25 +0000 Subject: [PATCH 179/414] Refs #11094 Resolve Coverity issues in insert3DMatrixPlot --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 41c637efb7e7..312faa3ab870 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -2424,7 +2424,10 @@ void ApplicationWindow::insert3DMatrixPlot(const QString& matrix_name) if (!w) return; - dynamic_cast(w)->addMatrixData(matrix(matrix_name)); + auto g3d = dynamic_cast(w); + if(g3d) + g3d->addMatrixData(matrix(matrix_name)); + emit modified(); } From d966782e299d9b8de5cc8564b2e3726862de3fbd Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:19:01 +0000 Subject: [PATCH 180/414] Refs #11094 Resolve Coverity issues in insertNew3DData --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 312faa3ab870..c43ea8a3a8bb 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -2437,7 +2437,9 @@ void ApplicationWindow::insertNew3DData(const QString& colName) if (!w) return; - dynamic_cast(w)->insertNewData(table(colName),colName); + auto g3d = dynamic_cast(w); + if(g3d) + g3d->insertNewData(table(colName),colName); emit modified(); } From 02b3e12595201bc7cba2216194fff0b2ce00f979 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:19:50 +0000 Subject: [PATCH 181/414] Refs #11094 Resolve Coverity issues in integrate --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index c43ea8a3a8bb..530493fccd81 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -11833,11 +11833,16 @@ void ApplicationWindow::integrate() if (w->isA("MultiLayer")) analysis(Integrate); - else if (w->isA("Matrix")){ + else if (w->isA("Matrix")) + { + auto matrix = dynamic_cast(w); + if(!matrix) + return; + QDateTime dt = QDateTime::currentDateTime (); QString info = dt.toString(Qt::LocalDate); info += "\n" + tr("Integration of %1 from zero is").arg(QString(w->objectName())) + ":\t"; - info += QString::number((dynamic_cast(w))->integrate()) + "\n"; + info += QString::number(matrix->integrate()) + "\n"; info += "-------------------------------------------------------------\n"; currentFolder()->appendLogInfo(info); showResults(true); From 2596e11322705a378806d6552dce1672a26808b6 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:20:48 +0000 Subject: [PATCH 182/414] Refs #11094 Resolve Coverity issues in minimizeWindow --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 530493fccd81..f171ae235af8 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -9086,8 +9086,10 @@ void ApplicationWindow::maximizeWindow(MdiSubWindow *w) void ApplicationWindow::minimizeWindow(MdiSubWindow *w) { + auto wli = dynamic_cast(lv->currentItem()); + if (!w) - w = (dynamic_cast(lv->currentItem()))->window(); + w = wli->window(); if (!w) return; From fd0a7f83e72696bb8e0f36e4fcbdb6b5b9f2eefc Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:21:56 +0000 Subject: [PATCH 183/414] Refs #11094 Resolve Coverity issues in multilayerDependencies --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index f171ae235af8..e02f74b8281a 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -10100,14 +10100,17 @@ QStringList ApplicationWindow::dependingPlots(const QString& name) QStringList ApplicationWindow::multilayerDependencies(QWidget *w) { QStringList tables; - MultiLayer *g=dynamic_cast(w); + MultiLayer* g = dynamic_cast(w); + if(!g) + return tables; + QList layers = g->layersList(); foreach(Graph *ag, layers){ QStringList onPlot=ag->curvesList(); for (int j=0; j Date: Mon, 16 Feb 2015 13:25:44 +0000 Subject: [PATCH 184/414] Refs #11094 Resolve Coverity issues in print --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index e02f74b8281a..708d70029a02 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -7702,7 +7702,8 @@ void ApplicationWindow::print() if (!w) return; - if (w->isA("MultiLayer") && (dynamic_cast(w))->isEmpty()){ + auto ml = dynamic_cast(w); + if (w->isA("MultiLayer") && ml && ml->isEmpty()){ QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid tr("

There are no plot layers available in this window.

")); return; From 09414e086d164d3a511191df2de3184dab88dc11 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:27:14 +0000 Subject: [PATCH 185/414] Refs #11094 Resolve Coverity issues in projectFolder --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 708d70029a02..13942dd9b110 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -6093,7 +6093,11 @@ void ApplicationWindow::restoreWindowGeometry(ApplicationWindow *app, MdiSubWind Folder* ApplicationWindow::projectFolder() const { - return dynamic_cast(folders->firstChild())->folder(); + auto fli = dynamic_cast(folders->firstChild()); + if(fli) + return fli->folder(); + else + throw std::runtime_error("Couldn't retrieve project folder"); } bool ApplicationWindow::saveProject(bool compress) From 29ce124d0719b7d41d21f33a9c6db57240a0a391 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 13:31:54 +0000 Subject: [PATCH 186/414] Fix file loading on Muon Analysis UI Refs #11049 --- .../Mantid/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp index 235660a21c44..22c2f7fd75ae 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp @@ -703,6 +703,9 @@ MatrixWorkspace_sptr MuonAnalysis::getPeriodWorkspace(PeriodType periodType, Wor */ void MuonAnalysis::userSelectInstrument(const QString& prefix) { + // Set file browsing to current instrument + m_uiForm.mwRunFiles->setInstrumentOverride(prefix); + if ( prefix != m_curInterfaceSetup ) { runClearGroupingButton(); From c69586722df29ac8bc9df5d262e916c05198baca Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 13:43:23 +0000 Subject: [PATCH 187/414] Fix file loading on Direct Convert to Energy Refs #11049 --- .../CustomInterfaces/src/DirectConvertToEnergy.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp index a527a211365f..2220d18b31e6 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp @@ -233,6 +233,14 @@ void DirectConvertToEnergy::instrumentLoadingDone(bool error) */ void DirectConvertToEnergy::userSelectInstrument(const QString& prefix) { + // Search for files for the current selected instrument + m_uiForm.runFiles->setInstrumentOverride(prefix); + m_uiForm.mapFile->setInstrumentOverride(prefix); + m_uiForm.whiteBeamFile->setInstrumentOverride(prefix); + m_uiForm.absRunFiles->setInstrumentOverride(prefix); + m_uiForm.absMapFile->setInstrumentOverride(prefix); + m_uiForm.absWhiteFile->setInstrumentOverride(prefix); + if ( prefix != m_curInterfaceSetup ) { // Remove the old empty instrument workspace if it is there From 824839e0ec3a27bb154bbc8a7a06312432f498ea Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Mon, 16 Feb 2015 14:01:03 +0000 Subject: [PATCH 188/414] Fix bugs with cleaning logic in Windows build script Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript.bat | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript.bat b/Code/Mantid/Build/Jenkins/buildscript.bat index 151378aa1c70..694da2eb62c4 100755 --- a/Code/Mantid/Build/Jenkins/buildscript.bat +++ b/Code/Mantid/Build/Jenkins/buildscript.bat @@ -33,19 +33,20 @@ if NOT DEFINED MANTID_DATA_STORE ( ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Check job requirements from the name ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -if "%JOB_NAME%"=="%JOB_NAME:clean=%" ( +set CLEANBUILD= +set BUILDPKG= +if not "%JOB_NAME%" == "%JOB_NAME:clean=%" ( set CLEANBUILD=yes set BUILDPKG=yes ) if EXIST %WORKSPACE%\build\CMakeCache.txt ( - TYPE %WORKSPACE%\build\CMakeCache.txt | FINDSTR "Code/Mantid/TestingTools/cxxtest" - if %ERRORLEVEL% EQU 0 ( + FINDSTR "Code/Mantid/TestingTools/cxxtest" %WORKSPACE%\build\CMakeCache.txt && ( rmdir /S /Q %WORKSPACE%\build ) ) -if "%JOB_NAME%"=="%JOB_NAME:pull_requests=%" ( +if not "%JOB_NAME%" == "%JOB_NAME:pull_requests=%" ( set BUILDPKG=yes ) @@ -60,7 +61,7 @@ if "%BUILDPKG%" EQU "yes" ( ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Setup the build directory ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -if "%CLEANBUILD%" EQU "yes" ( +if "%CLEANBUILD%" == "yes" ( rmdir /S /Q %WORKSPACE%\build ) md %WORKSPACE%\build From e3c261089a74ae38d067612fd5317b9f42bdb070 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Mon, 16 Feb 2015 14:01:25 +0000 Subject: [PATCH 189/414] fix 1075577-80, avoid leak using shared_ptr, re #11060 --- .../src/CoordTransformDistanceParser.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Code/Mantid/Framework/MDEvents/src/CoordTransformDistanceParser.cpp b/Code/Mantid/Framework/MDEvents/src/CoordTransformDistanceParser.cpp index 42de3c7b0be4..38a66a2f0c2d 100644 --- a/Code/Mantid/Framework/MDEvents/src/CoordTransformDistanceParser.cpp +++ b/Code/Mantid/Framework/MDEvents/src/CoordTransformDistanceParser.cpp @@ -51,32 +51,33 @@ Mantid::API::CoordTransform *CoordTransformDistanceParser::createTransform( InDimParameterParser inDimParamParser; Poco::XML::Element *parameter = dynamic_cast(parameters->item(0)); - Mantid::API::InDimParameter *inDimParameter = - inDimParamParser.createWithoutDelegation(parameter); + boost::shared_ptr + inDimParameter(inDimParamParser.createWithoutDelegation(parameter)); // Parse the out dimension parameter. OutDimParameterParser outDimParamParser; parameter = dynamic_cast(parameters->item(1)); - Mantid::API::OutDimParameter *outDimParameter = - outDimParamParser.createWithoutDelegation(parameter); + boost::shared_ptr + outDimParameter(outDimParamParser.createWithoutDelegation(parameter)); UNUSED_ARG(outDimParameter); // not actually used as an input. // Parse the coordinate centre parameter. CoordCenterParser coordCenterParser; parameter = dynamic_cast(parameters->item(2)); - Mantid::MDEvents::CoordCenterVectorParam *coordCenterParam = - coordCenterParser.createWithoutDelegation(parameter); + boost::shared_ptr + coordCenterParam(coordCenterParser.createWithoutDelegation(parameter)); // Parse the dimensions used parameter. DimsUsedParser dimsUsedParser; parameter = dynamic_cast(parameters->item(3)); - Mantid::MDEvents::DimensionsUsedVectorParam *dimsUsedVecParm = - dimsUsedParser.createWithoutDelegation(parameter); + boost::shared_ptr + dimsUsedVecParm(dimsUsedParser.createWithoutDelegation(parameter)); ////Generate the coordinate transform and return CoordTransformDistance *transform = new CoordTransformDistance( inDimParameter->getValue(), coordCenterParam->getPointerToStart(), dimsUsedVecParm->getPointerToStart()); + return transform; } From 6c16ad0f4fd45b1167ff8115b30fe261891b6dab Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Mon, 16 Feb 2015 14:02:18 +0000 Subject: [PATCH 190/414] fix 1075581-83, avoid leak using shared_ptr, re #11060 --- .../MDEvents/src/CoordTransformAffineParser.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Code/Mantid/Framework/MDEvents/src/CoordTransformAffineParser.cpp b/Code/Mantid/Framework/MDEvents/src/CoordTransformAffineParser.cpp index 26d2419fd53c..b2f92cbb2517 100644 --- a/Code/Mantid/Framework/MDEvents/src/CoordTransformAffineParser.cpp +++ b/Code/Mantid/Framework/MDEvents/src/CoordTransformAffineParser.cpp @@ -49,20 +49,20 @@ Mantid::API::CoordTransform *CoordTransformAffineParser::createTransform( InDimParameterParser inDimParser; Poco::XML::Element *parameter = dynamic_cast(parameters->item(0)); - Mantid::API::InDimParameter *inDim = - inDimParser.createWithoutDelegation(parameter); + boost::shared_ptr + inDim(inDimParser.createWithoutDelegation(parameter)); // Add output dimension parameter. OutDimParameterParser outDimParser; parameter = dynamic_cast(parameters->item(1)); - Mantid::API::OutDimParameter *outDim = - outDimParser.createWithoutDelegation(parameter); + boost::shared_ptr + outDim(outDimParser.createWithoutDelegation(parameter)); // Add affine matrix parameter. AffineMatrixParameterParser affineMatrixDimParser; parameter = dynamic_cast(parameters->item(2)); - AffineMatrixParameter *affineMatrix = - affineMatrixDimParser.createParameter(parameter); + boost::shared_ptr + affineMatrix(affineMatrixDimParser.createParameter(parameter)); // Generate the coordinate transform with the matrix and return. CoordTransformAffine *transform = From cfd08d21be2b4386922c9586a07e5db9238ec566 Mon Sep 17 00:00:00 2001 From: Pete Peterson Date: Mon, 16 Feb 2015 09:14:44 -0500 Subject: [PATCH 191/414] Updating comments --- Code/Mantid/Build/Jenkins/jenkins-slave.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Build/Jenkins/jenkins-slave.sh b/Code/Mantid/Build/Jenkins/jenkins-slave.sh index 02596bb47456..b728187b1cc7 100755 --- a/Code/Mantid/Build/Jenkins/jenkins-slave.sh +++ b/Code/Mantid/Build/Jenkins/jenkins-slave.sh @@ -7,7 +7,9 @@ # The settings at the top must be filled in for each slave. ##################################################################### # Crontab setting should be something like -# 0,30 * * * * /home/builder/jenkins-linode nodename secret +# 0,30 * * * * /home/builder/jenkins-linode/jenkins-slave.sh nodename secret +# or (on mac) +# 0,30 * * * * /Users/builder/jenkins-linode/jenkins-slave.sh nodename secret ##################################################################### # User configuration ##################################################################### From 3c5782ecc51cf01555cbd2b507d089d06b2cf77d Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:30:55 +0000 Subject: [PATCH 192/414] Refs #11094 Resolve Coverity issues in recalculateTable --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 13942dd9b110..1c8b12260afd 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -6669,10 +6669,13 @@ void ApplicationWindow::recalculateTable() if (!w) return; - if (w->inherits("Table")) - (dynamic_cast(w))->calculate(); - else if (w->isA("Matrix")) - (dynamic_cast(w))->calculate(); + auto table = dynamic_cast(w); + auto matrix = dynamic_cast(w); + + if(table) + table->calculate(); + else if(matrix) + matrix->calculate(); } void ApplicationWindow::sortActiveTable() From 3d75bf589d33814faf7a633c3f1b897bb9b7fefb Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:34:50 +0000 Subject: [PATCH 193/414] Refs #11094 Resolve Coverity issues in redo --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 1c8b12260afd..949807483047 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -8811,10 +8811,14 @@ void ApplicationWindow::redo() QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - if (qobject_cast(w)) - dynamic_cast(w)->editor()->redo(); - else if (qobject_cast(w)){ - QUndoStack *stack = (dynamic_cast(w))->undoStack(); + auto note = dynamic_cast(w); + auto matrix = dynamic_cast(w); + + if(note) + note->editor()->redo(); + else if(matrix) + { + QUndoStack *stack = matrix->undoStack(); if (stack && stack->canRedo()) stack->redo(); } From 2f3546c5eab0239c236526ada88f3176f71e6cfc Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:36:33 +0000 Subject: [PATCH 194/414] Refs #11094 Resolve Coverity issues in remove3DMatrixPlots --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 949807483047..ff62968ada33 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -2278,10 +2278,13 @@ void ApplicationWindow::remove3DMatrixPlots(Matrix *m) QList windows = windowsList(); foreach(MdiSubWindow *w, windows){ - if (w->isA("Graph3D") && dynamic_cast(w)->matrix() == m) - dynamic_cast(w)->clearData(); - else if (w->isA("MultiLayer")){ - QList layers = dynamic_cast(w)->layersList(); + auto g3d = dynamic_cast(w); + if(g3d && g3d->matrix() == m) + g3d->clearData(); + auto ml = dynamic_cast(w); + + if(ml) { + QList layers = ml->layersList(); foreach(Graph *g, layers){ for (int i=0; icurves(); i++){ if (g->curveType(i) == Graph::Histogram){ From 7edfda6c34d4f5691eb3d167cef78f56ea8327b9 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:39:09 +0000 Subject: [PATCH 195/414] Refs #11094 Resolve Coverity issues in removeErrorBars --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index ff62968ada33..0d912257e2b6 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -3858,6 +3858,9 @@ void ApplicationWindow::removeErrorBars() return; MultiLayer* plot = dynamic_cast(w); + if(!plot) + return; + if (plot->isEmpty()){ QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid tr("

There are no plot layers available in this window.

" @@ -3892,7 +3895,11 @@ void ApplicationWindow::removeErrorBars(const QString& name) if (!w) return; - Graph* g = dynamic_cast(w)->activeGraph(); + auto ml = dynamic_cast(w); + if(!ml) + return; + + Graph* g = ml->activeGraph(); if (!g) return; From a2d141d433990f6d0c64fabdb67153576f06344d Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:40:30 +0000 Subject: [PATCH 196/414] Refs #11094 Resolve Coverity issues in removeWindowFromLists --- .../MantidPlot/src/ApplicationWindow.cpp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 0d912257e2b6..4b8e244e5d9d 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -9144,23 +9144,28 @@ void ApplicationWindow::removeWindowFromLists(MdiSubWindow* w) QString caption = w->objectName(); if (w->inherits("Table")){ - Table* m=dynamic_cast(w); + Table* m = dynamic_cast(w); + if(!m) + return; for (int i=0; inumCols(); i++){ QString name=m->colName(i); removeCurves(name); } } else if (w->isA("MultiLayer")){ - MultiLayer *ml = dynamic_cast(w); + MultiLayer *ml = dynamic_cast(w); + if(!ml) + return; Graph *g = ml->activeGraph(); - if (g) - btnPointer->setChecked(true); + if(!g) + return; + btnPointer->setChecked(true); } else if (w->isA("Matrix")) { - remove3DMatrixPlots(dynamic_cast(w)); + auto matrix = dynamic_cast(w); + if(matrix) + remove3DMatrixPlots(matrix); } - else { } - if (hiddenWindows->contains(w)) { hiddenWindows->takeAt(hiddenWindows->indexOf(w)); From c6c55b6ee46cb5834f8f475059d0de43ff97741c Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:41:14 +0000 Subject: [PATCH 197/414] Refs #11094 Resolve Coverity issues in setGraphDefaultSettings --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 4b8e244e5d9d..a2c626133bc0 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -4212,7 +4212,10 @@ void ApplicationWindow::setGraphDefaultSettings(bool autoscale, bool scaleFonts, foreach(MdiSubWindow *w, windows){ if (w->isA("MultiLayer")) { - QList layers = dynamic_cast(w)->layersList(); + auto ml = dynamic_cast(w); + if(!ml) + continue; + QList layers = ml->layersList(); foreach(Graph *g, layers) { g->enableAutoscaling(autoscale2DPlots); From 884fdea8f73e1869bc8f73a846b257cd3df6439b Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:42:08 +0000 Subject: [PATCH 198/414] Refs #11094 Resolve Coverity issues in setMatrixUndoStackSize --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index a2c626133bc0..2bcb7aa9b7c9 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -16537,7 +16537,10 @@ void ApplicationWindow::setMatrixUndoStackSize(int size) QList folderWindows = f->windowsList(); foreach(MdiSubWindow *w, folderWindows){ if (w->isA("Matrix")){ - QUndoStack *stack = (dynamic_cast(w))->undoStack(); + auto matrix = dynamic_cast(w); + if(!matrix) + continue; + QUndoStack *stack = matrix->undoStack(); if (!stack->count())// undo limit can only be changed for empty stacks stack->setUndoLimit(size); } From c9420b312bc44a4c69470cc52aaeb773cd6dbf13 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:43:26 +0000 Subject: [PATCH 199/414] Refs #11094 Resolve Coverity issues in setPlot3DOptions --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 2bcb7aa9b7c9..d5806bd701d9 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -12045,6 +12045,8 @@ void ApplicationWindow::setPlot3DOptions() foreach(MdiSubWindow *w, windows){ if (w->isA("Graph3D")){ Graph3D *g = dynamic_cast(w); + if(!g) + continue; g->setOrthogonal(orthogonal3DPlots); g->setAutoscale(autoscale3DPlots); g->setAntialiasing(smooth3DMesh); From e11fb508498a15d5f7cdee6028fd8ce79a85f374 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:44:26 +0000 Subject: [PATCH 200/414] Refs #11094 Resolve Coverity issues in showAllFolderWindows --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index d5806bd701d9..b97298571e41 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -14666,10 +14666,15 @@ void ApplicationWindow::showAllFolderWindows() FolderListItem *fi = currentFolder()->folderListItem(); FolderListItem *item = dynamic_cast(fi->firstChild()); + if(!item) + return; int initial_depth = item->depth(); while (item && item->depth() >= initial_depth) {// show/hide windows in all subfolders - lst = dynamic_cast(item->folder())->windowsList(); + auto fld = dynamic_cast(item->folder()); + if(!fld) + break; + lst = fld->windowsList(); foreach(MdiSubWindow *w, lst){ if (w && show_windows_policy == SubFolders){ updateWindowLists(w); From 4a3c6ee85be11765e59718173b509d9e7deb7a21 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:47:19 +0000 Subject: [PATCH 201/414] Refs #11094 Resolve Coverity issues in showAxisDialog --- .../MantidPlot/src/ApplicationWindow.cpp | 30 +++++-------------- 1 file changed, 8 insertions(+), 22 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index b97298571e41..71b8e656b646 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -7209,32 +7209,18 @@ void ApplicationWindow::showAxisDialog() QDialog* gd = showScaleDialog(); if (gd && plot->isA("MultiLayer")) { - MultiLayer* ml; - try - { - ml = dynamic_cast(plot); - } - catch(std::runtime_error& ) - { - g_log.error() << "Failed to open axis dialog for multi layer plot"; + MultiLayer* ml = dynamic_cast(plot); + if (!ml || (ml && !ml->layers())) return; - } - if (ml && ml->layers()) - dynamic_cast(gd)->showAxesPage(); + + auto ad = dynamic_cast(gd); + if(ad) + ad->showAxesPage(); } else if (gd && plot->isA("Graph3D")) { - Plot3DDialog* p3d; - try - { - p3d = dynamic_cast(gd); - } - catch(std::runtime_error& ) - { - g_log.error() << "Failed to open axis dialog for multi layer plot"; - return; - } - if (p3d) + Plot3DDialog* p3d = dynamic_cast(gd); + if(p3d) p3d->showAxisTab(); } } From 8434e6b5953c02577251eeece32bad73ef68e4f3 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:48:01 +0000 Subject: [PATCH 202/414] Refs #11094 Resolve Coverity issues in showAxisTitleDialog --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 71b8e656b646..5d2470c13b92 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -6506,7 +6506,11 @@ void ApplicationWindow::showAxisTitleDialog() if (!w) return; - Graph* g = dynamic_cast(w)->activeGraph(); + auto ml = dynamic_cast(w); + if(!ml) + return; + + Graph* g = ml->activeGraph(); if (!g) return; From 54d522ca934314b31876952ffe0cf89f29fc578d Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:50:25 +0000 Subject: [PATCH 203/414] Refs #11094 Resolve Coverity issues in showCurveWorksheet --- .../MantidPlot/src/ApplicationWindow.cpp | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 5d2470c13b92..6a5f36f7c4b9 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -7489,20 +7489,17 @@ void ApplicationWindow::showCurveWorksheet(Graph *g, int curveIndex) if (!it) return; - if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram) - { - Spectrogram *sp = dynamic_cast(it); - if (sp->matrix()) - sp->matrix()->showMaximized(); - } - else if (dynamic_cast(it)->type() == Graph::Function) - { - g->createTable(dynamic_cast(it)); - } - else - { + + auto sp = dynamic_cast(it); + auto pc = dynamic_cast(it); + + if(sp && sp->matrix()) + sp->matrix()->showMaximized(); + if(pc && pc->type() == Graph::Function) + g->createTable(pc); + + if(!pc && !sp) showTable(it->title().text()); - } } void ApplicationWindow::showCurveWorksheet() From 9a361fc31ba03ce4a0619864994891af84a446f2 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:51:23 +0000 Subject: [PATCH 204/414] Refs #11094 Resolve Coverity issues in showCurvesDialog --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 6a5f36f7c4b9..92b015c133a4 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -6396,14 +6396,18 @@ void ApplicationWindow::showCurvesDialog() if (!w) return; - if (dynamic_cast(w)->isEmpty()){ + auto ml = dynamic_cast(w); + if(!ml) + return; + + if (ml->isEmpty()){ QMessageBox::warning(this,tr("MantidPlot - Error"),//Mantid tr("

There are no plot layers available in this window.

" "

Please add a layer and try again!

")); return; } - Graph* g = dynamic_cast(w)->activeGraph(); + Graph* g = ml->activeGraph(); if (!g) return; From aaeecfe453284dfb0fd517f9c9d6eadc89274953 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:52:32 +0000 Subject: [PATCH 205/414] Refs #11094 Resolve Coverity issues in showFolderPopupMenu --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 92b015c133a4..0ce36218c82f 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -14485,7 +14485,12 @@ void ApplicationWindow::showFolderPopupMenu(Q3ListViewItem *it, const QPoint &p, cm.insertItem(tr("&Find..."), this, SLOT(showFindDialogue())); cm.insertSeparator(); cm.insertItem(tr("App&end Project..."), this, SLOT(appendProject())); - if (dynamic_cast(it)->folder()->parent()) + + auto fli = dynamic_cast(it); + if(!fli) + return; + + if (fli->folder()->parent()) cm.insertItem(tr("Save &As Project..."), this, SLOT(saveAsProject())); else cm.insertItem(tr("Save Project &As..."), this, SLOT(saveProjectAs())); @@ -14498,7 +14503,7 @@ void ApplicationWindow::showFolderPopupMenu(Q3ListViewItem *it, const QPoint &p, cm.insertSeparator(); } - if (dynamic_cast(it)->folder()->parent()) + if (fli->folder()->parent()) { cm.insertItem(getQPixmap("close_xpm"), tr("&Delete Folder"), this, SLOT(deleteFolder()), Qt::Key_F8); cm.insertItem(tr("&Rename"), this, SLOT(startRenameFolder()), Qt::Key_F2); From f16b0cd722d3e2efa20a9307b908d6d41873e9d1 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:56:53 +0000 Subject: [PATCH 206/414] Refs #11094 Resolve Coverity issues in showGraphContextMenu --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 0ce36218c82f..8b7314079726 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -10146,10 +10146,15 @@ void ApplicationWindow::showGraphContextMenu() QMenu cm(this); Graph* ag = dynamic_cast(plot->activeGraph()); + if(!ag) + return; PlotToolInterface* tool = ag->activeTool(); if (dynamic_cast(tool)) { - dynamic_cast(tool)->prepareContextMenu(cm); + auto ppt = dynamic_cast(tool); + if(!ppt) + return; + ppt->prepareContextMenu(cm); cm.exec(QCursor::pos()); return; } From ded79973b2f13f2181059bcfa207d4c37ea8b241 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 13:57:28 +0000 Subject: [PATCH 207/414] Refs #11094 Resolve Coverity issues in showPlotAssociations --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 8b7314079726..56424d704a3e 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -6473,7 +6473,11 @@ AssociationsDialog* ApplicationWindow::showPlotAssociations(int curve) if (!w) return 0; - Graph *g = dynamic_cast(w)->activeGraph(); + auto ml = dynamic_cast(w); + if(!ml) + return 0; + + Graph *g = ml->activeGraph(); if (!g) return 0; From bac19413f710e6455379e8e0b7f6d6ca3999d871 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 14:00:03 +0000 Subject: [PATCH 208/414] Refs #11094 Resolve Coverity issues in showScaleDialog --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 56424d704a3e..8b14c8dc1ea3 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -7251,20 +7251,14 @@ QDialog* ApplicationWindow::showScaleDialog() return 0; if (w->isA("MultiLayer")){ - MultiLayer* ml; - try - { - ml = dynamic_cast(w); - } - catch(std::runtime_error& ) - { - g_log.error() << "Failed to open scale dialog for multi layer plot"; - return 0; - } + auto ml = dynamic_cast(w); if (!ml || ml->isEmpty()) return 0; - Graph* g = dynamic_cast(w)->activeGraph(); + Graph* g = ml->activeGraph(); + if(!g) + return 0; + if (g->isPiePlot()){ QMessageBox::warning(this, tr("MantidPlot - Warning"), tr("This functionality is not available for pie plots!"));//Mantid return 0; From 80935443e31aed512a39623ed666120a41c7fb9e Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 14:00:42 +0000 Subject: [PATCH 209/414] Refs #11094 Resolve Coverity issues in showSelectedWindows --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 8b14c8dc1ea3..6e080f404e60 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -15867,7 +15867,11 @@ void ApplicationWindow::showSelectedWindows() folders->blockSignals(true); foreach(item, lst){ if (item->rtti() != FolderListItem::RTTI) - activateWindow(dynamic_cast(item)->window()); + { + auto wli = dynamic_cast(item); + if(wli) + activateWindow(wli->window()); + } } folders->blockSignals(false); } From 73905a87a99d0e51990d466e9399b7c4fac05c6a Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 14:01:18 +0000 Subject: [PATCH 210/414] Refs #11094 Resolve Coverity issues in showTitleDialog --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 6e080f404e60..899df1726e93 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -6495,8 +6495,12 @@ void ApplicationWindow::showTitleDialog() return; if (w->isA("MultiLayer")){ - Graph* g = dynamic_cast(w)->activeGraph(); - if (g){ + auto ml = dynamic_cast(w); + if(!ml) + return; + + Graph* g = ml->activeGraph(); + if (g) { TextDialog* td= new TextDialog(TextDialog::LayerTitle, this,0); td->setGraph(g); td->exec(); From 4464ba428582f0bcc78175aa6109288043676b3d Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 14:04:02 +0000 Subject: [PATCH 211/414] Refs #11094 Resolve Coverity issues in showWindowContextMenu --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 899df1726e93..c9aa8e42b7e2 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -10259,6 +10259,8 @@ void ApplicationWindow::showWindowContextMenu() QMenu plot3D(this); if (w->isA("MultiLayer")){ MultiLayer *g = dynamic_cast(w); + if(!g) + return; if (lastCopiedLayer){ cm.insertItem(getQPixmap("paste_xpm"), tr("&Paste Layer"), this, SLOT(pasteSelection())); cm.insertSeparator(); @@ -10280,6 +10282,8 @@ void ApplicationWindow::showWindowContextMenu() cm.addAction(actionCloseWindow); } else if (w->isA("Graph3D")){ Graph3D *g=dynamic_cast(w); + if(!g) + return; if (!g->hasData()){ cm.insertItem(tr("3D &Plot"), &plot3D); plot3D.addAction(actionAdd3DData); @@ -10306,6 +10310,8 @@ void ApplicationWindow::showWindowContextMenu() cm.addAction(actionCloseWindow); } else if (w->isA("Matrix")) { Matrix *t = dynamic_cast(w); + if(!t) + return; if (t->viewType() == Matrix::TableView){ cm.insertItem(getQPixmap("cut_xpm"),tr("Cu&t"), t, SLOT(cutSelection())); cm.insertItem(getQPixmap("copy_xpm"),tr("&Copy"), t, SLOT(copySelection())); From 445de3e685b12a0c6947080a26a4d8b64eeacc98 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 14:08:03 +0000 Subject: [PATCH 212/414] Refs #11094 Resolve Coverity issues in showWindowPopupMenu --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index c9aa8e42b7e2..2281c9cdfa7d 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -9967,12 +9967,20 @@ void ApplicationWindow::showWindowPopupMenu(Q3ListViewItem *it, const QPoint &p, } if (it->rtti() == FolderListItem::RTTI){ - d_current_folder = dynamic_cast(it)->folder(); - showFolderPopupMenu(it, p, false); + auto fli = dynamic_cast(it); + if(fli) + { + d_current_folder = fli->folder(); + showFolderPopupMenu(it, p, false); + } return; } - MdiSubWindow *w= dynamic_cast(it)->window(); + auto wli = dynamic_cast(it); + if(!wli) + return; + + MdiSubWindow *w = wli->window(); if (w){ QMenu cm(this); QMenu plots(this); @@ -10023,6 +10031,8 @@ void ApplicationWindow::showWindowPopupMenu(Q3ListViewItem *it, const QPoint &p, } } else if (w->isA("Graph3D")) { Graph3D *sp=dynamic_cast(w); + if(!sp) + return; Matrix *m = sp->matrix(); QString formula = sp->formula(); if (!formula.isEmpty()){ From 9cf4ee23f8df81c491e9d0f9dd657168eea504d1 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 14:09:26 +0000 Subject: [PATCH 213/414] Refs #11094 Resolve Coverity issues in startRenameFolder --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 2281c9cdfa7d..8559930f36c4 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -14603,8 +14603,12 @@ void ApplicationWindow::startRenameFolder(Q3ListViewItem *item) return; if (item->listView() == lv && item->rtti() == FolderListItem::RTTI) { + auto fli = dynamic_cast(item); + if(!fli) + return; + disconnect(folders, SIGNAL(currentChanged(Q3ListViewItem *)), this, SLOT(folderItemChanged(Q3ListViewItem *))); - d_current_folder = dynamic_cast(item)->folder(); + d_current_folder = fli->folder(); FolderListItem *it = d_current_folder->folderListItem(); it->setRenameEnabled (0, true); it->startRename (0); @@ -14618,8 +14622,8 @@ void ApplicationWindow::renameFolder(Q3ListViewItem *it, int col, const QString { Q_UNUSED(col) - if (!it) - return; + if (!it) + return; Folder *parent = dynamic_cast(currentFolder()->parent()); if (!parent)//the parent folder is the project folder (it always exists) From 922a393a03450eef4697a6dc490ec5380beb5ed7 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 14:10:44 +0000 Subject: [PATCH 214/414] Refs #11094 Resolve Coverity issues in undo --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 8559930f36c4..93a123f98a87 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -8799,10 +8799,14 @@ void ApplicationWindow::undo() QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - if (qobject_cast(w)) - dynamic_cast(w)->editor()->undo(); - else if (qobject_cast(w)){ - QUndoStack *stack = (dynamic_cast(w))->undoStack(); + auto note = dynamic_cast(w); + auto matrix = dynamic_cast(w); + + if(note) + note->editor()->undo(); + else if(matrix) + { + QUndoStack *stack = matrix->undoStack(); if (stack && stack->canUndo()) stack->undo(); } From 0a6fc572af9e9de81297c8303e1844f19df9be6c Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 14:12:30 +0000 Subject: [PATCH 215/414] Refs #11094 Resolve Coverity issues in updateColNames --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 93a123f98a87..3e7c4093643d 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -2221,13 +2221,18 @@ void ApplicationWindow::updateColNames(const QString& oldName, const QString& ne { QList windows = windowsList(); foreach (MdiSubWindow *w, windows){ - if (w->isA("MultiLayer")){ - QList layers = dynamic_cast(w)->layersList(); + auto ml = dynamic_cast(w); + auto g3d = dynamic_cast(w); + + if(ml) + { + QList layers = ml->layersList(); foreach(Graph *g, layers) - g->updateCurveNames(oldName, newName, false); + g->updateCurveNames(oldName, newName, false); } - else if (w->isA("Graph3D")){ - QString name = dynamic_cast(w)->formula(); + else if(g3d) + { + QString name = g3d->formula(); if (name.contains(oldName)){ name.replace(oldName,newName); dynamic_cast(w)->setPlotAssociation(name); From 8eea26c8a186a4051c7de30e9baedb4a30883cef Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 14:13:36 +0000 Subject: [PATCH 216/414] Refs #11094 Resolve Coverity issues in updateTableNames --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 3e7c4093643d..56aeef0452ef 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -2203,15 +2203,17 @@ void ApplicationWindow::updateTableNames(const QString& oldName, const QString& { QList windows = windowsList(); foreach (MdiSubWindow *w, windows) { - if (w->isA("MultiLayer")) { - QList layers = dynamic_cast(w)->layersList(); + auto ml = dynamic_cast(w); + auto g3d = dynamic_cast(w); + if (ml) { + QList layers = ml->layersList(); foreach(Graph *g, layers) - g->updateCurveNames(oldName, newName); - } else if (w->isA("Graph3D")) { - QString name = dynamic_cast(w)->formula(); + g->updateCurveNames(oldName, newName); + } else if (g3d) { + QString name = g3d->formula(); if (name.contains(oldName, true)) { name.replace(oldName,newName); - dynamic_cast(w)->setPlotAssociation(name); + g3d->setPlotAssociation(name); } } } From 545aedb14d3aa132c41e6a227db2c33b34c45737 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 14:14:11 +0000 Subject: [PATCH 217/414] Refs #11094 Resolve Coverity issues in windowProperties --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 56aeef0452ef..d229ae847833 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -15154,6 +15154,9 @@ void ApplicationWindow::addListViewItem(MdiSubWindow *w) void ApplicationWindow::windowProperties() { WindowListItem *it = dynamic_cast(lv->currentItem()); + if(!it) + return; + MdiSubWindow *w = it->window(); if (!w) return; From f5e6c385c17f06e05f729f0285f01f9beaa81481 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 14:17:23 +0000 Subject: [PATCH 218/414] Refs #11094 Resolve Coverity issues in updateMatrixPlots --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index d229ae847833..dbe5fdb7bcd8 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -2320,10 +2320,17 @@ void ApplicationWindow::updateMatrixPlots(MdiSubWindow *window) QList windows = windowsList(); foreach(MdiSubWindow *w, windows){ - if (w->isA("Graph3D") && dynamic_cast(w)->matrix() == m) - dynamic_cast(w)->updateMatrixData(m); + if (w->isA("Graph3D")) { + auto g3d = dynamic_cast(w); + if(g3d && g3d->matrix() == m) + g3d->updateMatrixData(m); + } else if (w->isA("MultiLayer")){ - QList layers = dynamic_cast(w)->layersList(); + auto ml = dynamic_cast(w); + if(!ml) + continue; + + QList layers = ml->layersList(); foreach(Graph *g, layers){ for (int i=0; icurves(); i++){ if (g->curveType(i) == Graph::Histogram){ From d0efde6c59b3036242c5901dc09ad04acddd092e Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 14:19:34 +0000 Subject: [PATCH 219/414] Refs #11094 Resolve Coverity issues in open --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index dbe5fdb7bcd8..172ee729a968 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -4569,7 +4569,11 @@ ApplicationWindow* ApplicationWindow::open(const QString& fn, bool factorySettin QFile f(fname); QTextStream t( &f ); - f.open(QIODevice::ReadOnly); + if(!f.open(QIODevice::ReadOnly)) + { + QMessageBox::critical(this, tr("MantidPlot - File opening error"), tr("The file: %1 could not be opened!").arg(fn)); + return 0; + } QString s = t.readLine(); QStringList list = s.split(QRegExp("\\s"), QString::SkipEmptyParts); if (list.count() < 2 || list[0] != "MantidPlot"){ From a5b71390cbd802b605333e2584dffd0eb47a4c72 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 14:20:38 +0000 Subject: [PATCH 220/414] Refs #11094 Resolve Coverity issues in appendProject --- Code/Mantid/MantidPlot/src/ApplicationWindow.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 172ee729a968..1101ccb3f69f 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -14383,7 +14383,12 @@ Folder* ApplicationWindow::appendProject(const QString& fn, Folder* parentFolder QFile file(fn); QFileInfo fileInfo(fn); - file.open(QIODevice::ReadOnly); + if(!file.open(QIODevice::ReadOnly)) + { + QMessageBox::critical(this, tr("MantidPlot - File opening error"), tr("The file: %1 could not be opened!").arg(fn)); + return 0; + } + QTextStream fileTS(&file); fileTS.setEncoding(QTextStream::UnicodeUTF8); From 522eb122884f13b0c504cbfc1d0e6912233c9608 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Mon, 16 Feb 2015 14:56:20 +0000 Subject: [PATCH 221/414] Refs #11093 Document the slit calculator menu option --- Code/Mantid/docs/source/interfaces/ISIS_Reflectometry.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Code/Mantid/docs/source/interfaces/ISIS_Reflectometry.rst b/Code/Mantid/docs/source/interfaces/ISIS_Reflectometry.rst index bfa6e5b86d72..5d28a9fe39fe 100644 --- a/Code/Mantid/docs/source/interfaces/ISIS_Reflectometry.rst +++ b/Code/Mantid/docs/source/interfaces/ISIS_Reflectometry.rst @@ -120,6 +120,11 @@ The **Reflectometry** menu provides access to the following functionality: | | enabling you to save a *TableWorkspace* to a ``.tbl`` | | | file. | +------------------+----------------------------------------------------------+ +| Slit Calculator | Opens the slit calculator: a tool to help calculate the | +| | correct geometry for the instruments' slits. It's powered| +| | by the :ref:`CalculateSlits ` | +| | algorithm. | ++------------------+----------------------------------------------------------+ | Options | Opens the `Options`_ menu. | +------------------+----------------------------------------------------------+ From 69ae3ddefc75553b84336f132981da509cac3e3c Mon Sep 17 00:00:00 2001 From: Nick Draper Date: Mon, 16 Feb 2015 14:59:48 +0000 Subject: [PATCH 222/414] re #11091 fix linux bug --- Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h | 1 + Code/Mantid/Framework/Kernel/src/InternetHelper.cpp | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h b/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h index d55696f3d102..7fc7b1ed5cb0 100644 --- a/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h +++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h @@ -6,6 +6,7 @@ #include "MantidKernel/ProxyInfo.h" #include +#include #include namespace Poco { diff --git a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp index f99b99b28e25..e10ba8966dac 100644 --- a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp +++ b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp @@ -485,7 +485,8 @@ void InternetHelper::setBody(Poco::Net::HTMLForm& form) { setMethod("POST"); if (m_request == NULL) { - createRequest(Poco::URI("http://www.mantidproject.org")); + Poco::URI uri("http://www.mantidproject.org"); + createRequest(uri); } form.prepareSubmit(*m_request); setContentType(m_request->getContentType()); From 126a19a7e1100410ec0a28b7512216c3b63600a0 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 15:06:09 +0000 Subject: [PATCH 223/414] Started work refactoring indirect Python scripts Refs #10706 --- .../scripts/Inelastic/IndirectCommon.py | 450 +++++++++--------- .../scripts/Inelastic/IndirectDataAnalysis.py | 333 ++++++------- .../scripts/Inelastic/IndirectImport.py | 47 +- 3 files changed, 436 insertions(+), 394 deletions(-) diff --git a/Code/Mantid/scripts/Inelastic/IndirectCommon.py b/Code/Mantid/scripts/Inelastic/IndirectCommon.py index 043c2717866c..d6147a76cc78 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectCommon.py +++ b/Code/Mantid/scripts/Inelastic/IndirectCommon.py @@ -4,48 +4,37 @@ from IndirectImport import import_mantidplot -import sys, platform, os.path, math, datetime, re +import os.path +import math +import datetime +import re import numpy as np import itertools + def StartTime(prog): logger.notice('----------') - message = 'Program ' + prog +' started @ ' + str(datetime.datetime.now()) + message = 'Program ' + prog + ' started @ ' + str(datetime.datetime.now()) logger.notice(message) + def EndTime(prog): - message = 'Program ' + prog +' ended @ ' + str(datetime.datetime.now()) + message = 'Program ' + prog + ' ended @ ' + str(datetime.datetime.now()) logger.notice(message) logger.notice('----------') -def loadInst(instrument): - ws = '__empty_' + instrument - if not mtd.doesExist(ws): - idf_dir = config['instrumentDefinition.directory'] - idf = idf_dir + instrument + '_Definition.xml' - LoadEmptyInstrument(Filename=idf, OutputWorkspace=ws) - -def loadNexus(filename): - ''' - Loads a Nexus file into a workspace with the name based on the - filename. Convenience function for not having to play around with paths - in every function. - ''' - name = os.path.splitext( os.path.split(filename)[1] )[0] - LoadNexus(Filename=filename, OutputWorkspace=name) - return name def getInstrRun(ws_name): - ''' + """ Get the instrument name and run number from a workspace. @param ws_name - name of the workspace @return tuple of form (instrument, run number) - ''' + """ ws = mtd[ws_name] run_number = str(ws.getRunNumber()) if run_number == '0': - #attempt to parse run number off of name + # Attempt to parse run number off of name match = re.match(r'([a-zA-Z]+)([0-9]+)', ws_name) if match: run_number = match.group(2) @@ -58,12 +47,13 @@ def getInstrRun(ws_name): instrument = instrument.lower() return instrument, run_number + def getWSprefix(wsname): - ''' + """ Returns a string of the form '__' on which all of our other naming conventions are built. The workspace is used to get the instrument parameters. - ''' + """ if wsname == '': return '' @@ -76,7 +66,7 @@ def getWSprefix(wsname): (instrument, run_number) = getInstrRun(wsname) if facility == 'ILL': - run_name = instrument + '_'+ run_number + run_name = instrument + '_' + run_number else: run_name = instrument + run_number @@ -94,10 +84,12 @@ def getWSprefix(wsname): return prefix + def getEfixed(workspace, detIndex=0): inst = mtd[workspace].getInstrument() return inst.getNumberParameter("efixed-val")[0] + def checkUnitIs(ws, unit_id, axis_index=0): """ Check that the workspace has the correct units by comparing @@ -105,10 +97,13 @@ def checkUnitIs(ws, unit_id, axis_index=0): """ axis = mtd[ws].getAxis(axis_index) unit = axis.getUnit() - return (unit.unitID() == unit_id) + return unit.unitID() == unit_id + -# Get the default save directory and check it's valid def getDefaultWorkingDirectory(): + """ + Get the default save directory and check it's valid. + """ workdir = config['defaultsave.directory'] if not os.path.isdir(workdir): @@ -116,19 +111,20 @@ def getDefaultWorkingDirectory(): return workdir + def createQaxis(inputWS): result = [] ws = mtd[inputWS] - nHist = ws.getNumberHistograms() + num_hist = ws.getNumberHistograms() if ws.getAxis(1).isSpectra(): inst = ws.getInstrument() - samplePos = inst.getSample().getPos() - beamPos = samplePos - inst.getSource().getPos() - for i in range(0,nHist): + sample_pos = inst.getSample().getPos() + beam_pos = sample_pos - inst.getSource().getPos() + for i in range(0, num_hist): efixed = getEfixed(inputWS, i) detector = ws.getDetector(i) - theta = detector.getTwoTheta(samplePos, beamPos) / 2 - lamda = math.sqrt(81.787/efixed) + theta = detector.getTwoTheta(sample_pos, beam_pos) / 2 + lamda = math.sqrt(81.787 / efixed) q = 4 * math.pi * math.sin(theta) / lamda result.append(q) else: @@ -137,25 +133,27 @@ def createQaxis(inputWS): if not axis.isNumeric(): msg += 'Input workspace must have either spectra or numeric axis.' raise ValueError(msg) - if ( axis.getUnit().unitID() != 'MomentumTransfer' ): + if axis.getUnit().unitID() != 'MomentumTransfer': msg += 'Input must have axis values of Q' raise ValueError(msg) - for i in range(0, nHist): + for i in range(0, num_hist): result.append(float(axis.label(i))) return result + def GetWSangles(inWS): - nhist = mtd[inWS].getNumberHistograms() # get no. of histograms/groups - sourcePos = mtd[inWS].getInstrument().getSource().getPos() - samplePos = mtd[inWS].getInstrument().getSample().getPos() - beamPos = samplePos - sourcePos + num_hist = mtd[inWS].getNumberHistograms() # get no. of histograms/groups + source_pos = mtd[inWS].getInstrument().getSource().getPos() + sample_pos = mtd[inWS].getInstrument().getSample().getPos() + beam_pos = sample_pos - source_pos angles = [] # will be list of angles - for index in range(0, nhist): + for index in range(0, num_hist): detector = mtd[inWS].getDetector(index) # get index - twoTheta = detector.getTwoTheta(samplePos, beamPos)*180.0/math.pi # calc angle - angles.append(twoTheta) # add angle + two_theta = detector.getTwoTheta(sample_pos, beam_pos) * 180.0 / math.pi # calc angle + angles.append(two_theta) # add angle return angles + def GetThetaQ(ws): """ Returns the theta and elastic Q for each spectrum in a given workspace. @@ -164,8 +162,8 @@ def GetThetaQ(ws): @returns A tuple containing a list of theta values and a list of Q values """ - eFixed = getEfixed(ws) - wavelas = math.sqrt(81.787 / eFixed) # Elastic wavelength + e_fixed = getEfixed(ws) + wavelas = math.sqrt(81.787 / e_fixed) # Elastic wavelength k0 = 4.0 * math.pi / wavelas axis = mtd[ws].getAxis(1) @@ -191,28 +189,40 @@ def GetThetaQ(ws): return theta, q + def ExtractFloat(data_string): - """ Extract float values from an ASCII string""" + """ + Extract float values from an ASCII string + """ values = data_string.split() values = map(float, values) return values + def ExtractInt(data_string): - """ Extract int values from an ASCII string""" + """ + Extract int values from an ASCII string + """ values = data_string.split() values = map(int, values) return values -def PadArray(inarray,nfixed): #pad a list to specified size - npt=len(inarray) - padding = nfixed-npt - outarray=[] + +def PadArray(inarray, nfixed): + """ + Pad a list to specified size. + """ + npt = len(inarray) + padding = nfixed - npt + outarray = [] outarray.extend(inarray) - outarray +=[0]*padding + outarray += [0] * padding return outarray -def CheckAnalysers(in1WS,in2WS): - '''Check workspaces have identical analysers and reflections + +def CheckAnalysers(in1WS, in2WS): + """ + Check workspaces have identical analysers and reflections Args: @param in1WS - first 2D workspace @@ -224,22 +234,24 @@ def CheckAnalysers(in1WS,in2WS): Raises: @exception Valuerror - workspaces have different analysers @exception Valuerror - workspaces have different reflections - ''' + """ ws1 = mtd[in1WS] - a1 = ws1.getInstrument().getStringParameter('analyser')[0] - r1 = ws1.getInstrument().getStringParameter('reflection')[0] + analyser_1 = ws1.getInstrument().getStringParameter('analyser')[0] + reflection_1 = ws1.getInstrument().getStringParameter('reflection')[0] ws2 = mtd[in2WS] - a2 = ws2.getInstrument().getStringParameter('analyser')[0] - r2 = ws2.getInstrument().getStringParameter('reflection')[0] - if a1 != a2: - raise ValueError('Workspace '+in1WS+' and '+in2WS+' have different analysers') - elif r1 != r2: - raise ValueError('Workspace '+in1WS+' and '+in2WS+' have different reflections') + analyser_2 = ws2.getInstrument().getStringParameter('analyser')[0] + reflection_2 = ws2.getInstrument().getStringParameter('reflection')[0] + if analyser_1 != analyser_2: + raise ValueError('Workspace %s and %s have different analysers' % (ws1, ws2)) + elif reflection_1 != reflection_2: + raise ValueError('Workspace %s and %s have different reflections' % (ws1, ws2)) else: - logger.information('Analyser is '+a1+r1) + logger.information('Analyser is %s, reflection %s' % (analyser_1, reflection_1)) + def CheckHistZero(inWS): - '''Retrieves basic info on a worskspace + """ + Retrieves basic info on a worskspace Checks the workspace is not empty, then returns the number of histogram and the number of X-points, which is the number of bin boundaries minus one @@ -248,25 +260,27 @@ def CheckHistZero(inWS): @param inWS 2D workspace Returns: - @return nhist - number of histograms in the workspace + @return num_hist - number of histograms in the workspace @return ntc - number of X-points in the first histogram, which is the number of bin boundaries minus one. It is assumed all histograms have the same number of X-points. Raises: @exception ValueError - Worskpace has no histograms - ''' - nhist = mtd[inWS].getNumberHistograms() # no. of hist/groups in WS - if nhist == 0: - raise ValueError('Workspace '+inWS+' has NO histograms') - Xin = mtd[inWS].readX(0) - ntc = len(Xin)-1 # no. points from length of x array + """ + num_hist = mtd[inWS].getNumberHistograms() # no. of hist/groups in WS + if num_hist == 0: + raise ValueError('Workspace ' + inWS + ' has NO histograms') + x_in = mtd[inWS].readX(0) + ntc = len(x_in) - 1 # no. points from length of x array if ntc == 0: - raise ValueError('Workspace '+inWS+' has NO points') - return nhist,ntc + raise ValueError('Workspace ' + inWS + ' has NO points') + return num_hist, ntc -def CheckHistSame(in1WS,name1,in2WS,name2): - '''Check workspaces have same number of histograms and bin boundaries + +def CheckHistSame(in1WS, name1, in2WS, name2): + """ + Check workspaces have same number of histograms and bin boundaries Args: @param in1WS - first 2D workspace @@ -280,49 +294,52 @@ def CheckHistSame(in1WS,name1,in2WS,name2): Raises: Valuerror: number of histograms is different Valuerror: number of bin boundaries in the histograms is different - ''' - nhist1 = mtd[in1WS].getNumberHistograms() # no. of hist/groups in WS1 - X1 = mtd[in1WS].readX(0) - xlen1 = len(X1) - nhist2 = mtd[in2WS].getNumberHistograms() # no. of hist/groups in WS2 - X2 = mtd[in2WS].readX(0) - xlen2 = len(X2) - if nhist1 != nhist2: # check that no. groups are the same - e1 = name1+' ('+in1WS+') histograms (' +str(nhist1) + ')' - e2 = name2+' ('+in2WS+') histograms (' +str(nhist2) + ')' - error = e1 + ' not = ' + e2 + """ + num_hist_1 = mtd[in1WS].getNumberHistograms() # no. of hist/groups in WS1 + x_1 = mtd[in1WS].readX(0) + x_len_1 = len(x_1) + num_hist_2 = mtd[in2WS].getNumberHistograms() # no. of hist/groups in WS2 + x_2 = mtd[in2WS].readX(0) + x_len_2 = len(x_2) + if num_hist_1 != num_hist_2: # Check that no. groups are the same + error_1 = '%s (%s) histograms (%d)' % (name1, in1WS, num_hist_1) + error_2 = '%s (%s) histograms (%d)' % (name2, in2WS, num_hist_2) + error = error_1 + ' not = ' + error_2 raise ValueError(error) - elif xlen1 != xlen2: - e1 = name1+' ('+in1WS+') array length (' +str(xlen1) + ')' - e2 = name2+' ('+in2WS+') array length (' +str(xlen2) + ')' - error = e1 + ' not = ' + e2 + elif x_len_1 != x_len_2: + error_1 = '%s (%s) array length (%d)' % (name1, in1WS, x_len_1) + error_2 = '%s (%s) array length (%d)' % (name2, in2WS, x_len_2) + error = error_1 + ' not = ' + error_2 raise ValueError(error) -def CheckXrange(x_range,type): - if not ( ( len(x_range) == 2 ) or ( len(x_range) == 4 ) ): + +def CheckXrange(x_range, type): + if not (len(x_range) == 2) or (len(x_range) == 4): raise ValueError(type + ' - Range must contain either 2 or 4 numbers') for lower, upper in zip(x_range[::2], x_range[1::2]): if math.fabs(lower) < 1e-5: - raise ValueError(type + ' - input minimum ('+str(lower)+') is Zero') + raise ValueError('%s - input minimum (%f) is zero' % (type, lower)) if math.fabs(upper) < 1e-5: - raise ValueError(type + ' - input maximum ('+str(upper)+') is Zero') + raise ValueError('%s - input maximum (%f) is zero' % (type, upper)) if upper < lower: - raise ValueError(type + ' - input max ('+str(upper)+') < min ('+str(lower)+')') + raise ValueError('%s - input maximum (%f) < minimum (%f)' % (type, upper, lower)) + -def CheckElimits(erange,Xin): - nx = len(Xin)-1 +def CheckElimits(erange, Xin): + len_x = len(Xin) - 1 if math.fabs(erange[0]) < 1e-5: - raise ValueError('Elimits - input emin ( '+str(erange[0])+' ) is Zero') + raise ValueError('Elimits - input emin (%f) is Zero' % (erange[0])) if erange[0] < Xin[0]: - raise ValueError('Elimits - input emin ( '+str(erange[0])+' ) < data emin ( '+str(Xin[0])+' )') + raise ValueError('Elimits - input emin (%f) < data emin (%f)' % (erange[0], Xin[0])) if math.fabs(erange[1]) < 1e-5: - raise ValueError('Elimits - input emax ( '+str(erange[1])+' ) is Zero') - if erange[1] > Xin[nx]: - raise ValueError('Elimits - input emax ( '+str(erange[1])+' ) > data emax ( '+str(Xin[nx])+' )') + raise ValueError('Elimits - input emax (%f) is Zero' % (erange[1])) + if erange[1] > Xin[len_x]: + raise ValueError('Elimits - input emax (%f) > data emax (%f)' % (erange[1], Xin[len_x])) if erange[1] < erange[0]: - raise ValueError('Elimits - input emax ( '+str(erange[1])+' ) < emin ( '+str(erange[0])+' )') + raise ValueError('Elimits - input emax (%f) < emin (%f)' % (erange[1], erange[0])) + def getInstrumentParameter(ws, param_name): """Get an named instrument parameter from a workspace. @@ -333,8 +350,8 @@ def getInstrumentParameter(ws, param_name): """ inst = mtd[ws].getInstrument() - #create a map of type parameters to functions. This is so we avoid writing lots of - #if statements becuase there's no way to dynamically get the type. + # Create a map of type parameters to functions. This is so we avoid writing lots of + # if statements becuase there's no way to dynamically get the type. func_map = {'double': inst.getNumberParameter, 'string': inst.getStringParameter, 'int': inst.getIntParameter, 'bool': inst.getBoolParameter} @@ -349,6 +366,7 @@ def getInstrumentParameter(ws, param_name): return param + def plotSpectra(ws, y_axis_title, indicies=[]): """ Plot a selection of spectra given a list of indicies @@ -362,14 +380,15 @@ def plotSpectra(ws, y_axis_title, indicies=[]): indicies = range(num_spectra) try: - mp = import_mantidplot() - plot = mp.plotSpectrum(ws, indicies, True) + mtd_plot = import_mantidplot() + plot = mtd_plot.plotSpectrum(ws, indicies, True) layer = plot.activeLayer() - layer.setAxisTitle(mp.Layer.Left, y_axis_title) + layer.setAxisTitle(mtd_plot.Layer.Left, y_axis_title) except RuntimeError: - #User clicked cancel on plot so don't do anything + # User clicked cancel on plot so don't do anything return + def plotParameters(ws, *param_names): """ Plot a number of spectra given a list of parameter names @@ -387,78 +406,80 @@ def plotParameters(ws, *param_names): if len(indicies) > 0: plotSpectra(ws, name, indicies) + def convertToElasticQ(input_ws, output_ws=None): - """ + """ Helper function to convert the spectrum axis of a sample to ElasticQ. @param input_ws - the name of the workspace to convert from @param output_ws - the name to call the converted workspace - """ + """ - if output_ws is None: - output_ws = input_ws + if output_ws is None: + output_ws = input_ws - axis = mtd[input_ws].getAxis(1) - if axis.isSpectra(): - e_fixed = getEfixed(input_ws) - ConvertSpectrumAxis(input_ws,Target='ElasticQ',EMode='Indirect',EFixed=e_fixed,OutputWorkspace=output_ws) + axis = mtd[input_ws].getAxis(1) + if axis.isSpectra(): + e_fixed = getEfixed(input_ws) + ConvertSpectrumAxis(input_ws, Target='ElasticQ', EMode='Indirect', EFixed=e_fixed, OutputWorkspace=output_ws) - elif axis.isNumeric(): - #check that units are Momentum Transfer - if axis.getUnit().unitID() != 'MomentumTransfer': - raise RuntimeError('Input must have axis values of Q') + elif axis.isNumeric(): + # Check that units are Momentum Transfer + if axis.getUnit().unitID() != 'MomentumTransfer': + raise RuntimeError('Input must have axis values of Q') + + CloneWorkspace(input_ws, OutputWorkspace=output_ws) + else: + raise RuntimeError('Input workspace must have either spectra or numeric axis.') - CloneWorkspace(input_ws, OutputWorkspace=output_ws) - else: - raise RuntimeError('Input workspace must have either spectra or numeric axis.') def transposeFitParametersTable(params_table, output_table=None): - """ + """ Transpose the parameter table created from a multi domain Fit. This function will make the output consistent with PlotPeakByLogValue. @param params_table - the parameter table output from Fit. @param output_table - name to call the transposed table. If omitted, the output_table will be the same as the params_table - """ - params_table = mtd[params_table] - - table_ws = '__tmp_table_ws' - table_ws = CreateEmptyTableWorkspace(OutputWorkspace=table_ws) - - param_names = params_table.column(0)[:-1] #-1 to remove cost function - param_values = params_table.column(1)[:-1] - param_errors = params_table.column(2)[:-1] - - #find the number of parameters per function - func_index = param_names[0].split('.')[0] - num_params = 0 - for i, name in enumerate(param_names): - if name.split('.')[0] != func_index: - num_params = i - break - - #create columns with parameter names for headers - column_names = ['.'.join(name.split('.')[1:]) for name in param_names[:num_params]] - column_error_names = [name + '_Err' for name in column_names] - column_names = zip(column_names, column_error_names) - table_ws.addColumn('double', 'axis-1') - for name, error_name in column_names: - table_ws.addColumn('double', name) - table_ws.addColumn('double', error_name) - - #output parameter values to table row - for i in xrange(0, params_table.rowCount()-1, num_params): - row_values = param_values[i:i+num_params] - row_errors = param_errors[i:i+num_params] - row = [value for pair in zip(row_values, row_errors) for value in pair] - row = [i/num_params] + row - table_ws.addRow(row) - - if output_table is None: - output_table = params_table.name() - - RenameWorkspace(table_ws.name(), OutputWorkspace=output_table) + """ + params_table = mtd[params_table] + + table_ws = '__tmp_table_ws' + table_ws = CreateEmptyTableWorkspace(OutputWorkspace=table_ws) + + param_names = params_table.column(0)[:-1] # -1 to remove cost function + param_values = params_table.column(1)[:-1] + param_errors = params_table.column(2)[:-1] + + # Find the number of parameters per function + func_index = param_names[0].split('.')[0] + num_params = 0 + for i, name in enumerate(param_names): + if name.split('.')[0] != func_index: + num_params = i + break + + # Create columns with parameter names for headers + column_names = ['.'.join(name.split('.')[1:]) for name in param_names[:num_params]] + column_error_names = [name + '_Err' for name in column_names] + column_names = zip(column_names, column_error_names) + table_ws.addColumn('double', 'axis-1') + for name, error_name in column_names: + table_ws.addColumn('double', name) + table_ws.addColumn('double', error_name) + + # Output parameter values to table row + for i in xrange(0, params_table.rowCount() - 1, num_params): + row_values = param_values[i:i + num_params] + row_errors = param_errors[i:i + num_params] + row = [value for pair in zip(row_values, row_errors) for value in pair] + row = [i / num_params] + row + table_ws.addRow(row) + + if output_table is None: + output_table = params_table.name() + + RenameWorkspace(table_ws.name(), OutputWorkspace=output_table) def search_for_fit_params(suffix, table_ws): @@ -472,7 +493,7 @@ def search_for_fit_params(suffix, table_ws): def convertParametersToWorkspace(params_table, x_column, param_names, output_name): - """ + """ Convert a parameter table output by PlotPeakByLogValue to a MatrixWorkspace. This will make a spectrum for each parameter name using the x_column vairable as the @@ -482,60 +503,61 @@ def convertParametersToWorkspace(params_table, x_column, param_names, output_nam @param x_column - the column in the table to use for the x values. @param parameter_names - list of parameter names to add to the workspace @param output_name - name to call the output workspace. - """ - #search for any parameters in the table with the given parameter names, - #ignoring their function index and output them to a workspace - workspace_names = [] - for param_name in param_names: - column_names = search_for_fit_params(param_name, params_table) - column_error_names = search_for_fit_params(param_name+'_Err', params_table) - param_workspaces = [] - for name, error_name in zip(column_names, column_error_names): - ConvertTableToMatrixWorkspace(params_table, x_column, name, error_name, OutputWorkspace=name) - param_workspaces.append(name) - workspace_names.append(param_workspaces) - - #transpose list of workspaces, ignoring unequal length of lists - #this handles the case where a parameter occurs only once in the whole workspace - workspace_names = map(list, itertools.izip_longest(*workspace_names)) - workspace_names = [filter(None, sublist) for sublist in workspace_names] - - #join all the parameters for each peak into a single workspace per peak - temp_workspaces = [] - for peak_params in workspace_names: - temp_peak_ws = peak_params[0] - for param_ws in peak_params[1:]: - ConjoinWorkspaces(temp_peak_ws, param_ws, False) - temp_workspaces.append(temp_peak_ws) - - #join all peaks into a single workspace - temp_workspace = temp_workspaces[0] - for temp_ws in temp_workspaces[1:]: - ConjoinWorkspaces(temp_workspace, temp_peak_ws, False) - - RenameWorkspace(temp_workspace, OutputWorkspace=output_name) - - #replace axis on workspaces with text axis - axis = TextAxis.create(mtd[output_name].getNumberHistograms()) - workspace_names = [name for sublist in workspace_names for name in sublist] - for i, name in enumerate(workspace_names): - axis.setLabel(i, name) - mtd[output_name].replaceAxis(1, axis) + """ + # Search for any parameters in the table with the given parameter names, + # ignoring their function index and output them to a workspace + workspace_names = [] + for param_name in param_names: + column_names = search_for_fit_params(param_name, params_table) + column_error_names = search_for_fit_params(param_name + '_Err', params_table) + param_workspaces = [] + for name, error_name in zip(column_names, column_error_names): + ConvertTableToMatrixWorkspace(params_table, x_column, name, error_name, OutputWorkspace=name) + param_workspaces.append(name) + workspace_names.append(param_workspaces) + + # Transpose list of workspaces, ignoring unequal length of lists + # this handles the case where a parameter occurs only once in the whole workspace + workspace_names = map(list, itertools.izip_longest(*workspace_names)) + workspace_names = [filter(None, sublist) for sublist in workspace_names] + + # Join all the parameters for each peak into a single workspace per peak + temp_workspaces = [] + for peak_params in workspace_names: + temp_peak_ws = peak_params[0] + for param_ws in peak_params[1:]: + ConjoinWorkspaces(temp_peak_ws, param_ws, False) + temp_workspaces.append(temp_peak_ws) + + # Join all peaks into a single workspace + temp_workspace = temp_workspaces[0] + for temp_ws in temp_workspaces[1:]: # TODO: fairly certain something is wrong here + ConjoinWorkspaces(temp_workspace, temp_peak_ws, False) + + RenameWorkspace(temp_workspace, OutputWorkspace=output_name) + + # Replace axis on workspaces with text axis + axis = TextAxis.create(mtd[output_name].getNumberHistograms()) + workspace_names = [name for sublist in workspace_names for name in sublist] + for i, name in enumerate(workspace_names): + axis.setLabel(i, name) + mtd[output_name].replaceAxis(1, axis) + def addSampleLogs(ws, sample_logs): - """ + """ Add a dictionary of logs to a workspace. The type of the log is inferred by the type of the value passed to the log. + @param ws - workspace to add logs too. @param sample_logs - dictionary of logs to append to the workspace. - """ - for key, value in sample_logs.iteritems(): - if isinstance(value, bool): - log_type = 'String' - elif isinstance(value, (int, long, float)): - log_type = 'Number' - else: - log_type = 'String' + """ + + for key, value in sample_logs.iteritems(): + if isinstance(value, (int, long, float)): + log_type = 'Number' + else: + log_type = 'String' - AddSampleLog(Workspace=ws, LogName=key, LogType=log_type, LogText=str(value)) + AddSampleLog(Workspace=ws, LogName=key, LogType=log_type, LogText=str(value)) diff --git a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py index ca7a18289489..6edb1ac5074b 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py +++ b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py @@ -1,5 +1,5 @@ from IndirectImport import import_mantidplot -mp = import_mantidplot() +MTD_PLOT = import_mantidplot() from IndirectCommon import * import math, re, os.path, numpy as np @@ -13,7 +13,9 @@ ############################################################################## def split(l, n): - #Yield successive n-sized chunks from l. + """ + Yield successive n-sized chunks from l. + """ for i in xrange(0, len(l), n): yield l[i:i+n] @@ -23,13 +25,13 @@ def segment(l, fromIndex, toIndex): def trimData(nSpec, vals, min, max): result = [] - chunkSize = len(vals) / nSpec + chunk_size = len(vals / nSpec) assert min >= 0, 'trimData: min is less then zero' - assert max <= chunkSize - 1, 'trimData: max is greater than the number of spectra' + assert max <= chunk_size - 1, 'trimData: max is greater than the number of spectra' assert min <= max, 'trimData: min is greater than max' - chunks = split(vals,chunkSize) + chunks = split(vals, chunk_size) for chunk in chunks: - seg = segment(chunk,min,max) + seg = segment(chunk, min, max) for val in seg: result.append(val) return result @@ -91,7 +93,7 @@ def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin logger.information('Fit type : Delta = ' + str(using_delta_func) + ' ; Lorentzians = ' + str(lorentzians)) logger.information('Background type : ' + bgd) - output_workspace = getWSprefix(inputWS) + 'conv_' + ftype + bgd + '_s' + str(specMin) + "_to_" + str(specMax) + output_workspace = '%sconv_%s%s_s%d_to_%d' % (getWSprefix(inputWS), ftype, bgd, specMin, specMax) #convert input workspace to get Q axis temp_fit_workspace = "__convfit_fit_ws" @@ -122,20 +124,28 @@ def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin axis.setUnit("MomentumTransfer") CopyLogs(InputWorkspace=inputWS, OutputWorkspace=wsname) - AddSampleLog(Workspace=wsname, LogName='convolve_members', LogType='String', LogText=str(convolve)) - AddSampleLog(Workspace=wsname, LogName="fit_program", LogType="String", LogText='ConvFit') - AddSampleLog(Workspace=wsname, LogName='background', LogType='String', LogText=str(bgd)) - AddSampleLog(Workspace=wsname, LogName='delta_function', LogType='String', LogText=str(using_delta_func)) - AddSampleLog(Workspace=wsname, LogName='lorentzians', LogType='String', LogText=str(lorentzians)) + AddSampleLog(Workspace=wsname, LogName='convolve_members', + LogType='String', LogText=str(convolve)) + AddSampleLog(Workspace=wsname, LogName="fit_program", + LogType="String", LogText='ConvFit') + AddSampleLog(Workspace=wsname, LogName='background', + LogType='String', LogText=str(bgd)) + AddSampleLog(Workspace=wsname, LogName='delta_function', + LogType='String', LogText=str(using_delta_func)) + AddSampleLog(Workspace=wsname, LogName='lorentzians', + LogType='String', LogText=str(lorentzians)) CopyLogs(InputWorkspace=wsname, OutputWorkspace=output_workspace + "_Workspaces") temp_correction = temperature is not None - AddSampleLog(Workspace=wsname, LogName='temperature_correction', LogType='String', LogText=str(temp_correction)) + AddSampleLog(Workspace=wsname, LogName='temperature_correction', + LogType='String', LogText=str(temp_correction)) if temp_correction: - AddSampleLog(Workspace=wsname, LogName='temperature_value', LogType='String', LogText=str(temperature)) + AddSampleLog(Workspace=wsname, LogName='temperature_value', + LogType='String', LogText=str(temperature)) - RenameWorkspace(InputWorkspace=output_workspace, OutputWorkspace=output_workspace + "_Parameters") + RenameWorkspace(InputWorkspace=output_workspace, + OutputWorkspace=output_workspace + "_Parameters") fit_workspaces = mtd[output_workspace + '_Workspaces'].getNames() for i, ws in enumerate(fit_workspaces): RenameWorkspace(ws, OutputWorkspace=output_workspace + '_' + str(i+specMin) + '_Workspace') @@ -159,178 +169,178 @@ def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin ############################################################################## def furyfitSeq(inputWS, func, ftype, startx, endx, spec_min=0, spec_max=None, intensities_constrained=False, Save=False, Plot='None'): + StartTime('FuryFit') - StartTime('FuryFit') + fit_type = ftype[:-2] + logger.information('Option: ' + fit_type) + logger.information(func) - fit_type = ftype[:-2] - logger.information('Option: ' + fit_type) - logger.information(func) + tmp_fit_workspace = "__furyfit_fit_ws" + CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx) - tmp_fit_workspace = "__furyfit_fit_ws" - CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx) - - num_hist = mtd[inputWS].getNumberHistograms() - if spec_max is None: - spec_max = num_hist - 1 + num_hist = mtd[inputWS].getNumberHistograms() + if spec_max is None: + spec_max = num_hist - 1 - # name stem for generated workspace - output_workspace = getWSprefix(inputWS) + 'fury_' + ftype + str(spec_min) + "_to_" + str(spec_max) + # Name stem for generated workspace + output_workspace = '%sfury_%s%d_to_%d' % (getWSprefix(inputWS), ftype, spec_min, spec_max) - ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) - convertToElasticQ(tmp_fit_workspace) + ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) + convertToElasticQ(tmp_fit_workspace) - #build input string for PlotPeakByLogValue - input_str = [tmp_fit_workspace + ',i%d' % i for i in range(spec_min, spec_max + 1)] - input_str = ';'.join(input_str) + # Build input string for PlotPeakByLogValue + input_str = [tmp_fit_workspace + ',i%d' % i for i in range(spec_min, spec_max + 1)] + input_str = ';'.join(input_str) - PlotPeakByLogValue(Input=input_str, OutputWorkspace=output_workspace, Function=func, - StartX=startx, EndX=endx, FitType='Sequential', CreateOutput=True) + PlotPeakByLogValue(Input=input_str, OutputWorkspace=output_workspace, Function=func, + StartX=startx, EndX=endx, FitType='Sequential', CreateOutput=True) - #remove unsused workspaces - DeleteWorkspace(output_workspace + '_NormalisedCovarianceMatrices') - DeleteWorkspace(output_workspace + '_Parameters') + # Remove unsused workspaces + DeleteWorkspace(output_workspace + '_NormalisedCovarianceMatrices') + DeleteWorkspace(output_workspace + '_Parameters') - fit_group = output_workspace + '_Workspaces' - params_table = output_workspace + '_Parameters' - RenameWorkspace(output_workspace, OutputWorkspace=params_table) + fit_group = output_workspace + '_Workspaces' + params_table = output_workspace + '_Parameters' + RenameWorkspace(output_workspace, OutputWorkspace=params_table) - #create *_Result workspace - result_workspace = output_workspace + "_Result" - parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] - convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) + # Create *_Result workspace + result_workspace = output_workspace + "_Result" + parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] + convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) - #set x units to be momentum transfer - axis = mtd[result_workspace].getAxis(0) - axis.setUnit("MomentumTransfer") + # Set x units to be momentum transfer + axis = mtd[result_workspace].getAxis(0) + axis.setUnit("MomentumTransfer") - #process generated workspaces - wsnames = mtd[fit_group].getNames() - params = [startx, endx, fit_type] - for i, ws in enumerate(wsnames): - output_ws = output_workspace + '_%d_Workspace' % i - RenameWorkspace(ws, OutputWorkspace=output_ws) + # Process generated workspaces + wsnames = mtd[fit_group].getNames() + for i, ws in enumerate(wsnames): + output_ws = output_workspace + '_%d_Workspace' % i + RenameWorkspace(ws, OutputWorkspace=output_ws) - sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': fit_type, - 'intensities_constrained': intensities_constrained, 'beta_constrained': False} + sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': fit_type, + 'intensities_constrained': intensities_constrained, 'beta_constrained': False} - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) - addSampleLogs(fit_group, sample_logs) - addSampleLogs(result_workspace, sample_logs) + addSampleLogs(fit_group, sample_logs) + addSampleLogs(result_workspace, sample_logs) - if Save: - save_workspaces = [result_workspace, fit_group] - furyFitSaveWorkspaces(save_workspaces) + if Save: + save_workspaces = [result_workspace, fit_group] + furyFitSaveWorkspaces(save_workspaces) - if Plot != 'None' : - furyfitPlotSeq(result_workspace, Plot) + if Plot != 'None' : + furyfitPlotSeq(result_workspace, Plot) - EndTime('FuryFit') - return result_workspace + EndTime('FuryFit') + return result_workspace def furyfitMult(inputWS, function, ftype, startx, endx, spec_min=0, spec_max=None, intensities_constrained=False, Save=False, Plot='None'): - StartTime('FuryFit Multi') + StartTime('FuryFit Multi') - nHist = mtd[inputWS].getNumberHistograms() - output_workspace = getWSprefix(inputWS) + 'fury_1Smult_s0_to_' + str(nHist-1) + nHist = mtd[inputWS].getNumberHistograms() + output_workspace = getWSprefix(inputWS) + 'fury_1Smult_s0_to_' + str(nHist-1) - option = ftype[:-2] - logger.information('Option: '+option) - logger.information('Function: '+function) + option = ftype[:-2] + logger.information('Option: '+option) + logger.information('Function: '+function) - #prepare input workspace for fitting - tmp_fit_workspace = "__furyfit_fit_ws" - if spec_max is None: - CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx, - StartWorkspaceIndex=spec_min) - else: - CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx, - StartWorkspaceIndex=spec_min, EndWorkspaceIndex=spec_max) + #prepare input workspace for fitting + tmp_fit_workspace = "__furyfit_fit_ws" + if spec_max is None: + CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, + XMin=startx, XMax=endx, + StartWorkspaceIndex=spec_min) + else: + CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, + XMin=startx, XMax=endx, + StartWorkspaceIndex=spec_min, EndWorkspaceIndex=spec_max) - ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) - convertToElasticQ(tmp_fit_workspace) + ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) + convertToElasticQ(tmp_fit_workspace) - #fit multi-domian functino to workspace - multi_domain_func, kwargs = createFuryMultiDomainFunction(function, tmp_fit_workspace) - Fit(Function=multi_domain_func, InputWorkspace=tmp_fit_workspace, WorkspaceIndex=0, - Output=output_workspace, CreateOutput=True, **kwargs) + #fit multi-domian functino to workspace + multi_domain_func, kwargs = createFuryMultiDomainFunction(function, tmp_fit_workspace) + Fit(Function=multi_domain_func, InputWorkspace=tmp_fit_workspace, WorkspaceIndex=0, + Output=output_workspace, CreateOutput=True, **kwargs) - params_table = output_workspace + '_Parameters' - transposeFitParametersTable(params_table) + params_table = output_workspace + '_Parameters' + transposeFitParametersTable(params_table) - #set first column of parameter table to be axis values - ax = mtd[tmp_fit_workspace].getAxis(1) - axis_values = ax.extractValues() - for i, value in enumerate(axis_values): - mtd[params_table].setCell('axis-1', i, value) + #set first column of parameter table to be axis values + ax = mtd[tmp_fit_workspace].getAxis(1) + axis_values = ax.extractValues() + for i, value in enumerate(axis_values): + mtd[params_table].setCell('axis-1', i, value) - #convert parameters to matrix workspace - result_workspace = output_workspace + "_Result" - parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] - convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) + #convert parameters to matrix workspace + result_workspace = output_workspace + "_Result" + parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] + convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) - #set x units to be momentum transfer - axis = mtd[result_workspace].getAxis(0) - axis.setUnit("MomentumTransfer") + #set x units to be momentum transfer + axis = mtd[result_workspace].getAxis(0) + axis.setUnit("MomentumTransfer") - result_workspace = output_workspace + '_Result' - fit_group = output_workspace + '_Workspaces' + result_workspace = output_workspace + '_Result' + fit_group = output_workspace + '_Workspaces' - sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': ftype, - 'intensities_constrained': intensities_constrained, 'beta_constrained': True} + sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': ftype, + 'intensities_constrained': intensities_constrained, 'beta_constrained': True} - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) - addSampleLogs(result_workspace, sample_logs) - addSampleLogs(fit_group, sample_logs) + addSampleLogs(result_workspace, sample_logs) + addSampleLogs(fit_group, sample_logs) - DeleteWorkspace(tmp_fit_workspace) + DeleteWorkspace(tmp_fit_workspace) - if Save: - save_workspaces = [result_workspace] - furyFitSaveWorkspaces(save_workspaces) + if Save: + save_workspaces = [result_workspace] + furyFitSaveWorkspaces(save_workspaces) - if Plot != 'None': - furyfitPlotSeq(result_workspace, Plot) + if Plot != 'None': + furyfitPlotSeq(result_workspace, Plot) - EndTime('FuryFit Multi') - return result_workspace + EndTime('FuryFit Multi') + return result_workspace def createFuryMultiDomainFunction(function, input_ws): - multi= 'composite=MultiDomainFunction,NumDeriv=1;' - comp = '(composite=CompositeFunction,$domains=i;' + function + ');' + multi= 'composite=MultiDomainFunction,NumDeriv=1;' + comp = '(composite=CompositeFunction,$domains=i;' + function + ');' - ties = [] - kwargs = {} - num_spectra = mtd[input_ws].getNumberHistograms() - for i in range(0, num_spectra): - multi += comp - kwargs['WorkspaceIndex_' + str(i)] = i + ties = [] + kwargs = {} + num_spectra = mtd[input_ws].getNumberHistograms() + for i in range(0, num_spectra): + multi += comp + kwargs['WorkspaceIndex_' + str(i)] = i - if i > 0: - kwargs['InputWorkspace_' + str(i)] = input_ws + if i > 0: + kwargs['InputWorkspace_' + str(i)] = input_ws - #tie beta for every spectrum - tie = 'f%d.f1.Beta=f0.f1.Beta' % i - ties.append(tie) + #tie beta for every spectrum + tie = 'f%d.f1.Beta=f0.f1.Beta' % i + ties.append(tie) - ties = ','.join(ties) - multi += 'ties=(' + ties + ')' + ties = ','.join(ties) + multi += 'ties=(' + ties + ')' - return multi, kwargs + return multi, kwargs def furyFitSaveWorkspaces(save_workspaces): - workdir = getDefaultWorkingDirectory() - for ws in save_workspaces: - #save workspace to default directory - fpath = os.path.join(workdir, ws+'.nxs') - SaveNexusProcessed(InputWorkspace=ws, Filename=fpath) - logger.information(ws + ' output to file : '+fpath) + workdir = getDefaultWorkingDirectory() + for ws in save_workspaces: + #save workspace to default directory + fpath = os.path.join(workdir, ws+'.nxs') + SaveNexusProcessed(InputWorkspace=ws, Filename=fpath) + logger.information(ws + ' output to file : '+fpath) def furyfitPlotSeq(ws, plot): @@ -349,10 +359,10 @@ def furyfitPlotSeq(ws, plot): def msdfitPlotSeq(inputWS, xlabel): ws = mtd[inputWS+'_A1'] if len(ws.readX(0)) > 1: - msd_plot = mp.plotSpectrum(inputWS+'_A1',0,True) + msd_plot = MTD_PLOT.plotSpectrum(inputWS+'_A1',0,True) msd_layer = msd_plot.activeLayer() - msd_layer.setAxisTitle(mp.Layer.Bottom,xlabel) - msd_layer.setAxisTitle(mp.Layer.Left,'') + msd_layer.setAxisTitle(MTD_PLOT.Layer.Bottom,xlabel) + msd_layer.setAxisTitle(MTD_PLOT.Layer.Left,'') def msdfit(ws, startX, endX, spec_min=0, spec_max=None, Save=False, Plot=True): StartTime('msdFit') @@ -444,7 +454,7 @@ def plotInput(inputfiles,spectra=[]): GroupDetectors(root, root, DetectorList=range(spectra[0],spectra[1]+1) ) workspaces.append(root) if len(workspaces) > 0: - graph = mp.plotSpectrum(workspaces,0) + graph = MTD_PLOT.plotSpectrum(workspaces,0) graph.activeLayer().setTitle(", ".join(workspaces)) ############################################################################## @@ -504,15 +514,14 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): ConvertUnits(InputWorkspace=inputWS, OutputWorkspace=inputWS, Target='Wavelength') else: efixed = getEfixed(inputWS) # Get efixed - theta, Q = GetThetaQ(inputWS) + Q = GetThetaQ(inputWS)[1] ConvertUnits(InputWorkspace=inputWS, OutputWorkspace=inputWS, Target='Wavelength', EMode='Indirect', EFixed=efixed) sam_name = getWSprefix(inputWS) - nameStem = corr[:-4] corrections = mtd[corr].getNames() if mtd.doesExist(canWS): - (instr, can_run) = getInstrRun(canWS) + can_run = getInstrRun(canWS)[1] CorrectedWS = sam_name +'Correct_'+ can_run if diffraction_run: @@ -526,7 +535,7 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): # Check that number of histograms in each corrections workspace matches # that of the input (sample) workspace for ws in corrections: - if ( mtd[ws].getNumberHistograms() != nHist ): + if mtd[ws].getNumberHistograms() != nHist: raise ValueError('Mismatch: num of spectra in '+ws+' and inputWS') # Workspaces that hold intermediate results CorrectedSampleWS = '__csam' @@ -537,7 +546,8 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): logger.information(str(i) + str(mtd[CorrectedSampleWS].readX(0))) if len(corrections) == 1: Ass = CubicFit(corrections[0], i) - PolynomialCorrection(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedSampleWS, + PolynomialCorrection(InputWorkspace=CorrectedSampleWS, + OutputWorkspace=CorrectedSampleWS, Coefficients=Ass, Operation='Divide') if i == 0: CloneWorkspace(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedWS) @@ -554,11 +564,13 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): PolynomialCorrection(InputWorkspace=CorrectedCanWS, OutputWorkspace=CorrectedCanWS, Coefficients=Acsc, Operation='Multiply') - subractCanWorkspace(CorrectedSampleWS, CorrectedCanWS, CorrectedSampleWS, rebin_can=rebin_can) + subractCanWorkspace(CorrectedSampleWS, CorrectedCanWS, + CorrectedSampleWS, rebin_can=rebin_can) Assc = CubicFit(corrections[1], i) - PolynomialCorrection(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedSampleWS, - Coefficients=Assc, Operation='Divide') + PolynomialCorrection(InputWorkspace=CorrectedSampleWS, + OutputWorkspace=CorrectedSampleWS, + Coefficients=Assc, Operation='Divide') if i == 0: CloneWorkspace(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedWS) else: @@ -613,7 +625,7 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S StartTime('ApplyCorrections') workdir = config['defaultsave.directory'] - s_hist,sxlen = CheckHistZero(sample) + s_hist = CheckHistZero(sample)[0] CloneWorkspace(sample, OutputWorkspace='__apply_corr_cloned_sample') sample = '__apply_corr_cloned_sample' @@ -635,11 +647,12 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S if diffraction_run and not checkUnitIs(container, 'dSpacing'): raise ValueError("Sample and Can must both have the same units.") - (instr, can_run) = getInstrRun(container) + can_run = getInstrRun(container)[1] if ScaleOrNotToScale: - #use temp workspace so we don't modify original data - Scale(InputWorkspace=container, OutputWorkspace=scaled_container, Factor=factor, Operation='Multiply') + # Use temp workspace so we don't modify original data + Scale(InputWorkspace=container, OutputWorkspace=scaled_container, + Factor=factor, Operation='Multiply') logger.information('Container scaled by %f' % factor) else: @@ -659,7 +672,6 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S cred_path = os.path.join(workdir,cor_result + ext + '.nxs') SaveNexusProcessed(InputWorkspace=cor_result + ext, Filename=cred_path) logger.information('Output file created : '+cred_path) - calc_plot = [cor_result + ext, sample] if not diffraction_run: res_plot = cor_result + '_rqw' @@ -721,7 +733,8 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S fout = outNm + str(i) CreateWorkspace(OutputWorkspace=fout, DataX=dataX, DataY=dataY, DataE=dataE, - Nspec=3, UnitX=x_unit, VerticalAxisUnit='Text', VerticalAxisValues=names) + Nspec=3, UnitX=x_unit, VerticalAxisUnit='Text', + VerticalAxisValues=names) if i == 0: group = fout @@ -735,7 +748,7 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S if Save: res_path = os.path.join(workdir,outNm[:-1] + '.nxs') SaveNexusProcessed(InputWorkspace=outNm[:-1], Filename=res_path) - logger.information('Output file created : '+res_path) + logger.information('Output file created : ' + res_path) DeleteWorkspace(cws) @@ -751,11 +764,11 @@ def plotCorrResult(inWS, PlotResult): plot_list = [] for i in range(0, nHist): plot_list.append(i) - res_plot=mp.plotSpectrum(inWS, plot_list) + MTD_PLOT.plotSpectrum(inWS, plot_list) if PlotResult == 'Contour' or PlotResult == 'Both': if nHist >= 5: #needs at least 5 hists for a contour - mp.importMatrixWorkspace(inWS).plotGraph2D() + MTD_PLOT.importMatrixWorkspace(inWS).plotGraph2D() def plotCorrContrib(plot_list, n): - con_plot = mp.plotSpectrum(plot_list, n) + MTD_PLOT.plotSpectrum(plot_list, n) diff --git a/Code/Mantid/scripts/Inelastic/IndirectImport.py b/Code/Mantid/scripts/Inelastic/IndirectImport.py index 34cf8d8e99f4..e88d525831ce 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectImport.py +++ b/Code/Mantid/scripts/Inelastic/IndirectImport.py @@ -1,16 +1,19 @@ -''' Temporary solutions to the messy problem of importing F2Py libraries into +""" +Temporary solutions to the messy problem of importing F2Py libraries into the Indirect scripts depending on platform and numpy package version. We also deal with importing the mantidplot module outside of MantidPlot here. -''' +""" import numpy import platform import sys from mantid import logger + def import_mantidplot(): - ''' Currently, all scripts in the PythonAlgorithms directory are imported + """ + Currently, all scripts in the PythonAlgorithms directory are imported during system tests. Unfortunately, these tests are run outside of MantidPlot and so are incompatible with scripts that import the "mantidplot" module. As a result, an error message is dumped to the @@ -20,7 +23,7 @@ def import_mantidplot(): Here, we silently catch all ImportErrors so that this does not occur. @returns the mantidplot module. - ''' + """ try: import mantidplot return mantidplot @@ -29,9 +32,11 @@ def import_mantidplot(): # scripts are not needed there. return None + def _os_env(): return platform.system() + platform.architecture()[0] + def _lib_suffix(): if platform.system() == "Windows": suffix = "win" @@ -41,37 +46,37 @@ def _lib_suffix(): return "" return "_" + suffix + platform.architecture()[0][0:2] + def _numpy_ver(): - return numpy.version.short_version + """ + Gets the version of Numpy installed on the host system. -def _linux_distro_name(): - return platform.linux_distribution()[0] + @return Version number + """ + return numpy.version.short_version -def _linux_distro_version(): - return platform.linux_distribution()[1] def unsupported_message(): logger.error('F2Py functionality not currently available on your platform.') sys.exit() + def is_supported_f2py_platform(): - ''' We check for numpy version, as if Linux we check its distro and version + """ + We check for numpy version, as if Linux we check its distro and version as well. @returns True if we are currently on a platform that supports the F2Py libraries, else False. - ''' + """ if _os_env().startswith("Windows") and _numpy_ver() == "1.6.2": return True - #if _os_env() == "Linux64bit" and \ - # _linux_distro_name()[0:24] == "Red Hat Enterprise Linux" and \ - # _linux_distro_version() == "6.2" and \ - # _numpy_ver() == "1.3.0": - # return True return False + def import_f2py(lib_base_name): - ''' Until we can include the compilation process of Indirect F2Py modules + """ + Until we can include the compilation process of Indirect F2Py modules into the automated build of Mantid, we are forced to compile the libraries separately on every platform we wish to support. @@ -83,7 +88,7 @@ def import_f2py(lib_base_name): of "QLres". @returns the imported module. - ''' + """ # Only proceed if we are indeed on one of the supported platforms. assert is_supported_f2py_platform() @@ -91,9 +96,11 @@ def import_f2py(lib_base_name): return __import__(lib_name) + def run_f2py_compatibility_test(): - ''' Convenience method that raises an exception should a user try to run + """ + Convenience method that raises an exception should a user try to run the F2Py libraries on an incompatible platform. - ''' + """ if not is_supported_f2py_platform(): raise RuntimeError("F2Py programs NOT available on this platform.") From 39f854ad28f30d706831a8146d69756b0a89380a Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Mon, 16 Feb 2015 15:34:01 +0000 Subject: [PATCH 224/414] Fix bug in setting PATH variable. It needs to come after choosing the configuration. Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript.bat | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript.bat b/Code/Mantid/Build/Jenkins/buildscript.bat index 694da2eb62c4..0e9e6e37cdbd 100755 --- a/Code/Mantid/Build/Jenkins/buildscript.bat +++ b/Code/Mantid/Build/Jenkins/buildscript.bat @@ -17,8 +17,6 @@ cd %WORKSPACE%\Code call fetch_Third_Party win64 cd %WORKSPACE% -set PATH=%WORKSPACE%\Code\Third_Party\lib\win64;%WORKSPACE%\Code\Third_Party\lib\win64\Python27;%PARAVIEW_DIR%\bin\%BUILD_CONFIG%;%PATH% - ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Set up the location for local object store outside of the build and source :: tree, which can be shared by multiple builds. @@ -85,6 +83,10 @@ if not "%JOB_NAME%"=="%JOB_NAME:relwithdbg=%" ( ) else ( set BUILD_CONFIG=Release )) +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Update the PATH so that we can find everything +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +set PATH=%WORKSPACE%\Code\Third_Party\lib\win64;%WORKSPACE%\Code\Third_Party\lib\win64\Python27;%PARAVIEW_DIR%\bin\%BUILD_CONFIG%;%PATH% ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: CMake configuration From 6dc3ae2935ee63f910173d777c6c72d334742467 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Mon, 16 Feb 2015 16:05:43 +0000 Subject: [PATCH 225/414] Follow the standard convention for the system tests results filename. Refs #10870 --- Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py b/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py index ca5c5f1be96e..9952384010a6 100755 --- a/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py +++ b/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py @@ -115,7 +115,7 @@ # report the errors success = reporter.reportStatus() -xml_report = open(os.path.join(mtdconf.saveDir, "SystemTestsReport.xml"),'w') +xml_report = open(os.path.join(mtdconf.saveDir, "TEST-systemtests.xml"),'w') xml_report.write(reporter.getResults()) xml_report.close() From e307846882ae1e49317b84babf0fea10f88bbef6 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 16:22:56 +0000 Subject: [PATCH 226/414] More refactoring for PyLint in scripts Refs #10706 --- .../scripts/Inelastic/IndirectAbsCor.py | 89 ++++----- .../Mantid/scripts/Inelastic/IndirectBayes.py | 169 +++++++++++------- .../scripts/Inelastic/IndirectCommon.py | 32 ++-- .../scripts/Inelastic/IndirectDataAnalysis.py | 79 +++----- .../scripts/Inelastic/IndirectNeutron.py | 33 ++-- 5 files changed, 209 insertions(+), 193 deletions(-) diff --git a/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py b/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py index 532cf685079a..e0149af7f7a1 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py +++ b/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py @@ -1,13 +1,13 @@ # IDA F2PY Absorption Corrections Wrapper ## Handle selection of .pyd files for absorption corrections -import platform, sys +import sys from IndirectImport import * from IndirectCommon import * from mantid.simpleapi import * from mantid import config, logger, mtd import math, os.path, numpy as np -mp = import_mantidplot() +MTD_PLOT = import_mantidplot() def WaveRange(inWS, efixed): # create a list of 10 equi-spaced wavelengths spanning the input data @@ -231,33 +231,33 @@ def plotAbs(workspaces, plotOpt): return if plotOpt == 'Wavelength' or plotOpt == 'Both': - graph = mp.plotSpectrum(workspaces, 0) + graph = MTD_PLOT.plotSpectrum(workspaces, 0) if plotOpt == 'Angle' or plotOpt == 'Both': - graph = mp.plotTimeBin(workspaces, 0) - graph.activeLayer().setAxisTitle(mp.Layer.Bottom, 'Angle') + graph = MTD_PLOT.plotTimeBin(workspaces, 0) + graph.activeLayer().setAxisTitle(MTD_PLOT.Layer.Bottom, 'Angle') def AbsRunFeeder(input_ws, can_ws, geom, ncan, size, avar, density, beam_width=None, sample_formula=None, can_formula=None, sigs=None, siga=None, plot_opt='None', save=False): """ - Handles the feeding of input and plotting of output for the F2PY - absorption correction routine. - - @param input_ws - workspace to generate corrections for - @param geom - type of geometry used (flat plate or cylinder) - @param beam_width - width of the beam used. If None this will be taken from the IPF - @param ncan - number of cans used. - @param size - sample & can thickness - @param sample_formula - optional, chemical formula for the sample - @param cam_formula - optional, chemical formula for the can - @param density - density of the sample and cans(s) - @param sigs - scattering for sample and can(s) - @param siga - absorption for sample and can(s) - @param avar - sample angle - @param plot_opt - whether to plot output - @param save - whether to save the output to file - @return The result workspace group + Handles the feeding of input and plotting of output for the F2PY + absorption correction routine. + + @param input_ws - workspace to generate corrections for + @param geom - type of geometry used (flat plate or cylinder) + @param beam_width - width of the beam used. If None this will be taken from the IPF + @param ncan - number of cans used. + @param size - sample & can thickness + @param sample_formula - optional, chemical formula for the sample + @param cam_formula - optional, chemical formula for the can + @param density - density of the sample and cans(s) + @param sigs - scattering for sample and can(s) + @param siga - absorption for sample and can(s) + @param avar - sample angle + @param plot_opt - whether to plot output + @param save - whether to save the output to file + @return The result workspace group """ StartTime('CalculateCorrections') @@ -288,7 +288,8 @@ def AbsRunFeeder(input_ws, can_ws, geom, ncan, size, avar, density, beam_width=N #set sample material based on input or formula if sample_formula is not None: - SetSampleMaterial(InputWorkspace=input_ws, ChemicalFormula=sample_formula, SampleNumberDensity=density[0]) + SetSampleMaterial(InputWorkspace=input_ws, ChemicalFormula=sample_formula, + SampleNumberDensity=density[0]) sample = mtd[input_ws].sample() sam_mat = sample.getMaterial() @@ -300,7 +301,8 @@ def AbsRunFeeder(input_ws, can_ws, geom, ncan, size, avar, density, beam_width=N if can_formula is not None and ncan == 2: #set can material based on input or formula - SetSampleMaterial(InputWorkspace=can_ws, ChemicalFormula=can_formula, SampleNumberDensity=density[1]) + SetSampleMaterial(InputWorkspace=can_ws, ChemicalFormula=can_formula, + SampleNumberDensity=density[1]) can_sample = mtd[can_ws].sample() can_mat = can_sample.getMaterial() @@ -323,19 +325,19 @@ def AbsRunFeeder(input_ws, can_ws, geom, ncan, size, avar, density, beam_width=N def FlatAbs(ncan, thick, density, sigs, siga, angles, waves): """ - FlatAbs - calculate flat plate absorption factors - - For more information See: - - MODES User Guide: http://www.isis.stfc.ac.uk/instruments/iris/data-analysis/modes-v3-user-guide-6962.pdf - - C J Carlile, Rutherford Laboratory report, RL-74-103 (1974) - - @param sigs - list of scattering cross-sections - @param siga - list of absorption cross-sections - @param density - list of density - @param ncan - =0 no can, >1 with can - @param thick - list of thicknesses: sample thickness, can thickness1, can thickness2 - @param angles - list of angles - @param waves - list of wavelengths + FlatAbs - calculate flat plate absorption factors + + For more information See: + - MODES User Guide: http://www.isis.stfc.ac.uk/instruments/iris/data-analysis/modes-v3-user-guide-6962.pdf + - C J Carlile, Rutherford Laboratory report, RL-74-103 (1974) + + @param sigs - list of scattering cross-sections + @param siga - list of absorption cross-sections + @param density - list of density + @param ncan - =0 no can, >1 with can + @param thick - list of thicknesses: sample thickness, can thickness1, can thickness2 + @param angles - list of angles + @param waves - list of wavelengths """ PICONV = math.pi/180. @@ -355,7 +357,7 @@ def FlatAbs(ncan, thick, density, sigs, siga, angles, waves): acc = np.ones(nlam) # case where tsec is close to 90 degrees. CALCULATION IS UNRELIABLE - if (abs(abs(tsec)-90.0) < 1.0): + if abs(abs(tsec)-90.0) < 1.0: #default to 1 for everything return ass, assc, acsc, acc else: @@ -385,7 +387,7 @@ def FlatAbs(ncan, thick, density, sigs, siga, angles, waves): sampleSec1, sampleSec2 = calcThicknessAtSec(sampleXSection, samThickness, [sec1, sec2]) - if (sec2 < 0.): + if sec2 < 0.0: ass = fs / samThickness else: ass= np.exp(-sampleSec2) * fs / samThickness @@ -394,7 +396,8 @@ def FlatAbs(ncan, thick, density, sigs, siga, angles, waves): if useCan: #calculate can cross section canXSection = (canScatt + canAbs * waves / 1.8) * canDensity - assc, acsc, acc = calcFlatAbsCan(ass, canXSection, canThickness1, canThickness2, sampleSec1, sampleSec2, [sec1, sec2]) + assc, acsc, acc = calcFlatAbsCan(ass, canXSection, canThickness1, canThickness2, + sampleSec1, sampleSec2, [sec1, sec2]) return ass, assc, acsc, acc @@ -429,9 +432,9 @@ def calcFlatAbsCan(ass, canXSection, canThickness1, canThickness2, sampleSec1, s f2 = vecFact(canXSection,canThickness2,sec1,sec2) canThick1Sec1, canThick1Sec2 = calcThicknessAtSec(canXSection, canThickness1, sec) - canThick2Sec1, canThick2Sec2 = calcThicknessAtSec(canXSection, canThickness2, sec) + canThick2Sec2 = calcThicknessAtSec(canXSection, canThickness2, sec)[1] - if (sec2 < 0.): + if sec2 < 0.0: val = np.exp(-(canThick1Sec1-canThick1Sec2)) assc = ass * val @@ -452,7 +455,7 @@ def calcFlatAbsCan(ass, canXSection, canThickness1, canThickness2, sampleSec1, s canThickness = canThickness1 + canThickness2 - if(canThickness > 0.): + if canThickness > 0.0: acc = (acc1 + acc2) / canThickness acsc = (acsc1 + acsc2) / canThickness diff --git a/Code/Mantid/scripts/Inelastic/IndirectBayes.py b/Code/Mantid/scripts/Inelastic/IndirectBayes.py index 90123e79487c..a3779479261a 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectBayes.py +++ b/Code/Mantid/scripts/Inelastic/IndirectBayes.py @@ -17,7 +17,7 @@ from mantid import config, logger, mtd from IndirectCommon import * import sys, platform, math, os.path, numpy as np -mp = import_mantidplot() +MTD_PLOT = import_mantidplot() def readASCIIFile(file_name): workdir = config['defaultsave.directory'] @@ -55,7 +55,7 @@ def CalcErange(inWS,ns,erange,binWidth): Xin = Xin.reshape(len(Xin)/binWidth, binWidth) #sum and normalise values in bins - Xout = [sum(bin)*bnorm for bin in Xin] + Xout = [sum(bin) * bnorm for bin in Xin] #count number of bins nbins = len(Xout) @@ -97,7 +97,7 @@ def ReadNormFile(readRes,resnormWS,nsam): # get norm & scale values nrm = len(Xin) # no. points from length of x array if nrm == 0: raise ValueError('ResNorm file has no Intensity points') - Xin = mtd[resnormWS+'_Stretch'].readX(0) # no. points from length of x array + Xin = mtd[resnormWS+'_Stretch'].readX(0) # no. points from length of x array if len(Xin) == 0: raise ValueError('ResNorm file has no xscale points') if nrm != nsam: # check that no. groups are the same @@ -129,7 +129,7 @@ def ReadWidthFile(readWidth,widthFile,numSampleGroups): asc.append(line) handle.close() - except Exception, e: + except Exception: raise ValueError('Failed to read width file') numLines = len(asc) @@ -141,8 +141,8 @@ def ReadWidthFile(readWidth,widthFile,numSampleGroups): raise ValueError('Width groups (' +str(numLines) + ') not = Sample (' +str(numSampleGroups) +')') else: # no file: just use constant values - widthY = np.zeros(numSampleGroups) - widthE = np.zeros(numSampleGroups) + widthY = np.zeros(numSampleGroups) + widthE = np.zeros(numSampleGroups) # pad for Fortran call widthY = PadArray(widthY,51) @@ -337,18 +337,20 @@ def QLRun(program,samWS,resWS,resnormWS,erange,nbins,Fit,wfile,Loop,Plot,Save): CreateWorkspace(OutputWorkspace=probWS, DataX=xProb, DataY=yProb, DataE=eProb, Nspec=3, UnitX='MomentumTransfer') outWS = C2Fw(samWS[:-4],fname) - if (Plot != 'None'): + if Plot != 'None': QuasiPlot(fname,Plot,res_plot,Loop) if program == 'QSe': outWS = C2Se(fname) - if (Plot != 'None'): + if Plot != 'None': QuasiPlot(fname,Plot,res_plot,Loop) #Add some sample logs to the output workspaces CopyLogs(InputWorkspace=samWS, OutputWorkspace=outWS) - QLAddSampleLogs(outWS, resWS, prog, background, elastic, erange, (nbin, nrbin), resnormWS, wfile) + QLAddSampleLogs(outWS, resWS, prog, background, elastic, erange, + (nbin, nrbin), resnormWS, wfile) CopyLogs(InputWorkspace=samWS, OutputWorkspace=fitWS) - QLAddSampleLogs(fitWS, resWS, prog, background, elastic, erange, (nbin, nrbin), resnormWS, wfile) + QLAddSampleLogs(fitWS, resWS, prog, background, elastic, erange, + (nbin, nrbin), resnormWS, wfile) if Save: fit_path = os.path.join(workdir,fitWS+'.nxs') @@ -365,24 +367,37 @@ def QLAddSampleLogs(workspace, res_workspace, fit_program, background, elastic_p sample_binning, res_binning = binning energy_min, energy_max = e_range - AddSampleLog(Workspace=workspace, LogName="res_file", LogType="String", LogText=res_workspace) - AddSampleLog(Workspace=workspace, LogName="fit_program", LogType="String", LogText=fit_program) - AddSampleLog(Workspace=workspace, LogName="background", LogType="String", LogText=str(background)) - AddSampleLog(Workspace=workspace, LogName="elastic_peak", LogType="String", LogText=str(elastic_peak)) - AddSampleLog(Workspace=workspace, LogName="energy_min", LogType="Number", LogText=str(energy_min)) - AddSampleLog(Workspace=workspace, LogName="energy_max", LogType="Number", LogText=str(energy_max)) - AddSampleLog(Workspace=workspace, LogName="sample_binning", LogType="Number", LogText=str(sample_binning)) - AddSampleLog(Workspace=workspace, LogName="resolution_binning", LogType="Number", LogText=str(res_binning)) + AddSampleLog(Workspace=workspace, LogName="res_file", + LogType="String", LogText=res_workspace) + AddSampleLog(Workspace=workspace, LogName="fit_program", + LogType="String", LogText=fit_program) + AddSampleLog(Workspace=workspace, LogName="background", + LogType="String", LogText=str(background)) + AddSampleLog(Workspace=workspace, LogName="elastic_peak", + LogType="String", LogText=str(elastic_peak)) + AddSampleLog(Workspace=workspace, LogName="energy_min", + LogType="Number", LogText=str(energy_min)) + AddSampleLog(Workspace=workspace, LogName="energy_max", + LogType="Number", LogText=str(energy_max)) + AddSampleLog(Workspace=workspace, LogName="sample_binning", + LogType="Number", LogText=str(sample_binning)) + AddSampleLog(Workspace=workspace, LogName="resolution_binning", + LogType="Number", LogText=str(res_binning)) resnorm_used = (resnorm_workspace != '') - AddSampleLog(Workspace=workspace, LogName="resnorm", LogType="String", LogText=str(resnorm_used)) + AddSampleLog(Workspace=workspace, LogName="resnorm", + LogType="String", LogText=str(resnorm_used)) if resnorm_used: - AddSampleLog(Workspace=workspace, LogName="resnorm_file", LogType="String", LogText=resnorm_workspace) + AddSampleLog(Workspace=workspace, LogName="resnorm_file", + LogType="String", LogText=resnorm_workspace) width_file_used = (width_file != '') - AddSampleLog(Workspace=workspace, LogName="width", LogType="String", LogText=str(width_file_used)) + AddSampleLog(Workspace=workspace, LogName="width", + LogType="String", LogText=str(width_file_used)) if width_file_used: - AddSampleLog(Workspace=workspace, LogName="width_file", LogType="String", LogText=width_file) + AddSampleLog(Workspace=workspace, LogName="width_file", + LogType="String", LogText=width_file) + def yield_floats(block): #yield a list of floats from a list of lines of text @@ -390,6 +405,7 @@ def yield_floats(block): for line in block: yield ExtractFloat(line) + def read_ql_file(file_name, nl): #offet to ignore header header_offset = 8 @@ -463,6 +479,7 @@ def read_ql_file(file_name, nl): return q_data, (amp_data, FWHM_data, height_data), (amp_error, FWHM_error, height_error) + def C2Fw(prog,sname): output_workspace = sname+'_Result' num_spectra = 0 @@ -513,12 +530,12 @@ def C2Fw(prog,sname): axis_names.append('f'+str(nl)+'.f0.'+'Height') x.append(x_data) for j in range(1,nl+1): - axis_names.append('f'+str(nl)+'.f'+str(j)+'.Amplitude') - x.append(x_data) - axis_names.append('f'+str(nl)+'.f'+str(j)+'.FWHM') - x.append(x_data) - axis_names.append('f'+str(nl)+'.f'+str(j)+'.EISF') - x.append(x_data) + axis_names.append('f'+str(nl)+'.f'+str(j)+'.Amplitude') + x.append(x_data) + axis_names.append('f'+str(nl)+'.f'+str(j)+'.FWHM') + x.append(x_data) + axis_names.append('f'+str(nl)+'.f'+str(j)+'.EISF') + x.append(x_data) x = np.asarray(x).flatten() y = np.asarray(y).flatten() @@ -529,6 +546,7 @@ def C2Fw(prog,sname): return output_workspace + def SeBlock(a,first): #read Ascii block of Integers line1 = a[first] first += 1 @@ -560,6 +578,7 @@ def SeBlock(a,first): #read Ascii block of Integ first += 1 return first,Q,int0,fw,int,be #values as list + def C2Se(sname): prog = 'QSe' outWS = sname+'_Result' @@ -617,22 +636,22 @@ def C2Se(sname): UnitX='MomentumTransfer', VerticalAxisUnit='Text', VerticalAxisValues=Vaxis, YUnitLabel='') return outWS + def QuasiPlot(ws_stem,plot_type,res_plot,sequential): if plot_type: if sequential: ws_name = ws_stem + '_Result' - num_spectra = mtd[ws_name].getNumberHistograms() - if (plot_type == 'Prob' or plot_type == 'All'): + if plot_type == 'Prob' or plot_type == 'All': prob_ws = ws_stem+'_Prob' if prob_ws in mtd.getObjectNames(): - mp.plotSpectrum(prob_ws,[1,2],False) + MTD_PLOT.plotSpectrum(prob_ws,[1,2],False) QuasiPlotParameters(ws_name, plot_type) - if (plot_type == 'Fit' or plot_type == 'All'): + if plot_type == 'Fit' or plot_type == 'All': fWS = ws_stem+'_Workspace_0' - f_plot=mp.plotSpectrum(fWS,res_plot,False) + MTD_PLOT.plotSpectrum(fWS,res_plot,False) def QuasiPlotParameters(ws_name, plot_type): @@ -641,18 +660,20 @@ def QuasiPlotParameters(ws_name, plot_type): in the workspace @param ws_name :: name of the workspace to plot from. This function expects it has a TextAxis - @param plot_type :: the name of the parameter to plot (or All if all parameters should be plotted) + @param plot_type :: the name of the parameter to plot (or All if all parameters should + be plotted) """ num_spectra = mtd[ws_name].getNumberHistograms() param_names = ['Amplitude', 'FWHM', 'Beta'] for param_name in param_names: - if (plot_type == param_name or plot_type == 'All'): + if plot_type == param_name or plot_type == 'All': spectra_indicies = [i for i in range(num_spectra) if param_name in mtd[ws_name].getAxis(1).label(i)] - if(len(spectra_indicies) > 0): + if len(spectra_indicies) > 0: plotSpectra(ws_name, param_name, indicies=spectra_indicies[:3]) + # Quest programs def CheckBetSig(nbs): Nsig = int(nbs[1]) @@ -742,7 +763,7 @@ def QuestRun(samWS,resWS,nbs,erange,nbins,Fit,Loop,Plot,Save): dataXb = xbout[:Nbet] dataYb = ybout[:Nbet] zpWS = fname + '_Zp' +str(m) - if (m > 0): + if m > 0: Qaxis += ',' Qaxis += str(Q[m]) @@ -759,7 +780,8 @@ def QuestRun(samWS,resWS,nbs,erange,nbins,Fit,Loop,Plot,Save): dataEz = np.append(dataEz,eBet0) CreateWorkspace(OutputWorkspace=zpWS, DataX=dataXz, DataY=dataYz, DataE=dataEz, - Nspec=Nsig, UnitX='MomentumTransfer', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=dataXs) + Nspec=Nsig, UnitX='MomentumTransfer', + VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=dataXs) unitx = mtd[zpWS].getAxis(0).setUnit("Label") unitx.setLabel('beta' , '') @@ -817,28 +839,36 @@ def QuestRun(samWS,resWS,nbs,erange,nbins,Fit,Loop,Plot,Save): logger.information('Output file for Fit : ' + fpath) logger.information('Output file for Contours : ' + cpath) - if (Plot != 'None' and Loop == True): + if Plot != 'None' and Loop == True: QuestPlot(fname,Plot) EndTime('Quest') def QuestAddSampleLogs(workspace, res_workspace, background, elastic_peak, e_range, sample_binning, sigma, beta): energy_min, energy_max = e_range - AddSampleLog(Workspace=workspace, LogName="res_file", LogType="String", LogText=res_workspace) - AddSampleLog(Workspace=workspace, LogName="background", LogType="String", LogText=str(background)) - AddSampleLog(Workspace=workspace, LogName="elastic_peak", LogType="String", LogText=str(elastic_peak)) - AddSampleLog(Workspace=workspace, LogName="energy_min", LogType="Number", LogText=str(energy_min)) - AddSampleLog(Workspace=workspace, LogName="energy_max", LogType="Number", LogText=str(energy_max)) - AddSampleLog(Workspace=workspace, LogName="sample_binning", LogType="Number", LogText=str(sample_binning)) - AddSampleLog(Workspace=workspace, LogName="sigma", LogType="Number", LogText=str(sigma)) - AddSampleLog(Workspace=workspace, LogName="beta", LogType="Number", LogText=str(beta)) + AddSampleLog(Workspace=workspace, LogName="res_file", + LogType="String", LogText=res_workspace) + AddSampleLog(Workspace=workspace, LogName="background", + LogType="String", LogText=str(background)) + AddSampleLog(Workspace=workspace, LogName="elastic_peak", + LogType="String", LogText=str(elastic_peak)) + AddSampleLog(Workspace=workspace, LogName="energy_min", + LogType="Number", LogText=str(energy_min)) + AddSampleLog(Workspace=workspace, LogName="energy_max", + LogType="Number", LogText=str(energy_max)) + AddSampleLog(Workspace=workspace, LogName="sample_binning", + LogType="Number", LogText=str(sample_binning)) + AddSampleLog(Workspace=workspace, LogName="sigma", + LogType="Number", LogText=str(sigma)) + AddSampleLog(Workspace=workspace, LogName="beta", + LogType="Number", LogText=str(beta)) def QuestPlot(inputWS,Plot): - if (Plot == 'Sigma' or Plot == 'All'): - sig_plot=mp.importMatrixWorkspace(inputWS+'_Sigma').plotGraph2D() - if (Plot == 'Beta' or Plot == 'All'): - beta_plot=mp.importMatrixWorkspace(inputWS+'_Beta').plotGraph2D() + if Plot == 'Sigma' or Plot == 'All': + MTD_PLOT.importMatrixWorkspace(inputWS+'_Sigma').plotGraph2D() + if Plot == 'Beta' or Plot == 'All': + MTD_PLOT.importMatrixWorkspace(inputWS+'_Beta').plotGraph2D() # ResNorm programs def ResNormRun(vname,rname,erange,nbin,Plot='None',Save=False): @@ -895,12 +925,14 @@ def ResNormRun(vname,rname,erange,nbin,Plot='None',Save=False): else: yPar1 = np.append(yPar1,pfit[0]) yPar2 = np.append(yPar2,pfit[1]) - CreateWorkspace(OutputWorkspace='__datmp', DataX=dataX, DataY=yout[:nd], DataE=eout[:nd], - NSpec=1, UnitX='DeltaE') - ConjoinWorkspaces(InputWorkspace1='Data', InputWorkspace2='__datmp', CheckOverlapping=False) - CreateWorkspace(OutputWorkspace='__f1tmp', DataX=dataX, DataY=yfit[:nd], DataE=np.zeros(nd), - NSpec=1, UnitX='DeltaE') - ConjoinWorkspaces(InputWorkspace1='Fit', InputWorkspace2='__f1tmp', CheckOverlapping=False) + CreateWorkspace(OutputWorkspace='__datmp', DataX=dataX, DataY=yout[:nd], + DataE=eout[:nd], NSpec=1, UnitX='DeltaE') + ConjoinWorkspaces(InputWorkspace1='Data', InputWorkspace2='__datmp', + CheckOverlapping=False) + CreateWorkspace(OutputWorkspace='__f1tmp', DataX=dataX, DataY=yfit[:nd], + DataE=np.zeros(nd), NSpec=1, UnitX='DeltaE') + ConjoinWorkspaces(InputWorkspace1='Fit', InputWorkspace2='__f1tmp', + CheckOverlapping=False) resnorm_intesity = fname+'_ResNorm_Intensity' resnorm_stretch = fname+'_ResNorm_Stretch' @@ -934,24 +966,27 @@ def ResNormRun(vname,rname,erange,nbin,Plot='None',Save=False): logger.information('Parameter file created : ' + par_path) logger.information('Fit file created : ' + fit_path) - if (Plot != 'None'): + if Plot != 'None': ResNormPlot(fname,Plot) EndTime('ResNorm') def ResNormAddSampleLogs(workspace, e_range, v_binning): energy_min, energy_max = e_range - AddSampleLog(Workspace=workspace, LogName="energy_min", LogType="Number", LogText=str(energy_min)) - AddSampleLog(Workspace=workspace, LogName="energy_max", LogType="Number", LogText=str(energy_max)) - AddSampleLog(Workspace=workspace, LogName="van_binning", LogType="Number", LogText=str(v_binning)) + AddSampleLog(Workspace=workspace, LogName="energy_min", + LogType="Number", LogText=str(energy_min)) + AddSampleLog(Workspace=workspace, LogName="energy_max", + LogType="Number", LogText=str(energy_max)) + AddSampleLog(Workspace=workspace, LogName="van_binning", + LogType="Number", LogText=str(v_binning)) def ResNormPlot(inputWS,Plot): - if (Plot == 'Intensity' or Plot == 'All'): + if Plot == 'Intensity' or Plot == 'All': iWS = inputWS + '_ResNorm_Intensity' - i_plot=mp.plotSpectrum(iWS,0,False) - if (Plot == 'Stretch' or Plot == 'All'): + MTD_PLOT.plotSpectrum(iWS,0,False) + if Plot == 'Stretch' or Plot == 'All': sWS = inputWS + '_ResNorm_Stretch' - s_plot=mp.plotSpectrum(sWS,0,False) - if (Plot == 'Fit' or Plot == 'All'): + MTD_PLOT.plotSpectrum(sWS,0,False) + if Plot == 'Fit' or Plot == 'All': fWS = inputWS + '_ResNorm_Fit' - f_plot=mp.plotSpectrum(fWS,0,False) + MTD_PLOT.plotSpectrum(fWS,0,False) diff --git a/Code/Mantid/scripts/Inelastic/IndirectCommon.py b/Code/Mantid/scripts/Inelastic/IndirectCommon.py index d6147a76cc78..794eb6ce274b 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectCommon.py +++ b/Code/Mantid/scripts/Inelastic/IndirectCommon.py @@ -31,8 +31,8 @@ def getInstrRun(ws_name): @param ws_name - name of the workspace @return tuple of form (instrument, run number) """ - ws = mtd[ws_name] - run_number = str(ws.getRunNumber()) + workspace = mtd[ws_name] + run_number = str(workspace.getRunNumber()) if run_number == '0': # Attempt to parse run number off of name match = re.match(r'([a-zA-Z]+)([0-9]+)', ws_name) @@ -41,7 +41,7 @@ def getInstrRun(ws_name): else: raise RuntimeError("Could not find run number associated with workspace.") - instrument = ws.getInstrument().getName() + instrument = workspace.getInstrument().getName() facility = config.getFacility() instrument = facility.instrument(instrument).filePrefix(int(run_number)) instrument = instrument.lower() @@ -57,10 +57,10 @@ def getWSprefix(wsname): if wsname == '': return '' - ws = mtd[wsname] + workspace = mtd[wsname] facility = config['default.facility'] - ws_run = ws.getRun() + ws_run = workspace.getRun() if 'facility' in ws_run: facility = ws_run.getLogData('facility').value @@ -71,8 +71,8 @@ def getWSprefix(wsname): run_name = instrument + run_number try: - analyser = ws.getInstrument().getStringParameter('analyser')[0] - reflection = ws.getInstrument().getStringParameter('reflection')[0] + analyser = workspace.getInstrument().getStringParameter('analyser')[0] + reflection = workspace.getInstrument().getStringParameter('reflection')[0] except IndexError: analyser = '' reflection = '' @@ -114,21 +114,21 @@ def getDefaultWorkingDirectory(): def createQaxis(inputWS): result = [] - ws = mtd[inputWS] - num_hist = ws.getNumberHistograms() - if ws.getAxis(1).isSpectra(): - inst = ws.getInstrument() + workspace = mtd[inputWS] + num_hist = workspace.getNumberHistograms() + if workspace.getAxis(1).isSpectra(): + inst = workspace.getInstrument() sample_pos = inst.getSample().getPos() beam_pos = sample_pos - inst.getSource().getPos() for i in range(0, num_hist): efixed = getEfixed(inputWS, i) - detector = ws.getDetector(i) + detector = workspace.getDetector(i) theta = detector.getTwoTheta(sample_pos, beam_pos) / 2 lamda = math.sqrt(81.787 / efixed) q = 4 * math.pi * math.sin(theta) / lamda result.append(q) else: - axis = ws.getAxis(1) + axis = workspace.getAxis(1) msg = 'Creating Axis based on Detector Q value: ' if not axis.isNumeric(): msg += 'Input workspace must have either spectra or numeric axis.' @@ -421,7 +421,8 @@ def convertToElasticQ(input_ws, output_ws=None): axis = mtd[input_ws].getAxis(1) if axis.isSpectra(): e_fixed = getEfixed(input_ws) - ConvertSpectrumAxis(input_ws, Target='ElasticQ', EMode='Indirect', EFixed=e_fixed, OutputWorkspace=output_ws) + ConvertSpectrumAxis(input_ws, Target='ElasticQ', EMode='Indirect', EFixed=e_fixed, + OutputWorkspace=output_ws) elif axis.isNumeric(): # Check that units are Momentum Transfer @@ -512,7 +513,8 @@ def convertParametersToWorkspace(params_table, x_column, param_names, output_nam column_error_names = search_for_fit_params(param_name + '_Err', params_table) param_workspaces = [] for name, error_name in zip(column_names, column_error_names): - ConvertTableToMatrixWorkspace(params_table, x_column, name, error_name, OutputWorkspace=name) + ConvertTableToMatrixWorkspace(params_table, x_column, name, error_name, + OutputWorkspace=name) param_workspaces.append(name) workspace_names.append(param_workspaces) diff --git a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py index 6edb1ac5074b..e9d46faca479 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py +++ b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py @@ -8,34 +8,6 @@ from mantid import * -############################################################################## -# Misc. Helper Functions -############################################################################## - -def split(l, n): - """ - Yield successive n-sized chunks from l. - """ - for i in xrange(0, len(l), n): - yield l[i:i+n] - -def segment(l, fromIndex, toIndex): - for i in xrange(fromIndex, toIndex + 1): - yield l[i] - -def trimData(nSpec, vals, min, max): - result = [] - chunk_size = len(vals / nSpec) - assert min >= 0, 'trimData: min is less then zero' - assert max <= chunk_size - 1, 'trimData: max is greater than the number of spectra' - assert min <= max, 'trimData: min is greater than max' - chunks = split(vals, chunk_size) - for chunk in chunks: - seg = segment(chunk, min, max) - for val in seg: - result.append(val) - return result - ############################################################################## # ConvFit ############################################################################## @@ -89,11 +61,13 @@ def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin using_delta_func = ftype[:5] == 'Delta' lorentzians = ftype[5:6] if using_delta_func else ftype[:1] - logger.information('Input files : '+str(inputWS)) - logger.information('Fit type : Delta = ' + str(using_delta_func) + ' ; Lorentzians = ' + str(lorentzians)) - logger.information('Background type : ' + bgd) + logger.information('Input files: ' + str(inputWS)) + logger.information('Fit type: Delta=%s; Lorentzians=%s' % ( + str(using_delta_func), str(lorentzians))) + logger.information('Background type: ' + bgd) - output_workspace = '%sconv_%s%s_s%d_to_%d' % (getWSprefix(inputWS), ftype, bgd, specMin, specMax) + output_workspace = '%sconv_%s%s_s%d_to_%d' % ( + getWSprefix(inputWS), ftype, bgd, specMin, specMax) #convert input workspace to get Q axis temp_fit_workspace = "__convfit_fit_ws" @@ -147,8 +121,9 @@ def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin RenameWorkspace(InputWorkspace=output_workspace, OutputWorkspace=output_workspace + "_Parameters") fit_workspaces = mtd[output_workspace + '_Workspaces'].getNames() - for i, ws in enumerate(fit_workspaces): - RenameWorkspace(ws, OutputWorkspace=output_workspace + '_' + str(i+specMin) + '_Workspace') + for i, workspace in enumerate(fit_workspaces): + RenameWorkspace(workspace, + OutputWorkspace='%s_%d_Workspace' % (output_workspace, i + specMin)) if Save: # path name for nxs file @@ -214,9 +189,9 @@ def furyfitSeq(inputWS, func, ftype, startx, endx, spec_min=0, spec_max=None, in # Process generated workspaces wsnames = mtd[fit_group].getNames() - for i, ws in enumerate(wsnames): + for i, workspace in enumerate(wsnames): output_ws = output_workspace + '_%d_Workspace' % i - RenameWorkspace(ws, OutputWorkspace=output_ws) + RenameWorkspace(workspace, OutputWorkspace=output_ws) sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': fit_type, 'intensities_constrained': intensities_constrained, 'beta_constrained': False} @@ -271,8 +246,8 @@ def furyfitMult(inputWS, function, ftype, startx, endx, spec_min=0, spec_max=Non transposeFitParametersTable(params_table) #set first column of parameter table to be axis values - ax = mtd[tmp_fit_workspace].getAxis(1) - axis_values = ax.extractValues() + x_axis = mtd[tmp_fit_workspace].getAxis(1) + axis_values = x_axis.extractValues() for i, value in enumerate(axis_values): mtd[params_table].setCell('axis-1', i, value) @@ -336,11 +311,11 @@ def createFuryMultiDomainFunction(function, input_ws): def furyFitSaveWorkspaces(save_workspaces): workdir = getDefaultWorkingDirectory() - for ws in save_workspaces: + for workspace in save_workspaces: #save workspace to default directory - fpath = os.path.join(workdir, ws+'.nxs') - SaveNexusProcessed(InputWorkspace=ws, Filename=fpath) - logger.information(ws + ' output to file : '+fpath) + fpath = os.path.join(workdir, workspace+'.nxs') + SaveNexusProcessed(InputWorkspace=workspace, Filename=fpath) + logger.information(workspace + ' output to file : '+fpath) def furyfitPlotSeq(ws, plot): @@ -357,8 +332,8 @@ def furyfitPlotSeq(ws, plot): ############################################################################## def msdfitPlotSeq(inputWS, xlabel): - ws = mtd[inputWS+'_A1'] - if len(ws.readX(0)) > 1: + workspace = mtd[inputWS + '_A1'] + if len(workspace.readX(0)) > 1: msd_plot = MTD_PLOT.plotSpectrum(inputWS+'_A1',0,True) msd_layer = msd_plot.activeLayer() msd_layer.setAxisTitle(MTD_PLOT.Layer.Bottom,xlabel) @@ -448,8 +423,8 @@ def plotInput(inputfiles,spectra=[]): spectra = [spectra[0], spectra[0]] OneSpectra = True workspaces = [] - for file in inputfiles: - root = LoadNexus(Filename=file) + for in_file in inputfiles: + root = LoadNexus(Filename=in_file) if not OneSpectra: GroupDetectors(root, root, DetectorList=range(spectra[0],spectra[1]+1) ) workspaces.append(root) @@ -471,9 +446,9 @@ def CubicFit(inputWS, spec): fit = Fit(Function=function, InputWorkspace=inputWS, WorkspaceIndex=spec, CreateOutput=True, Output='Fit') table = mtd['Fit_Parameters'] - A0 = table.cell(0,1) - A1 = table.cell(1,1) - A2 = table.cell(2,1) + A0 = table.cell(0, 1) + A1 = table.cell(1, 1) + A2 = table.cell(2, 1) Abs = [A0, A1, A2] logger.information('Group '+str(spec)+' of '+inputWS+' ; fit coefficients are : '+str(Abs)) return Abs @@ -534,9 +509,9 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): nHist = mtd[inputWS].getNumberHistograms() # Check that number of histograms in each corrections workspace matches # that of the input (sample) workspace - for ws in corrections: - if mtd[ws].getNumberHistograms() != nHist: - raise ValueError('Mismatch: num of spectra in '+ws+' and inputWS') + for workspace in corrections: + if mtd[workspace].getNumberHistograms() != nHist: + raise ValueError('Mismatch: num of spectra in '+workspace+' and inputWS') # Workspaces that hold intermediate results CorrectedSampleWS = '__csam' CorrectedCanWS = '__ccan' diff --git a/Code/Mantid/scripts/Inelastic/IndirectNeutron.py b/Code/Mantid/scripts/Inelastic/IndirectNeutron.py index ca8becb04006..d282afd8dad9 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectNeutron.py +++ b/Code/Mantid/scripts/Inelastic/IndirectNeutron.py @@ -3,10 +3,9 @@ from IndirectImport import * from mantid.simpleapi import * from mantid import config, logger, mtd, FileFinder -from mantid.kernel import V3D import sys, math, os.path, numpy as np from IndirectCommon import StartTime, EndTime, ExtractFloat, ExtractInt -mp = import_mantidplot() +MTD_PLOT = import_mantidplot() # Routines for Ascii file of raw data @@ -94,7 +93,7 @@ def ReadIbackGroup(a,first): #read Ascii block of spec def getFilePath(run,ext,instr): path = None fname = None - if(os.path.isfile(run)): + if os.path.isfile(run): #using full file path path = run #base name less extension @@ -255,7 +254,7 @@ def IbackStart(instr,run,ana,refl,rejectZ,useM,mapPath,Plot,Save): #Ascii s opath = os.path.join(workdir,outWS+'.nxs') SaveNexusProcessed(InputWorkspace=outWS, Filename=opath) logger.information('Output file : ' + opath) - if (Plot): + if Plot: plotForce(outWS,Plot) EndTime('Iback') @@ -347,7 +346,7 @@ def InxStart(instr,run,ana,refl,rejectZ,useM,mapPath,Plot,Save): opath = os.path.join(workdir,outWS+'.nxs') SaveNexusProcessed(InputWorkspace=outWS, Filename=opath) logger.information('Output file : ' + opath) - if (Plot): + if Plot: plotForce(outWS,Plot) EndTime('Inx') @@ -364,7 +363,8 @@ def RejectZero(inWS,tot): if nout == 0: RenameWorkspace(InputWorkspace='__tmp', OutputWorkspace=outWS) else: - ConjoinWorkspaces(InputWorkspace1=outWS, InputWorkspace2='__tmp',CheckOverlapping=False) + ConjoinWorkspaces(InputWorkspace1=outWS, InputWorkspace2='__tmp', + CheckOverlapping=False) nout += 1 else: logger.information('** spectrum '+str(n+1)+' rejected') @@ -378,7 +378,7 @@ def ReadMap(path): logger.information('Map file : ' + path +' ; spectra = ' +str(lasc-1)) val = ExtractInt(asc[0]) numb = val[0] - if (numb != (lasc-1)): + if numb != (lasc-1): error = 'Number of lines not equal to number of spectra' logger.error(error) sys.exit(error) @@ -388,7 +388,7 @@ def ReadMap(path): map.append(val[1]) return map -def UseMap(inWS,map): +def UseMap(inWS, map): nin = mtd[inWS].getNumberHistograms() # no. of hist/groups in sam nout = 0 outWS = inWS[:-3]+'red' @@ -399,28 +399,29 @@ def UseMap(inWS,map): if nout == 0: RenameWorkspace(InputWorkspace='__tmp', OutputWorkspace=outWS) else: - ConjoinWorkspaces(InputWorkspace1=outWS, InputWorkspace2='__tmp',CheckOverlapping=False) + ConjoinWorkspaces(InputWorkspace1=outWS, InputWorkspace2='__tmp', + CheckOverlapping=False) nout += 1 logger.information('** spectrum '+str(n+1)+' mapped') else: logger.information('** spectrum '+str(n+1)+' skipped') def plotForce(inWS,Plot): - if (Plot == 'Spectrum' or Plot == 'Both'): + if Plot == 'Spectrum' or Plot == 'Both': nHist = mtd[inWS].getNumberHistograms() if nHist > 10 : nHist = 10 plot_list = [] for i in range(0, nHist): plot_list.append(i) - res_plot=mp.plotSpectrum(inWS,plot_list) - if (Plot == 'Contour' or Plot == 'Both'): - cont_plot=mp.importMatrixWorkspace(inWS).plotGraph2D() + MTD_PLOT.plotSpectrum(inWS,plot_list) + if Plot == 'Contour' or Plot == 'Both': + MTD_PLOT.importMatrixWorkspace(inWS).plotGraph2D() def ChangeAngles(inWS,instr,theta): workdir = config['defaultsave.directory'] - file = instr+'_angles.txt' - path = os.path.join(workdir, file) + filename = instr+'_angles.txt' + path = os.path.join(workdir, filename) logger.information('Creating angles file : ' + path) handle = open(path, 'w') head = 'spectrum,theta' @@ -594,7 +595,7 @@ def IN13Read(instr,run,ana,refl,Plot,Save): #Ascii start routine opath = os.path.join(workdir,outWS+'.nxs') SaveNexusProcessed(InputWorkspace=outWS, Filename=opath) logger.information('Output file : ' + opath) - if (Plot != 'None'): + if Plot != 'None': plotForce(outWS,Plot) return outWS From 945c124dd8865ddf3b3be03ebc2e24347548455d Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 16:28:01 +0000 Subject: [PATCH 227/414] Refactored SofQWMoments Refs #10706 --- .../WorkflowAlgorithms/SofQWMoments.py | 90 +++++++++++-------- 1 file changed, 53 insertions(+), 37 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py index 6debe06b76df..b7063f1e99da 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py @@ -12,21 +12,31 @@ class SofQWMoments(DataProcessorAlgorithm): def category(self): return "Workflow\\MIDAS;PythonAlgorithms" + def summary (self): return "Calculates the nth moment of y(q,w)" + def PyInit(self): - 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='Scale', defaultValue=1.0, doc='Scale factor to multiply y(Q,w). Default=1.0') - 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(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='Scale', defaultValue=1.0, + doc='Scale factor to multiply y(Q,w). Default=1.0') + 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.") - 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 + from IndirectCommon import CheckHistZero, CheckElimits, getDefaultWorkingDirectory sample_workspace = self.getPropertyValue('Sample') output_workspace = self.getPropertyValue('OutputWorkspace') @@ -38,16 +48,17 @@ def PyExec(self): Plot = self.getProperty('Plot').value Save = self.getProperty('Save').value - StartTime('SofQWMoments') num_spectra,num_w = CheckHistZero(sample_workspace) - logger.information('Sample %s has %d Q values & %d w values' % (sample_workspace, num_spectra, num_w)) + logger.information('Sample %s has %d Q values & %d w values' % ( + sample_workspace, num_spectra, num_w)) - x = np.asarray(mtd[sample_workspace].readX(0)) - CheckElimits(erange,x) + x_data = np.asarray(mtd[sample_workspace].readX(0)) + CheckElimits(erange,x_data) samWS = '__temp_sqw_moments_cropped' - CropWorkspace(InputWorkspace=sample_workspace, OutputWorkspace=samWS, XMin=erange[0], XMax=erange[1]) + CropWorkspace(InputWorkspace=sample_workspace, OutputWorkspace=samWS, + XMin=erange[0], XMax=erange[1]) logger.information('Energy range is %f to %f' % (erange[0], erange[1])) @@ -57,30 +68,31 @@ def PyExec(self): #calculate delta x ConvertToPointData(InputWorkspace=samWS, OutputWorkspace=samWS) - x = np.asarray(mtd[samWS].readX(0)) - x_workspace = CreateWorkspace(OutputWorkspace="__temp_sqw_moments_x", DataX=x, DataY=x, UnitX="DeltaE") + x_data = np.asarray(mtd[samWS].readX(0)) + x_workspace = CreateWorkspace(OutputWorkspace="__temp_sqw_moments_x", + DataX=x_data, DataY=x_data, UnitX="DeltaE") #calculate moments - m0 = output_workspace + '_M0' - m1 = output_workspace + '_M1' - m2 = output_workspace + '_M2' - m3 = output_workspace + '_M3' - m4 = output_workspace + '_M4' - - Multiply(x_workspace, samWS, OutputWorkspace=m1) - Multiply(x_workspace, m1, OutputWorkspace=m2) - Multiply(x_workspace, m2, OutputWorkspace=m3) - Multiply(x_workspace, m3, OutputWorkspace=m4) - DeleteWorkspace(m3) + moments_0 = output_workspace + '_M0' + moments_1 = output_workspace + '_M1' + moments_2 = output_workspace + '_M2' + moments_3 = output_workspace + '_M3' + moments_4 = output_workspace + '_M4' + + Multiply(x_workspace, samWS, OutputWorkspace=moments_1) + Multiply(x_workspace, moments_1, OutputWorkspace=moments_2) + Multiply(x_workspace, moments_2, OutputWorkspace=moments_3) + Multiply(x_workspace, moments_3, OutputWorkspace=moments_4) + DeleteWorkspace(moments_3) ConvertToHistogram(InputWorkspace=samWS, OutputWorkspace=samWS) - Integration(samWS, OutputWorkspace=m0) + Integration(samWS, OutputWorkspace=moments_0) - moments = [m1, m2, m4] + moments = [moments_1, moments_2, moments_4] for moment_ws in moments: ConvertToHistogram(InputWorkspace=moment_ws, OutputWorkspace=moment_ws) Integration(moment_ws, OutputWorkspace=moment_ws) - Divide(moment_ws, m0, OutputWorkspace=moment_ws) + Divide(moment_ws, moments_0, OutputWorkspace=moment_ws) DeleteWorkspace(samWS) DeleteWorkspace(x_workspace) @@ -91,12 +103,16 @@ def PyExec(self): ws_name = output_workspace+ext Transpose(InputWorkspace=ws_name, OutputWorkspace=ws_name) ConvertToHistogram(InputWorkspace=ws_name, OutputWorkspace=ws_name) - ConvertUnits(InputWorkspace=ws_name, OutputWorkspace=ws_name, Target='MomentumTransfer', EMode='Indirect') + ConvertUnits(InputWorkspace=ws_name, OutputWorkspace=ws_name, + Target='MomentumTransfer', EMode='Indirect') CopyLogs(InputWorkspace=sample_workspace, OutputWorkspace=ws_name) - AddSampleLog(Workspace=ws_name, LogName="energy_min", LogType="Number", LogText=str(emin)) - AddSampleLog(Workspace=ws_name, LogName="energy_max", LogType="Number", LogText=str(emax)) - AddSampleLog(Workspace=ws_name, LogName="scale_factor", LogType="Number", LogText=str(factor)) + AddSampleLog(Workspace=ws_name, LogName="energy_min", + LogType="Number", LogText=str(emin)) + AddSampleLog(Workspace=ws_name, LogName="energy_max", + LogType="Number", LogText=str(emax)) + AddSampleLog(Workspace=ws_name, LogName="scale_factor", + LogType="Number", LogText=str(factor)) # Group output workspace group_workspaces = ','.join([output_workspace+ext for ext in extensions]) @@ -113,14 +129,14 @@ def PyExec(self): self.setProperty("OutputWorkspace", output_workspace) - EndTime('SofQWMoments') def _plot_moments(self, inputWS): from IndirectImport import import_mantidplot - mp = import_mantidplot() + mtd_plot = import_mantidplot() + + mtd_plot.plotSpectrum(inputWS+'_M0', 0) + mtd_plot.plotSpectrum([inputWS+'_M2', inputWS+'_M4'], 0) - mp.plotSpectrum(inputWS+'_M0', 0) - mp.plotSpectrum([inputWS+'_M2', inputWS+'_M4'], 0) # Register algorithm with Mantid AlgorithmFactory.subscribe(SofQWMoments) From bddddc23fe70b8338e17bcf20d376e6ddd626fec Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 16:52:25 +0000 Subject: [PATCH 228/414] Refactor more indirect related algorithms Refs #10706 --- .../plugins/algorithms/Symmetrise.py | 28 ++-- .../WorkflowAlgorithms/DensityOfStates.py | 17 +- .../ElasticWindowMultiple.py | 42 +++-- .../algorithms/WorkflowAlgorithms/Fury.py | 44 ++++-- .../IndirectILLReduction.py | 104 +++++++----- .../algorithms/WorkflowAlgorithms/JumpFit.py | 6 +- .../algorithms/WorkflowAlgorithms/ResNorm.py | 149 ++++++++++-------- .../WorkflowAlgorithms/SofQWMoments.py | 3 +- 8 files changed, 244 insertions(+), 149 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py index 4f498695472c..1244da9203ad 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py @@ -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 @@ -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): @@ -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 @@ -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 @@ -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 @@ -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') @@ -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) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py index ed313b04e543..291d9fd08749 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py @@ -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 @@ -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: @@ -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) @@ -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) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py index 9349f30d0d17..ae1dbd3b9bd7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py @@ -40,7 +40,8 @@ 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') @@ -48,10 +49,12 @@ def PyInit(self): 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') @@ -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' @@ -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) @@ -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: @@ -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) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py index e478aa2674b4..70e6e93fd478 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py @@ -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 @@ -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), @@ -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): @@ -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 @@ -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)) @@ -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): @@ -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') @@ -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') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py index acc78baa98ce..08e6684d5409 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py @@ -1,6 +1,7 @@ from mantid.simpleapi import * from mantid.kernel import StringListValidator, Direction -from mantid.api import DataProcessorAlgorithm, PropertyMode, AlgorithmFactory, FileProperty, FileAction, MatrixWorkspaceProperty +from mantid.api import DataProcessorAlgorithm, PropertyMode, AlgorithmFactory, \ + FileProperty, FileAction, MatrixWorkspaceProperty from mantid import config, logger, mtd import numpy as np @@ -12,39 +13,51 @@ class IndirectILLReduction(DataProcessorAlgorithm): def category(self): return "Workflow\\MIDAS;Inelastic;PythonAlgorithms" + def PyInit(self): #input options self.declareProperty(FileProperty('Run', '', action=FileAction.Load, extensions=["nxs"]), doc='File path of run.') - self.declareProperty(name='Analyser', defaultValue='silicon', validator=StringListValidator(['silicon']), + self.declareProperty(name='Analyser', defaultValue='silicon', + validator=StringListValidator(['silicon']), doc='Analyser crystal') - self.declareProperty(name='Reflection', defaultValue='111', validator=StringListValidator(['111']), + self.declareProperty(name='Reflection', defaultValue='111', + validator=StringListValidator(['111']), doc='Analyser reflection') - self.declareProperty(FileProperty('MapFile', '', action=FileAction.OptionalLoad, extensions=["xml"]), + self.declareProperty(FileProperty('MapFile', '', + action=FileAction.OptionalLoad, extensions=["xml"]), doc='Filename of the map file to use. If left blank the default will be used.') - self.declareProperty(name='MirrorMode', defaultValue=False, doc='Whether to use mirror mode') + self.declareProperty(name='MirrorMode', defaultValue=False, + doc='Whether to use mirror mode') #Output workspace properties - self.declareProperty(MatrixWorkspaceProperty("RawWorkspace", "", direction=Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("RawWorkspace", "", + direction=Direction.Output), doc="Name for the output raw workspace created.") - self.declareProperty(MatrixWorkspaceProperty("ReducedWorkspace", "", direction=Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("ReducedWorkspace", "", + direction=Direction.Output), doc="Name for the output reduced workspace created. If mirror mode is used this will be the sum of both" "the left and right hand workspaces.") - self.declareProperty(MatrixWorkspaceProperty("LeftWorkspace", "", optional=PropertyMode.Optional, direction=Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("LeftWorkspace", "", + optional=PropertyMode.Optional, direction=Direction.Output), doc="Name for the left workspace if mirror mode is used.") - self.declareProperty(MatrixWorkspaceProperty("RightWorkspace", "", optional=PropertyMode.Optional, direction=Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("RightWorkspace", "", + optional=PropertyMode.Optional, direction=Direction.Output), doc="Name for the right workspace if mirror mode is used.") # output options - self.declareProperty(name='Save', defaultValue=False, doc='Switch Save result to nxs file Off/On') - self.declareProperty(name='Plot', defaultValue=False, doc='Whether to plot the output workspace.') + self.declareProperty(name='Save', defaultValue=False, + doc='Switch Save result to nxs file Off/On') + self.declareProperty(name='Plot', defaultValue=False, + doc='Whether to plot the output workspace.') + def PyExec(self): self.log().information('IndirectILLreduction') @@ -77,7 +90,8 @@ def PyExec(self): self._reflection = self.getPropertyValue('Reflection') self._run_name = self._instrument_name + '_' + str(self._run_number) - AddSampleLog(Workspace=self._raw_workspace, LogName="mirror_sense", LogType="String", LogText=str(self._use_mirror_mode)) + AddSampleLog(Workspace=self._raw_workspace, LogName="mirror_sense", + LogType="String", LogText=str(self._use_mirror_mode)) logger.information('Nxs file : %s' % run_path) @@ -92,15 +106,15 @@ def PyExec(self): if self._plot: from IndirectImport import import_mantidplot - mp = import_mantidplot() - graph = mp.newGraph() + mtd_plot = import_mantidplot() + graph = mtd_plot.newGraph() for ws in output_workspaces: - mp.plotSpectrum(ws, 0, window=graph) + mtd_plot.plotSpectrum(ws, 0, window=graph) layer = graph.activeLayer() - layer.setAxisTitle(mp.Layer.Bottom, 'Energy Transfer (meV)') - layer.setAxisTitle(mp.Layer.Left, '') + layer.setAxisTitle(mtd_plot.Layer.Bottom, 'Energy Transfer (meV)') + layer.setAxisTitle(mtd_plot.Layer.Left, '') layer.setTitle('') self.setPropertyValue('RawWorkspace', self._raw_workspace) @@ -110,14 +124,11 @@ def PyExec(self): self.setPropertyValue('LeftWorkspace', self._red_left_workspace) self.setPropertyValue('RightWorkspace', self._red_right_workspace) + def _reduction(self): """ Run energy conversion for IN16B """ - from IndirectCommon import StartTime, EndTime - - StartTime('ILLindirect') - logger.information('Input workspace : %s' % self._raw_workspace) idf_directory = config['instrumentDefinition.directory'] @@ -125,7 +136,8 @@ def _reduction(self): ipf_path = os.path.join(idf_directory, ipf_name) LoadParameterFile(Workspace=self._raw_workspace, Filename=ipf_path) - AddSampleLog(Workspace=self._raw_workspace, LogName="facility", LogType="String", LogText="ILL") + AddSampleLog(Workspace=self._raw_workspace, LogName="facility", + LogType="String", LogText="ILL") if self._map_file == '': # path name for default map file @@ -139,11 +151,12 @@ def _reduction(self): logger.information('Map file : %s' % self._map_file) grouped_ws = self._run_name + '_group' - GroupDetectors(InputWorkspace=self._raw_workspace, OutputWorkspace=grouped_ws, MapFile=self._map_file, - Behaviour='Average') + GroupDetectors(InputWorkspace=self._raw_workspace, OutputWorkspace=grouped_ws, + MapFile=self._map_file, Behaviour='Average') monitor_ws = self._run_name + '_mon' - ExtractSingleSpectrum(InputWorkspace=self._raw_workspace, OutputWorkspace=monitor_ws, WorkspaceIndex=0) + ExtractSingleSpectrum(InputWorkspace=self._raw_workspace, + OutputWorkspace=monitor_ws, WorkspaceIndex=0) if self._use_mirror_mode: output_workspaces = self._run_mirror_mode(monitor_ws, grouped_ws) @@ -153,9 +166,9 @@ def _reduction(self): self._calculate_energy(monitor_ws, grouped_ws, self._red_workspace) output_workspaces = [self._red_workspace] - EndTime('ILLindirect') return output_workspaces + def _run_mirror_mode(self, monitor_ws, grouped_ws): """ Runs energy reduction with mirror mode. @@ -199,18 +212,24 @@ def _run_mirror_mode(self, monitor_ws, grouped_ws): nrmax = np.argmax(np.array(yr)) xrmax = xr[nrmax] xshift = xlmax - xrmax - ScaleX(InputWorkspace=self._red_right_workspace, OutputWorkspace=self._red_right_workspace, Factor=xshift, Operation='Add') - RebinToWorkspace(WorkspaceToRebin=self._red_right_workspace, WorkspaceToMatch=self._red_left_workspace, OutputWorkspace=self._red_right_workspace) + ScaleX(InputWorkspace=self._red_right_workspace, OutputWorkspace=self._red_right_workspace, + Factor=xshift, Operation='Add') + RebinToWorkspace(WorkspaceToRebin=self._red_right_workspace, + WorkspaceToMatch=self._red_left_workspace, + OutputWorkspace=self._red_right_workspace) #sum both workspaces together - Plus(LHSWorkspace=self._red_left_workspace, RHSWorkspace=self._red_right_workspace, OutputWorkspace=self._red_workspace) - Scale(InputWorkspace=self._red_workspace, OutputWorkspace=self._red_workspace, Factor=0.5, Operation='Multiply') + Plus(LHSWorkspace=self._red_left_workspace, RHSWorkspace=self._red_right_workspace, + OutputWorkspace=self._red_workspace) + Scale(InputWorkspace=self._red_workspace, OutputWorkspace=self._red_workspace, + Factor=0.5, Operation='Multiply') DeleteWorkspace(monitor_ws) DeleteWorkspace(grouped_ws) return [self._red_left_workspace, self._red_right_workspace, self._red_workspace] + def _calculate_energy(self, monitor_ws, grouped_ws, red_ws): """ Convert the input run to energy transfer @@ -220,18 +239,23 @@ def _calculate_energy(self, monitor_ws, grouped_ws, red_ws): @param red_ws :: name to call the reduced workspace """ x_range = self._monitor_range(monitor_ws) - Scale(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, Factor=0.001, Operation='Multiply') + Scale(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, Factor=0.001, + Operation='Multiply') - CropWorkspace(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, Xmin=x_range[0], XMax=x_range[1]) - ScaleX(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, Factor=-x_range[0], Operation='Add') + CropWorkspace(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, + Xmin=x_range[0], XMax=x_range[1]) + ScaleX(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, Factor=-x_range[0], + Operation='Add') - CropWorkspace(InputWorkspace=grouped_ws, OutputWorkspace=grouped_ws, Xmin=x_range[0], XMax=x_range[1]) - ScaleX(InputWorkspace=grouped_ws, OutputWorkspace=grouped_ws, Factor=-x_range[0], Operation='Add') + CropWorkspace(InputWorkspace=grouped_ws, OutputWorkspace=grouped_ws, Xmin=x_range[0], + XMax=x_range[1]) + ScaleX(InputWorkspace=grouped_ws, OutputWorkspace=grouped_ws, Factor=-x_range[0], + Operation='Add') Divide(LHSWorkspace=grouped_ws, RHSWorkspace=monitor_ws, OutputWorkspace=grouped_ws) formula = self._energy_range(grouped_ws) - ConvertAxisByFormula(InputWorkspace=grouped_ws, OutputWorkspace=red_ws, Axis='X', Formula=formula, - AxisTitle='Energy transfer', AxisUnits='meV') + ConvertAxisByFormula(InputWorkspace=grouped_ws, OutputWorkspace=red_ws, Axis='X', + Formula=formula, AxisTitle='Energy transfer', AxisUnits='meV') xnew = mtd[red_ws].readX(0) # energy array logger.information('Energy range : %f to %f' % (xnew[0], xnew[-1])) @@ -239,6 +263,7 @@ def _calculate_energy(self, monitor_ws, grouped_ws, red_ws): DeleteWorkspace(grouped_ws) DeleteWorkspace(monitor_ws) + def _monitor_range(self, monitor_ws): """ Get sensible values for the min and max cropping range @@ -257,6 +282,7 @@ def _monitor_range(self, monitor_ws): return x[imin], x[imax] + def _energy_range(self, ws): """ Calculate the energy range for the workspace @@ -282,4 +308,6 @@ def _energy_range(self, ws): return formula -AlgorithmFactory.subscribe(IndirectILLReduction) # Register algorithm with Mantid + +# Register algorithm with Mantid +AlgorithmFactory.subscribe(IndirectILLReduction) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py index 0d5e64bbfc4e..4b1ccd2e651a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py @@ -37,7 +37,8 @@ def PyInit(self): def PyExec(self): - from mantid.simpleapi import ExtractSingleSpectrum, Scale, Fit, CopyLogs, AddSampleLog, DeleteWorkspace + from mantid.simpleapi import ExtractSingleSpectrum, Fit, CopyLogs, AddSampleLog, \ + DeleteWorkspace from mantid import logger, mtd from IndirectCommon import StartTime, EndTime @@ -47,7 +48,8 @@ def PyExec(self): # Select the width we wish to fit spectrum_ws = "__" + self._in_ws - ExtractSingleSpectrum(InputWorkspace=self._in_ws, OutputWorkspace=spectrum_ws, WorkspaceIndex=self._width) + ExtractSingleSpectrum(InputWorkspace=self._in_ws, OutputWorkspace=spectrum_ws, + WorkspaceIndex=self._width) logger.information('Cropping from Q= ' + str(self._q_min) + ' to ' + str(self._q_max)) in_run = mtd[self._in_ws].getRun() diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py index c7dd0825540e..cd390e450878 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py @@ -1,73 +1,94 @@ from mantid.api import PythonAlgorithm, AlgorithmFactory from mantid.kernel import StringListValidator, StringMandatoryValidator from mantid.simpleapi import * -from mantid import config, logger, mtd +from mantid import config, logger import os + class ResNorm(PythonAlgorithm): - def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" - - def summary(self): - return "This algorithm creates a group 'normalisation' file by taking a resolution file and fitting it to all the groups in the resolution (vanadium) data file which has the same grouping as the sample data of interest." - - def PyInit(self): - self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) 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='VanNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') - self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') - self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') - self.declareProperty(name='EnergyMin', defaultValue=-0.2, doc='Minimum energy for fit. Default=-0.2') - self.declareProperty(name='EnergyMax', defaultValue=0.2, doc='Maximum energy for fit. Default=0.2') - self.declareProperty(name='VanBinning', defaultValue=1, doc='Binning value (integer) for sample. Default=1') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Intensity','Stretch','Fit','All']), doc='Plot options') - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') - - def PyExec(self): - from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform - - if is_supported_f2py_platform(): + def category(self): + return "Workflow\\MIDAS;PythonAlgorithms" + + + def summary(self): + return "This algorithm creates a group 'normalisation' file by taking a resolution file and fitting it to all the groups in the resolution (vanadium) data file which has the same grouping as the sample data of interest." + + + def PyInit(self): + self.declareProperty(name='InputType', defaultValue='File', + validator=StringListValidator(['File','Workspace']), + doc='Origin of data input - File (.nxs) 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='VanNumber', defaultValue='', + validator=StringMandatoryValidator(), + doc='Sample run number') + self.declareProperty(name='ResInputType',defaultValue='File', + validator=StringListValidator(['File','Workspace']), + doc='Origin of res input - File (_res.nxs) or Workspace') + self.declareProperty(name='ResNumber', defaultValue='', + validator=StringMandatoryValidator(), + doc='Resolution run number') + self.declareProperty(name='EnergyMin', defaultValue=-0.2, + doc='Minimum energy for fit. Default=-0.2') + self.declareProperty(name='EnergyMax', defaultValue=0.2, + doc='Maximum energy for fit. Default=0.2') + self.declareProperty(name='VanBinning', defaultValue=1, + doc='Binning value (integer) for sample. Default=1') + self.declareProperty(name='Plot', defaultValue='None', + validator=StringListValidator(['None','Intensity','Stretch','Fit','All']), + doc='Plot options') + self.declareProperty(name='Save', defaultValue=False, + doc='Switch Save result to nxs file Off/On') + + + def PyExec(self): + from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform + + if is_supported_f2py_platform(): import IndirectBayes as Main - run_f2py_compatibility_test() - - self.log().information('ResNorm input') - inType = self.getPropertyValue('InputType') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - van = self.getPropertyValue('VanNumber') - rinType = self.getPropertyValue('ResInputType') - res = self.getPropertyValue('ResNumber') - emin = self.getPropertyValue('EnergyMin') - emax = self.getPropertyValue('EnergyMax') - nbin = self.getPropertyValue('VanBinning') - - vname = prefix+van+'_'+ana+ '_red' - rname = prefix+res+'_'+ana+ '_res' - erange = [float(emin), float(emax)] - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value - - workdir = config['defaultsave.directory'] - if inType == 'File': - vpath = os.path.join(workdir, vname+'.nxs') # path name for van nxs file - LoadNexusProcessed(Filename=vpath, OutputWorkspace=vname) - Vmessage = 'Vanadium from File : '+vpath - else: - Vmessage = 'Vanadium from Workspace : '+vname - if rinType == 'File': - rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file - LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) - Rmessage = 'Resolution from File : '+rpath - else: - Rmessage = 'Resolution from Workspace : '+rname - if verbOp: - logger.notice(Vmessage) - logger.notice(Rmessage) - Main.ResNormRun(vname,rname,erange,nbin,verbOp,plotOp,saveOp) - -AlgorithmFactory.subscribe(ResNorm) # Register algorithm with Mantid + run_f2py_compatibility_test() + + self.log().information('ResNorm input') + inType = self.getPropertyValue('InputType') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + van = self.getPropertyValue('VanNumber') + rinType = self.getPropertyValue('ResInputType') + res = self.getPropertyValue('ResNumber') + emin = self.getPropertyValue('EnergyMin') + emax = self.getPropertyValue('EnergyMax') + nbin = self.getPropertyValue('VanBinning') + + vname = prefix+van+'_'+ana+ '_red' + rname = prefix+res+'_'+ana+ '_res' + erange = [float(emin), float(emax)] + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value + + workdir = config['defaultsave.directory'] + if inType == 'File': + vpath = os.path.join(workdir, vname+'.nxs') # path name for van nxs file + LoadNexusProcessed(Filename=vpath, OutputWorkspace=vname) + Vmessage = 'Vanadium from File : '+vpath + else: + Vmessage = 'Vanadium from Workspace : '+vname + if rinType == 'File': + rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file + LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) + Rmessage = 'Resolution from File : '+rpath + else: + Rmessage = 'Resolution from Workspace : '+rname + logger.information(Vmessage) + logger.information(Rmessage) + Main.ResNormRun(vname,rname,erange,nbin,True,plotOp,saveOp) + + +# Register algorithm with Mantid +AlgorithmFactory.subscribe(ResNorm) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py index b7063f1e99da..18328047655e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py @@ -1,6 +1,7 @@ # Algorithm to start Bayes programs from mantid.simpleapi import * -from mantid.api import DataProcessorAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, WorkspaceGroupProperty +from mantid.api import DataProcessorAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, \ + WorkspaceGroupProperty from mantid.kernel import Direction from mantid import logger From ef306cb747d4434672a25e567786008a5c1f01fd Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 16 Feb 2015 16:57:47 +0000 Subject: [PATCH 229/414] Rafactor a couple more Python algorithms Refs #10706 --- .../plugins/algorithms/Mean.py | 33 ++++++++++++------- .../plugins/algorithms/SortXAxis.py | 33 +++++++++++-------- 2 files changed, 42 insertions(+), 24 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py index 54b5e72b53af..ac47c79c7960 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py @@ -2,41 +2,52 @@ from mantid.api import * from mantid.kernel import * + class Mean(PythonAlgorithm): def category(self): return "Arithmetic" + def name(self): return "Mean" + def summary(self): return "Calculates the arithemetic mean of the workspaces provided." + def PyInit(self): mustHaveWorkspaceNames = StringMandatoryValidator() - self.declareProperty("Workspaces", "", validator=mustHaveWorkspaceNames, direction=Direction.Input, doc="Input workspaces. Comma separated workspace names") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), "Output mean workspace") - def areWorkspacesCompatible(self, a, b): - sizeA = a.blocksize() * a.getNumberHistograms() - sizeB = b.blocksize() * b.getNumberHistograms() + self.declareProperty("Workspaces", "", validator=mustHaveWorkspaceNames, + direction=Direction.Input, + doc="Input workspaces. Comma separated workspace names") + + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", + Direction.Output), + doc="Output mean workspace") + + + def _are_workspaces_compatible(self, ws_a, ws_b): + sizeA = ws_a.blocksize() * ws_a.getNumberHistograms() + sizeB = ws_b.blocksize() * ws_b.getNumberHistograms() return sizeA == sizeB + def PyExec(self): workspaces = self.getProperty("Workspaces").value.split(',') - out_ws = CloneWorkspace(InputWorkspace=mtd[workspaces[0]], OutputWorkspace=self.getPropertyValue("OutputWorkspace")) + out_ws = CloneWorkspace(InputWorkspace=mtd[workspaces[0]], + OutputWorkspace=self.getPropertyValue("OutputWorkspace")) for index in range(1, len(workspaces)): name = workspaces[index].strip() - ws = mtd[name] - if not self.areWorkspacesCompatible(out_ws, ws): + workspace = mtd[name] + if not self._are_workspaces_compatible(out_ws, workspace): raise RuntimeError("Input Workspaces are not the same shape.") - out_ws += ws + out_ws += workspace out_ws /= len(workspaces) self.setProperty("OutputWorkspace", out_ws) -############################################################################################# - AlgorithmFactory.subscribe(Mean()) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py index 39c81a9f31a3..d3442b8bbed5 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py @@ -3,22 +3,30 @@ from mantid.api import * from mantid.kernel import * import numpy as np -import operator + class SortXAxis(PythonAlgorithm): def category(self): return "Transforms\\Axes" + def name(self): return "SortXAxis" + def summary(self): return "Clones the input MatrixWorkspace(s) and orders the x-axis in an ascending fashion." + def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", defaultValue="", direction=Direction.Input), doc="Input workspace") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", defaultValue="", direction=Direction.Output), doc="Sorted Output Workspace") + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", defaultValue="", + direction=Direction.Input), + doc="Input workspace") + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", defaultValue="", + direction=Direction.Output), + doc="Sorted Output Workspace") + def PyExec(self): input_ws = self.getProperty('InputWorkspace').value @@ -28,19 +36,19 @@ def PyExec(self): api.CloneWorkspace(InputWorkspace=input_ws, OutputWorkspace=output_ws) for i in range(0, num_specs): - x = input_ws.readX(i) - y = input_ws.readY(i) - e = input_ws.readE(i) + x_data = input_ws.readX(i) + y_data = input_ws.readY(i) + e_data = input_ws.readE(i) - indexes = x.argsort() + indexes = x_data.argsort() - x_ordered = x[indexes] + x_ordered = x_data[indexes] if input_ws.isHistogramData(): - max_index = np.argmax(indexes) - indexes = np.delete(indexes, max_index) + max_index = np.argmax(indexes) + indexes = np.delete(indexes, max_index) - y_ordered = y[indexes] - e_ordered = e[indexes] + y_ordered = y_data[indexes] + e_ordered = e_data[indexes] mtd[output_ws].setX(i, x_ordered) mtd[output_ws].setY(i, y_ordered) @@ -48,6 +56,5 @@ def PyExec(self): self.setProperty('OutputWorkspace', output_ws) -############################################################################################# AlgorithmFactory.subscribe(SortXAxis()) From 2c082b0c6ac90553271825154cad372864f66e60 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Mon, 16 Feb 2015 19:46:39 +0000 Subject: [PATCH 230/414] Fix check for pull_requests job name --- Code/Mantid/Build/Jenkins/buildscript.bat | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript.bat b/Code/Mantid/Build/Jenkins/buildscript.bat index 0e9e6e37cdbd..cbbd401d3c89 100755 --- a/Code/Mantid/Build/Jenkins/buildscript.bat +++ b/Code/Mantid/Build/Jenkins/buildscript.bat @@ -127,7 +127,7 @@ if "%BUILDPKG%" EQU "yes" ( :: Run the doc tests when doing a pull request build. Run from a package :: from a package to have at least one Linux checks it install okay ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -if "%JOB_NAME%"=="%JOB_NAME:pull_requests=%" ( +if not "%JOB_NAME%"=="%JOB_NAME:pull_requests=%" ( set SYSTEMTEST_DIR=%WORKSPACE%\Code\Mantid\Testing\SystemTest :: Install package python %SYSTEMTEST_DIR%\scripts\mantidinstaller.py install %WORKSPACE%\build From 707889044120cc2b128adf863579d6887ef0b2b0 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Mon, 16 Feb 2015 21:03:22 +0000 Subject: [PATCH 231/414] Fix path to installer python script on Windows Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript.bat | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript.bat b/Code/Mantid/Build/Jenkins/buildscript.bat index cbbd401d3c89..11d190a78a0b 100755 --- a/Code/Mantid/Build/Jenkins/buildscript.bat +++ b/Code/Mantid/Build/Jenkins/buildscript.bat @@ -128,15 +128,14 @@ if "%BUILDPKG%" EQU "yes" ( :: from a package to have at least one Linux checks it install okay ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: if not "%JOB_NAME%"=="%JOB_NAME:pull_requests=%" ( - set SYSTEMTEST_DIR=%WORKSPACE%\Code\Mantid\Testing\SystemTest :: Install package - python %SYSTEMTEST_DIR%\scripts\mantidinstaller.py install %WORKSPACE%\build + python %WORKSPACE%\Code\Mantid\Testing\SystemTest\scripts\mantidinstaller.py install %WORKSPACE%\build cd %WORKSPACE%\build\docs :: Run tests C:\MantidInstall\bin\MantidPlot.exe -xq runsphinx_doctest.py if ERRORLEVEl 1 exit /B %ERRORLEVEL% :: Remove cd %WORKSPACE%\build - python %SYSTEMTEST_DIR%\scripts\mantidinstaller.py uninstall %WORKSPACE%\build + python %WORKSPACE%\Code\Mantid\Testing\SystemTest\scripts\mantidinstaller.py uninstall %WORKSPACE%\build ) From dc21b4d134f726c91e615d25f93d9d4adfec6e9f Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Mon, 16 Feb 2015 21:31:14 +0000 Subject: [PATCH 232/414] Apply OSX > 10.8 fix to system test scripts Refs #10870 --- Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py | 4 +++- Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py b/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py index e365ed240559..88a6aeb13457 100644 --- a/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py +++ b/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py @@ -229,7 +229,9 @@ class DMGInstaller(MantidInstaller): def __init__(self, package_dir, do_install): MantidInstaller.__init__(self, package_dir, 'mantid-*.dmg', do_install) self.mantidPlotPath = '/Applications/MantidPlot.app/Contents/MacOS/MantidPlot' - os.environ['DYLD_LIBRARY_PATH'] = '/Applications/MantidPlot.app/Contents/MacOS' + # only necessary on 10.8 build + if int(platform.release().split('.')[0]) < 13: + os.environ['DYLD_LIBRARY_PATH'] = '/Applications/MantidPlot.app/Contents/MacOS' def do_install(self): """Mounts the dmg and copies the application into the right place. diff --git a/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py b/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py index 9952384010a6..3db730daaf48 100755 --- a/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py +++ b/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py @@ -78,7 +78,8 @@ # not the dynamic library path variable name if platform.system() == 'Windows': path_var = "PATH" -elif platform.system() == 'Darwin': +# only necessary on 10.8 build +elif platform.system() == 'Darwin' and int(platform.release().split('.')[0]) < 13 : path_var = "DYLD_LIBRARY_PATH" else: path_var = None From 59d199fd5cce1f8675e46bdc949d03b7a168ee29 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Mon, 16 Feb 2015 22:26:42 +0000 Subject: [PATCH 233/414] Fix path to mantidinstaller script Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript.bat | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript.bat b/Code/Mantid/Build/Jenkins/buildscript.bat index 11d190a78a0b..a2046490aa4c 100755 --- a/Code/Mantid/Build/Jenkins/buildscript.bat +++ b/Code/Mantid/Build/Jenkins/buildscript.bat @@ -129,13 +129,13 @@ if "%BUILDPKG%" EQU "yes" ( ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: if not "%JOB_NAME%"=="%JOB_NAME:pull_requests=%" ( :: Install package - python %WORKSPACE%\Code\Mantid\Testing\SystemTest\scripts\mantidinstaller.py install %WORKSPACE%\build + python %WORKSPACE%\Code\Mantid\Testing\SystemTests\scripts\mantidinstaller.py install %WORKSPACE%\build cd %WORKSPACE%\build\docs :: Run tests C:\MantidInstall\bin\MantidPlot.exe -xq runsphinx_doctest.py if ERRORLEVEl 1 exit /B %ERRORLEVEL% :: Remove cd %WORKSPACE%\build - python %WORKSPACE%\Code\Mantid\Testing\SystemTest\scripts\mantidinstaller.py uninstall %WORKSPACE%\build + python %WORKSPACE%\Code\Mantid\Testing\SystemTests\scripts\mantidinstaller.py uninstall %WORKSPACE%\build ) From 64e9872f79f8c1a77986ed888b76ce88397587e2 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Tue, 17 Feb 2015 08:50:08 +0000 Subject: [PATCH 234/414] Use delayed expansion to get error level behaviour correct. Also make sure the data paths are setup correct for the doc tests. Refs #10870 --- Code/Mantid/Build/Jenkins/buildscript.bat | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript.bat b/Code/Mantid/Build/Jenkins/buildscript.bat index a2046490aa4c..4071a94f1472 100755 --- a/Code/Mantid/Build/Jenkins/buildscript.bat +++ b/Code/Mantid/Build/Jenkins/buildscript.bat @@ -1,3 +1,4 @@ +setlocal enbaleextensions enabledelayedexpansion ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: WINDOWS SCRIPT TO DRIVE THE JENKINS BUILDS OF MANTID. :: @@ -131,11 +132,18 @@ if not "%JOB_NAME%"=="%JOB_NAME:pull_requests=%" ( :: Install package python %WORKSPACE%\Code\Mantid\Testing\SystemTests\scripts\mantidinstaller.py install %WORKSPACE%\build cd %WORKSPACE%\build\docs + ::Remove user properties, disable instrument updating & usage reports + del /Q C:\MantidInstall\bin\Mantid.user.properties + echo UpdateInstrumentDefinitions.OnStartup = 0 > C:\MantidInstall\bin\Mantid.user.properties + echo usagereports.enabled = 0 >> C:\MantidInstall\bin\Mantid.user.properties + set DATA_ROOT=%WORKSPACE%\build\ExternalData\Testing\Data + echo datasearch.directories = !DATA_ROOT!\UnitTest;!DATA_ROOT!\DocTest;%WORKSPACE%\Code\Mantid\instrument >> C:\MantidInstall\bin\Mantid.user.properties :: Run tests C:\MantidInstall\bin\MantidPlot.exe -xq runsphinx_doctest.py - if ERRORLEVEl 1 exit /B %ERRORLEVEL% + set RETCODE=!ERRORLEVEL! :: Remove cd %WORKSPACE%\build python %WORKSPACE%\Code\Mantid\Testing\SystemTests\scripts\mantidinstaller.py uninstall %WORKSPACE%\build + if !RETCODE! NEQ 0 exit /B 1 ) From 45204c84940708447022355919c5aa1687e65813 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Tue, 17 Feb 2015 09:04:26 +0000 Subject: [PATCH 235/414] Added preview plot of transmission curve Refs #11072 --- .../SampleTransmission.ui | 38 ++++++++++++++----- .../src/SampleTransmission.cpp | 4 +- .../SampleTransmissionCalculator.rst | 4 +- 3 files changed, 34 insertions(+), 12 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui index 14a70b09d4ff..f3b5ef6e696f 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui @@ -7,7 +7,7 @@ 0 0 550 - 450 + 570 @@ -232,23 +232,23 @@ - + 0 0 - + + false + + - 0 - 0 - 0 + 255 + 255 + 255 - - true - @@ -295,6 +295,26 @@ + + + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
+
+ + cbBinningType + spSingleLow + spSingleWidth + spSingleHigh + leMultiple + leChemicalFormula + spNumberDensity + spThickness + twResults + pbCalculate + diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp index 47d60bd70c6b..1c67f4c340f4 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp @@ -198,5 +198,7 @@ void SampleTransmission::algorithmComplete(bool error) m_uiForm.twResults->resizeColumnToContents(0); - //TODO: Preview plot + // Plot transmission curve on preview plot + m_uiForm.ppTransmission->addSpectrum("Transmission", "CalculatedSampleTransmission", 0); + m_uiForm.ppTransmission->resizeX(); } diff --git a/Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst b/Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst index aaa50194e0bf..f3282759eed3 100644 --- a/Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst +++ b/Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst @@ -1,5 +1,5 @@ -Data Comparison -=============== +Sample Transmission Calculator +============================== .. contents:: Table of Contents :local: From 654527d43e709dbdd90e8c8e548bb241c26cb01f Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Tue, 17 Feb 2015 09:32:27 +0000 Subject: [PATCH 236/414] added m_rawMem, m_refix, =NULL, coverity issues 1075587,8 re #11060 --- .../MantidMDEvents/AffineMatrixParameter.h | 8 ++- .../inc/MantidMDEvents/CoordTransformAffine.h | 6 +- .../MDEvents/src/AffineMatrixParameter.cpp | 67 ++++++++++--------- .../MDEvents/src/CoordTransformAffine.cpp | 50 +++++++------- 4 files changed, 68 insertions(+), 63 deletions(-) diff --git a/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/AffineMatrixParameter.h b/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/AffineMatrixParameter.h index 12000a3620cd..5b748bfefccf 100644 --- a/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/AffineMatrixParameter.h +++ b/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/AffineMatrixParameter.h @@ -42,11 +42,13 @@ class DLLExport AffineMatrixParameter private: void copyRawMatrix(); - /// Raw matrix used for speed. - coord_t **rawMatrix; + /// Raw matrix used for speed (array of pointers to columns). + coord_t **m_rawMatrix; + /// pointer to large memory block (matrix) + coord_t *m_rawMem; /// Affine matrix. - AffineMatrixType affineMatrix; + AffineMatrixType m_affineMatrix; }; } } diff --git a/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/CoordTransformAffine.h b/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/CoordTransformAffine.h index 1115ab99dd3a..8c138de70d8f 100644 --- a/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/CoordTransformAffine.h +++ b/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/CoordTransformAffine.h @@ -55,12 +55,12 @@ class DLLExport CoordTransformAffine : public Mantid::API::CoordTransform { * can be * combined by simply multiplying the matrices. */ - Mantid::Kernel::Matrix affineMatrix; + Mantid::Kernel::Matrix m_affineMatrix; /// Raw pointer to the same underlying matrix as affineMatrix. - coord_t **rawMatrix; + coord_t **m_rawMatrix; /// raw pointer to the memory block, referred by the raw Matrix; - coord_t *rawMemory; + coord_t *m_rawMemory; void copyRawMatrix(); }; diff --git a/Code/Mantid/Framework/MDEvents/src/AffineMatrixParameter.cpp b/Code/Mantid/Framework/MDEvents/src/AffineMatrixParameter.cpp index e0f17a542ce9..643badd778cd 100644 --- a/Code/Mantid/Framework/MDEvents/src/AffineMatrixParameter.cpp +++ b/Code/Mantid/Framework/MDEvents/src/AffineMatrixParameter.cpp @@ -10,15 +10,17 @@ namespace MDEvents { * @param inD the nubmer of input dimensions */ AffineMatrixParameter::AffineMatrixParameter(size_t outD, size_t inD) - : affineMatrix(outD + 1, inD + 1) { + : m_affineMatrix(outD + 1, inD + 1) { m_isValid = false; - affineMatrix.identityMatrix(); - size_t nx = affineMatrix.numRows(); - size_t ny = affineMatrix.numCols(); - coord_t *tmpX = new coord_t[nx * ny]; - rawMatrix = new coord_t *[nx]; + m_affineMatrix.identityMatrix(); + size_t nx = m_affineMatrix.numRows(); + size_t ny = m_affineMatrix.numCols(); + // big chunk of memory holding the whole matrix + m_rawMem = new coord_t[nx * ny]; + // array of pointers (one per column) + m_rawMatrix = new coord_t *[nx]; for (size_t i = 0; i < nx; i++) - rawMatrix[i] = tmpX + (i * ny); + m_rawMatrix[i] = m_rawMem + (i * ny); // Copy into the raw matrix (for speed) copyRawMatrix(); } @@ -26,19 +28,20 @@ AffineMatrixParameter::AffineMatrixParameter(size_t outD, size_t inD) //---------------------------------------------------------------------------------------------- /// Destructor AffineMatrixParameter::~AffineMatrixParameter() { - if (rawMatrix) { - delete[] * rawMatrix; - delete[] rawMatrix; + if (m_rawMatrix) { + delete[] * m_rawMatrix; + delete[] m_rawMatrix; } - rawMatrix = NULL; + m_rawMatrix = NULL; + m_rawMem = NULL; } //---------------------------------------------------------------------------------------------- /// Copy elements from affinematrix into raw array. void AffineMatrixParameter::copyRawMatrix() { - for (size_t x = 0; x < affineMatrix.numRows(); ++x) - for (size_t y = 0; y < affineMatrix.numCols(); ++y) - rawMatrix[x][y] = affineMatrix[x][y]; + for (size_t x = 0; x < m_affineMatrix.numRows(); ++x) + for (size_t y = 0; y < m_affineMatrix.numCols(); ++y) + m_rawMatrix[x][y] = m_affineMatrix[x][y]; } //---------------------------------------------------------------------------------------------- @@ -47,7 +50,7 @@ void AffineMatrixParameter::copyRawMatrix() { * @return A copy of the underlying affine matrix. */ AffineMatrixType AffineMatrixParameter::getAffineMatrix() const { - return affineMatrix; + return m_affineMatrix; } //---------------------------------------------------------------------------------------------- @@ -55,7 +58,7 @@ AffineMatrixType AffineMatrixParameter::getAffineMatrix() const { * * @return the matrix as an array. */ -coord_t **AffineMatrixParameter::getRawMatrix() { return rawMatrix; } +coord_t **AffineMatrixParameter::getRawMatrix() { return m_rawMatrix; } //---------------------------------------------------------------------------------------------- /** Get the name of the parameter @@ -72,7 +75,7 @@ std::string AffineMatrixParameter::getName() const { * @return the object as serialized. Xml in a std::string. */ std::string AffineMatrixParameter::toXMLString() const { - std::vector elements = this->affineMatrix.getVector(); + std::vector elements = this->m_affineMatrix.getVector(); const size_t size = elements.size(); std::string parameterValue; @@ -81,7 +84,7 @@ std::string AffineMatrixParameter::toXMLString() const { sstream << elements[i - 1]; parameterValue.append(sstream.str()); sstream.clear(); - if (i % affineMatrix.numCols() == 0) { + if (i % m_affineMatrix.numCols() == 0) { if (i != size) { parameterValue.append(";"); } @@ -99,8 +102,8 @@ std::string AffineMatrixParameter::toXMLString() const { * @return Cloned parameter. */ AffineMatrixParameter *AffineMatrixParameter::clone() const { - return new AffineMatrixParameter(affineMatrix.numRows() - 1, - affineMatrix.numCols() - 1); + return new AffineMatrixParameter(m_affineMatrix.numRows() - 1, + m_affineMatrix.numCols() - 1); } //---------------------------------------------------------------------------------------------- @@ -117,14 +120,14 @@ bool AffineMatrixParameter::isValid() const { return m_isValid; } */ AffineMatrixParameter &AffineMatrixParameter:: operator=(const AffineMatrixParameter &other) { - if ((other.affineMatrix.numCols() != this->affineMatrix.numCols()) || - (other.affineMatrix.numRows() != this->affineMatrix.numRows())) { + if ((other.m_affineMatrix.numCols() != this->m_affineMatrix.numCols()) || + (other.m_affineMatrix.numRows() != this->m_affineMatrix.numRows())) { throw std::runtime_error("Cannot make assignemnts between " "AffineMatrixParameter when the matrixes are of " "different sizes."); } if (this != &other) { - this->affineMatrix = other.affineMatrix; + this->m_affineMatrix = other.m_affineMatrix; this->m_isValid = other.m_isValid; copyRawMatrix(); } @@ -136,14 +139,14 @@ operator=(const AffineMatrixParameter &other) { * @param other : another affine matrix to copy from. */ AffineMatrixParameter::AffineMatrixParameter(const AffineMatrixParameter &other) - : affineMatrix(other.affineMatrix) { + : m_affineMatrix(other.m_affineMatrix) { m_isValid = other.m_isValid; - size_t nx = affineMatrix.numRows(); - size_t ny = affineMatrix.numCols(); - coord_t *tmpX = new coord_t[nx * ny]; - rawMatrix = new coord_t *[nx]; + size_t nx = m_affineMatrix.numRows(); + size_t ny = m_affineMatrix.numCols(); + m_rawMem = new coord_t[nx * ny]; + m_rawMatrix = new coord_t *[nx]; for (size_t i = 0; i < nx; i++) - rawMatrix[i] = tmpX + (i * ny); + m_rawMatrix[i] = m_rawMem + (i * ny); copyRawMatrix(); } @@ -153,11 +156,11 @@ AffineMatrixParameter::AffineMatrixParameter(const AffineMatrixParameter &other) * @param newMatrix : new matrix to use. */ void AffineMatrixParameter::setMatrix(const AffineMatrixType newMatrix) { - if (newMatrix.numRows() != this->affineMatrix.numRows()) + if (newMatrix.numRows() != this->m_affineMatrix.numRows()) throw std::runtime_error("setMatrix(): Number of rows must match!"); - if (newMatrix.numCols() != this->affineMatrix.numCols()) + if (newMatrix.numCols() != this->m_affineMatrix.numCols()) throw std::runtime_error("setMatrix(): Number of columns must match!"); - affineMatrix = newMatrix; + m_affineMatrix = newMatrix; // Copy into the raw matrix (for speed) copyRawMatrix(); this->m_isValid = true; diff --git a/Code/Mantid/Framework/MDEvents/src/CoordTransformAffine.cpp b/Code/Mantid/Framework/MDEvents/src/CoordTransformAffine.cpp index 2860f0e58b43..4d15ad909fe7 100644 --- a/Code/Mantid/Framework/MDEvents/src/CoordTransformAffine.cpp +++ b/Code/Mantid/Framework/MDEvents/src/CoordTransformAffine.cpp @@ -25,19 +25,19 @@ namespace MDEvents { * @throw std::runtime_error if outD > inD */ CoordTransformAffine::CoordTransformAffine(const size_t inD, const size_t outD) - : CoordTransform(inD, outD), affineMatrix(outD + 1, inD + 1), - rawMatrix(NULL), rawMemory(NULL) { - affineMatrix.identityMatrix(); + : CoordTransform(inD, outD), m_affineMatrix(outD + 1, inD + 1), + m_rawMatrix(NULL), m_rawMemory(NULL) { + m_affineMatrix.identityMatrix(); // Allocate the raw matrix - size_t nx = affineMatrix.numRows(); - size_t ny = affineMatrix.numCols(); + size_t nx = m_affineMatrix.numRows(); + size_t ny = m_affineMatrix.numCols(); // vector of pointers - rawMatrix = new coord_t *[nx]; + m_rawMatrix = new coord_t *[nx]; // memory itself - rawMemory = new coord_t[nx * ny]; + m_rawMemory = new coord_t[nx * ny]; for (size_t i = 0; i < nx; i++) - rawMatrix[i] = rawMemory + (i * ny); + m_rawMatrix[i] = m_rawMemory + (i * ny); // Copy into the raw matrix (for speed) copyRawMatrix(); } @@ -46,9 +46,9 @@ CoordTransformAffine::CoordTransformAffine(const size_t inD, const size_t outD) * Call this after any change to affineMatrix */ void CoordTransformAffine::copyRawMatrix() { - for (size_t x = 0; x < affineMatrix.numRows(); ++x) - for (size_t y = 0; y < affineMatrix.numCols(); ++y) - rawMatrix[x][y] = affineMatrix[x][y]; + for (size_t x = 0; x < m_affineMatrix.numRows(); ++x) + for (size_t y = 0; y < m_affineMatrix.numCols(); ++y) + m_rawMatrix[x][y] = m_affineMatrix[x][y]; } //---------------------------------------------------------------------------------------------- @@ -64,12 +64,12 @@ CoordTransform *CoordTransformAffine::clone() const { /** Destructor */ CoordTransformAffine::~CoordTransformAffine() { - if (rawMatrix) { - delete[] rawMatrix; - delete[] rawMemory; + if (m_rawMatrix) { + delete[] * m_rawMatrix; + delete[] m_rawMatrix; } - rawMatrix = NULL; - rawMemory = NULL; + m_rawMatrix = NULL; + m_rawMemory = NULL; } //---------------------------------------------------------------------------------------------- @@ -84,7 +84,7 @@ void CoordTransformAffine::setMatrix( throw std::runtime_error("setMatrix(): Number of rows must match!"); if (newMatrix.numCols() != inD + 1) throw std::runtime_error("setMatrix(): Number of columns must match!"); - affineMatrix = newMatrix; + m_affineMatrix = newMatrix; // Copy into the raw matrix (for speed) copyRawMatrix(); } @@ -93,12 +93,12 @@ void CoordTransformAffine::setMatrix( /** Return the affine matrix in the transform. */ const Mantid::Kernel::Matrix &CoordTransformAffine::getMatrix() const { - return affineMatrix; + return m_affineMatrix; } /** @return the affine matrix */ Mantid::Kernel::Matrix CoordTransformAffine::makeAffineMatrix() const { - return affineMatrix; + return m_affineMatrix; } //---------------------------------------------------------------------------------------------- @@ -116,7 +116,7 @@ void CoordTransformAffine::addTranslation(const coord_t *translationVector) { translationMatrix[i][inD] = translationVector[i]; // Multiply the affine matrix by the translation affine matrix to combine them - affineMatrix *= translationMatrix; + m_affineMatrix *= translationMatrix; // Copy into the raw matrix (for speed) copyRawMatrix(); @@ -172,7 +172,7 @@ void CoordTransformAffine::buildOrthogonal( "workspace."); // Start with identity - affineMatrix.identityMatrix(); + m_affineMatrix.identityMatrix(); for (size_t i = 0; i < axes.size(); i++) { if (axes[i].length() == 0.0) @@ -187,7 +187,7 @@ void CoordTransformAffine::buildOrthogonal( basis.normalize(); // The row of the affine matrix = the unit vector for (size_t j = 0; j < basis.size(); j++) - affineMatrix[i][j] = static_cast(basis[j] * scaling[i]); + m_affineMatrix[i][j] = static_cast(basis[j] * scaling[i]); // Now account for the translation coord_t transl = 0; @@ -195,7 +195,7 @@ void CoordTransformAffine::buildOrthogonal( transl += static_cast( origin[j] * basis[j]); // dot product of origin * basis aka ( X0 . U ) // The last column of the matrix = the translation movement - affineMatrix[i][inD] = -transl * static_cast(scaling[i]); + m_affineMatrix[i][inD] = -transl * static_cast(scaling[i]); } // Copy into the raw matrix (for speed) @@ -213,7 +213,7 @@ void CoordTransformAffine::apply(const coord_t *inputVector, // For each output dimension for (size_t out = 0; out < outD; ++out) { // Cache the row pointer to make the matrix access a bit faster - coord_t *rawMatrixRow = rawMatrix[out]; + coord_t *rawMatrixRow = m_rawMatrix[out]; coord_t outVal = 0.0; size_t in; for (in = 0; in < inD; ++in) @@ -259,7 +259,7 @@ std::string CoordTransformAffine::toXMLString() const { // Convert the members to parameters AffineMatrixParameter affineMatrixParameter(inD, outD); - affineMatrixParameter.setMatrix(affineMatrix); + affineMatrixParameter.setMatrix(m_affineMatrix); Mantid::API::InDimParameter inD_param(inD); Mantid::API::OutDimParameter outD_param(outD); From 44286ac625eacfbfc897628875a4fccf0646db64 Mon Sep 17 00:00:00 2001 From: Nick Draper Date: Tue, 17 Feb 2015 09:32:48 +0000 Subject: [PATCH 237/414] re #11091 fix doxygen error --- Code/Mantid/Framework/Kernel/src/InternetHelper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp index e10ba8966dac..7e07db7f453d 100644 --- a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp +++ b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp @@ -479,7 +479,7 @@ void InternetHelper::setBody(const std::ostringstream& body) { /** Sets the body & content length for future requests, this will also * set the method to POST is the body is not empty * and GET if it is. -* @param body A HTMLform +* @param form A HTMLform **/ void InternetHelper::setBody(Poco::Net::HTMLForm& form) { From e59c11071f74a4d522006bda8cb8ea3af40d0c19 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Tue, 17 Feb 2015 09:37:48 +0000 Subject: [PATCH 238/414] Properly document sample transmission interface Refs #11072 --- .../SampleTransmission.h | 2 + .../SampleTransmission.ui | 31 +++++++++++++ .../src/SampleTransmission.cpp | 11 +++++ .../CalculateSampleTransmission-v1.rst | 2 + .../SampleTransmissionCalculator.rst | 45 ++++++++++++++++++- 5 files changed, 90 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h index 66bb3b810dee..c40016894a5b 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h @@ -30,6 +30,8 @@ namespace CustomInterfaces SampleTransmission(QWidget *parent = 0); private slots: + /// Opens the Qt help page for the interface + void showHelp(); /// Runs the calculation void calculate(); /// Handle completion of the calculation algorithm diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui index f3b5ef6e696f..ac5fac1c162a 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui @@ -270,6 +270,34 @@
+ + + + + 0 + 0 + + + + + 25 + 25 + + + + + 25 + 25 + + + + <html><head/><body><p>Opens the help page for the interface.</p></body></html> + + + ? + + + @@ -285,6 +313,9 @@ + + <html><head/><body><p>Runs the sample transmission calculation.</p></body></html> + Calculate diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp index 1c67f4c340f4..d381af8bdffc 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp @@ -5,6 +5,7 @@ #include "MantidAPI/AlgorithmManager.h" #include "MantidKernel/Statistics.h" +#include "MantidQtAPI/HelpWindow.h" #include "MantidQtCustomInterfaces/UserInputValidator.h" @@ -45,11 +46,21 @@ void SampleTransmission::initLayout() { m_uiForm.setupUi(this); connect(m_uiForm.pbCalculate, SIGNAL(clicked()), this, SLOT(calculate())); + connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(showHelp())); validate(true); } +/** + * Opens the Qt help page for the interface. + */ +void SampleTransmission::showHelp() +{ + MantidQt::API::HelpWindow::showCustomInterface(NULL, QString("SampleTransmissionCalculator")); +} + + /** * Validate user input. * Outputs any warnings to the results log at warning level. diff --git a/Code/Mantid/docs/source/algorithms/CalculateSampleTransmission-v1.rst b/Code/Mantid/docs/source/algorithms/CalculateSampleTransmission-v1.rst index 1c23cbd58680..770b301f127a 100644 --- a/Code/Mantid/docs/source/algorithms/CalculateSampleTransmission-v1.rst +++ b/Code/Mantid/docs/source/algorithms/CalculateSampleTransmission-v1.rst @@ -17,6 +17,8 @@ The sample chemical formula is input for the :ref:`SetSampleMaterial number density & thickness is input to then calculate the percentage scattering & transmission. +A flat plate sample which is perpendicular to the beam is assumed. + Usage ----- diff --git a/Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst b/Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst index f3282759eed3..8034599e9609 100644 --- a/Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst +++ b/Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst @@ -9,9 +9,52 @@ Overview .. interface:: Sample Transmission Calculator :align: right + :width: 350 -The sample transmission calculator allows the calculation fo the sample +The sample transmission calculator allows the calculation of the sample transmission and scattering over a given wavelength range for a particular sample material and geometry. +This UI is a front end for the :ref:`CalculateSampleTransmission +` algorithm. + +The algorithm assumes a flat plate sample which is perpendicular to the beam. + +Input Wavelength +~~~~~~~~~~~~~~~~ + +.. interface:: Sample Transmission Calculator + :widget: gbRangeBinning + :align: right + :width: 350 + +The wavelength range to calculate transmission over can be given either by +providing a single binning range in the format of a start, width and end value or +by providing a bin parameter string as used in the :ref:`Rebin ` +algorithm. + +Sample Details +~~~~~~~~~~~~~~ + +.. interface:: Sample Transmission Calculator + :widget: gbSampleDetails + :align: right + :width: 350 + +The sample details required are the chemical formula which is to be given in the +format expected by the :ref:`SetSampleMaterial ` +algorithm, number density in :math:`\mathrm{\AA{}}^3` and thickness in :math:`cm`. + +Output +~~~~~~ + +.. interface:: Sample Transmission Calculator + :widget: gbOutput + :align: right + :width: 350 + +The output is given in a plot of the transmission percentage over wavelength and +a table of statistics for the transmission (maximum, minimum, mean, median and +standard deviation) as well as the scattering percentage for all wavelengths. + .. categories:: Interfaces General From 1f6bb6c8a1525d742f90cfc9351ca37bdc5a21e6 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Tue, 17 Feb 2015 09:47:57 +0000 Subject: [PATCH 239/414] Tidy up UI, added message boxes for failures Refs #11072 --- .../MantidQtCustomInterfaces/SampleTransmission.ui | 2 +- .../CustomInterfaces/src/SampleTransmission.cpp | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui index ac5fac1c162a..cb9b0b849dbb 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui @@ -30,7 +30,7 @@ - Input Wavelength Range + Input Wavelength Range (Ã…) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp index d381af8bdffc..c44be8a5c1cd 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp @@ -106,7 +106,7 @@ bool SampleTransmission::validate(bool silent) // Give error message if(!silent && !uiv.isAllInputValid()) - g_log.error(uiv.generateErrorMessage().toStdString()); + showInformationBox(uiv.generateErrorMessage()); return uiv.isAllInputValid(); } @@ -154,6 +154,10 @@ void SampleTransmission::calculate() transCalcAlg->setProperty("OutputWorkspace", "CalculatedSampleTransmission"); + // Clear the previous results + m_uiForm.twResults->clear(); + m_uiForm.ppTransmission->clear(); + // Run algorithm m_algRunner->startAlgorithm(transCalcAlg); } @@ -170,14 +174,15 @@ void SampleTransmission::algorithmComplete(bool error) // Ignore errors if(error) + { + showInformationBox("Transmission calculation failed.\nSee Results Log for details."); return; + } MatrixWorkspace_sptr ws = AnalysisDataService::Instance().retrieveWS("CalculatedSampleTransmission"); // Fill the output table - m_uiForm.twResults->clear(); - double scattering = ws->dataY(1)[0]; QTreeWidgetItem *scatteringItem = new QTreeWidgetItem(); scatteringItem->setText(0, "Scattering"); From a6a5947bd8a4c696036e96a3bdba7a4cca4e1cea Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Tue, 17 Feb 2015 09:51:58 +0000 Subject: [PATCH 240/414] Put back top level README --- README.md | 32 +++++++++++--------------------- 1 file changed, 11 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 8ef2ab770d04..71a05dea8d76 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,15 @@ -SysMon +Mantid ====== -Python qt system monitor which utilizes the Python psutil and platform modules to provide system information for display. +The Mantid project provides a framework that supports high-performance computing and visualisation of scientific data. Mantid has been created to manipulate and analyse Neutron and Muon scattering data, but could be applied to many other techniques. The framework is open source and supported on multiple target platforms (Windows, Linux, Mac OS X). -This application has been adapted to work with psutil version 1 and version 2 modules as there are some command syntax changes between these two versions. - -The SysMon user interface has been divided into a main window which imports the tabs to make a standalone application, or the tabs can be imported into other applications as a QWidget. Thus there are separate .ui files corresponding to each. - -The code which imports the tabs into the main program resides in SysMon.pyw. This is where to look to see how to include the tabs into your own application. All files except SysMon.pyw and ui_sysmonMainWindow.* will be required when tabs are incorporated in other applications. - -The following command line arguments have been added: - --help to print out the help message. - --nompl to run the application minus matplotlib in support of the current MantidPlot (removes those tabs requiring matplotlib). - --custom to enable the custom menubar item in the standalone application (currently supports checking Matlab license status on SNS analysis computers). - -To run as a standalone application via the corresponding command lines: - *Change to the folder containing the Sysmon software, then: - *DOS: python SysMon.pyw - *Linux: ./SysMon.pyw - -The standalone application been tested on Windows and RHEL Linux, but not on Mac yet. - -Note that configuration and global constants and variables now reside in config.py. +Useful links +------------ + * Homepage: http://www.mantidproject.org + * Download: http://download.mantidproject.org + * Asking for help: http://download.mantidproject.org/webmailer/index.php + * Issue tracking: http://trac.mantidproject.org/mantid/ + * Build server: http://builds.mantidproject.org + * Developer site: http://developer.mantidproject.org +[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/mantidproject/mantid/trend.png)](https://bitdeli.com/free "Bitdeli Badge") From 66e14526c1fdbb80ec0a9ef55ef514bf6a1a7e59 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Tue, 17 Feb 2015 10:31:12 +0000 Subject: [PATCH 241/414] Fix some broken unit tests Refs #10706 --- Code/Mantid/scripts/Inelastic/IndirectCommon.py | 6 ++++-- Code/Mantid/scripts/test/IndirectCommonTests.py | 13 ------------- 2 files changed, 4 insertions(+), 15 deletions(-) diff --git a/Code/Mantid/scripts/Inelastic/IndirectCommon.py b/Code/Mantid/scripts/Inelastic/IndirectCommon.py index 794eb6ce274b..062031bc12c1 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectCommon.py +++ b/Code/Mantid/scripts/Inelastic/IndirectCommon.py @@ -314,7 +314,7 @@ def CheckHistSame(in1WS, name1, in2WS, name2): def CheckXrange(x_range, type): - if not (len(x_range) == 2) or (len(x_range) == 4): + if not ((len(x_range) == 2) or (len(x_range) == 4)): raise ValueError(type + ' - Range must contain either 2 or 4 numbers') for lower, upper in zip(x_range[::2], x_range[1::2]): @@ -557,7 +557,9 @@ def addSampleLogs(ws, sample_logs): """ for key, value in sample_logs.iteritems(): - if isinstance(value, (int, long, float)): + if isinstance(value, bool): + log_type = 'String' + elif isinstance(value, (int, long, float)): log_type = 'Number' else: log_type = 'String' diff --git a/Code/Mantid/scripts/test/IndirectCommonTests.py b/Code/Mantid/scripts/test/IndirectCommonTests.py index db4249d96b49..92bbea3b13be 100644 --- a/Code/Mantid/scripts/test/IndirectCommonTests.py +++ b/Code/Mantid/scripts/test/IndirectCommonTests.py @@ -20,19 +20,6 @@ def setUp(self): def tearDown(self): config = self._config_defaults - def test_loadInst(self): - indirect_common.loadInst('IRIS') - - ws_name = '__empty_IRIS' - ws = mtd[ws_name] - instrument = ws.getInstrument() - self.assertEqual(instrument.getName(), 'IRIS') - - def test_loadNexus(self): - ws_name = indirect_common.loadNexus('IRS26173_ipg.nxs') - self.assertEqual(ws_name, 'IRS26173_ipg') - self.assertTrue(mtd.doesExist(ws_name)) - def test_getInstrRun_from_name(self): ws = self.make_dummy_QENS_workspace() (instrument, run_number) = indirect_common.getInstrRun(ws) From b030a92c00c874ffb851a4cba94f02f4c75963fe Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Tue, 17 Feb 2015 11:00:04 +0000 Subject: [PATCH 242/414] Refactor more Python algorithms Refs #10706 --- .../algorithms/CalculateSampleTransmission.py | 28 +++--- .../algorithms/CreateEmptyTableWorkspace.py | 6 +- .../plugins/algorithms/LoadVesuvio.py | 90 +++++++++++-------- .../plugins/algorithms/SortDetectors.py | 31 +++---- .../plugins/algorithms/VesuvioResolution.py | 5 +- .../WorkflowAlgorithms/IndirectResolution.py | 39 +++++--- 6 files changed, 117 insertions(+), 82 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py index c88d3bf4f803..4f759e7a7b0e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py @@ -12,14 +12,17 @@ def category(self): def summary(self): - return 'Calculates the scattering & transmission for a given sample material and size over a given wavelength range.' + return "Calculates the scattering & transmission for a given sample \ + material and size over a given wavelength range." def PyInit(self): - self.declareProperty(name='WavelengthRange', defaultValue='', validator=StringMandatoryValidator(), + self.declareProperty(name='WavelengthRange', defaultValue='', + validator=StringMandatoryValidator(), doc='Wavelength range to calculate transmission for.') - self.declareProperty(name='ChemicalFormula', defaultValue='', validator=StringMandatoryValidator(), + self.declareProperty(name='ChemicalFormula', defaultValue='', + validator=StringMandatoryValidator(), doc='Sample chemical formula') self.declareProperty(name='NumberDensity', defaultValue=0.1, @@ -29,18 +32,19 @@ def PyInit(self): doc='Sample thickness (cm). Default=0.1') self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '', Direction.Output), - doc='Outputs the sample transmission over the wavelength range as a function of wavelength.') + doc='Outputs the sample transmission over the wavelength range ' + 'as a function of wavelength.') def validateInputs(self): issues = dict() density = self.getProperty('NumberDensity').value - if(density < 0.0): + if density < 0.0: issues['NumberDensity'] = 'NumberDensity must be positive' thickness = self.getProperty('Thickness').value - if(thickness < 0.0): + if thickness < 0.0: issues['Thickness'] = 'Thickness must be positive' return issues @@ -51,12 +55,13 @@ def PyExec(self): # Create the workspace and set the sample material CreateWorkspace(OutputWorkspace=self._output_ws, NSpec=2, DataX=[0, 0], DataY=[0, 0]) - Rebin(InputWorkspace=self._output_ws, OutputWorkspace=self._output_ws, Params=self._bin_params) + Rebin(InputWorkspace=self._output_ws, OutputWorkspace=self._output_ws, + Params=self._bin_params) SetSampleMaterial(InputWorkspace=self._output_ws, ChemicalFormula=self._chamical_formula) ConvertToPointData(InputWorkspace=self._output_ws, OutputWorkspace=self._output_ws) - ws = mtd[self._output_ws] - wavelengths = ws.readX(0) + workspace = mtd[self._output_ws] + wavelengths = workspace.readX(0) transmission_data = np.zeros(len(wavelengths)) scattering_data = np.zeros(len(wavelengths)) @@ -66,8 +71,8 @@ def PyExec(self): transmission_data[idx] = transmission scattering_data[idx] = scattering - ws.setY(0, transmission_data) - ws.setY(1, scattering_data) + workspace.setY(0, transmission_data) + workspace.setY(1, scattering_data) self.setProperty('OutputWorkspace', self._output_ws) @@ -103,6 +108,5 @@ def _calculate_at_wavelength(self, wavelength): return transmission, scattering - # Register algorithm with Mantid AlgorithmFactory.subscribe(CalculateSampleTransmission) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py index 162f572d05da..7de26b454077 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py @@ -5,11 +5,13 @@ class CreateEmptyTableWorkspace(PythonAlgorithm): def summary(self): - return "Creates an empty TableWorkspace which can be populated with various types of information." + return "Creates an empty TableWorkspace which can be populated with various "\ + "types of information." def PyInit(self): # Declare properties - self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), "The name of the table workspace that will be created.") + self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), + "The name of the table workspace that will be created.") def PyExec(self): tableWS = WorkspaceFactory.createTable() diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py index 0d23197cc062..0e5d0de4fbe9 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py @@ -34,7 +34,7 @@ class LoadVesuvio(PythonAlgorithm): def summary(self): - return "Loads raw data produced by the Vesuvio instrument at ISIS." + return "Loads raw data produced by the Vesuvio instrument at ISIS." def PyInit(self): self.declareProperty(RUN_PROP, "", StringMandatoryValidator(), @@ -53,12 +53,13 @@ def PyInit(self): self.declareProperty(FileProperty(INST_PAR_PROP,"",action=FileAction.OptionalLoad, extensions=["dat"]), doc="An optional IP file. If provided the values are used to correct " - "the default instrument values and attach the t0 values to each detector") + "the default instrument values and attach the t0 values to each " + "detector") self.declareProperty(SUM_PROP, False, - doc="If true then the final output is a single spectrum containing the sum " - "of all of the requested spectra. All detector angles/parameters are " - "averaged over the individual inputs") + doc="If true then the final output is a single spectrum containing " + "the sum of all of the requested spectra. All detector angles/" + "parameters are averaged over the individual inputs") self.declareProperty(WorkspaceProperty(WKSP_PROP, "", Direction.Output), doc="The name of the output workspace.") @@ -114,13 +115,13 @@ def _exec_single_foil_state_mode(self): """ runs = self._get_runs() if len(runs) > 1: - raise RuntimeError("Single soil state mode does not currently support summing multiple files") + raise RuntimeError("Single soil state mode does not currently support summing " + "multiple files") isis = config.getFacility("ISIS") inst_prefix = isis.instrument("VESUVIO").shortName() try: - run = int(runs[0]) run_str = inst_prefix + runs[0] except ValueError: run_str = runs[0] @@ -138,7 +139,7 @@ def _exec_single_foil_state_mode(self): foil_map = SpectraToFoilPeriodMap(self._nperiods) for ws_index, spectrum_no in enumerate(all_spectra): self._set_spectra_type(spectrum_no) - foil_out_periods, foil_thin_periods, foil_thick_periods = self._get_foil_periods() + foil_out_periods, foil_thin_periods, _ = self._get_foil_periods() if self._diff_opt == "FoilOut": raw_grp_indices = foil_map.get_indices(spectrum_no, foil_out_periods) @@ -252,13 +253,15 @@ def _setup_raw(self, spectra): # Cache delta_t values raw_t = first_ws.readX(0) delay = raw_t[2] - raw_t[1] - raw_t = raw_t - delay # The original EVS loader, raw.for/rawb.for, does this. Done here to match results + # The original EVS loader, raw.for/rawb.for, does this. Done here to match results + raw_t = raw_t - delay self.pt_times = raw_t[1:] self.delta_t = (raw_t[1:] - raw_t[:-1]) mon_raw_t = self._raw_monitors[0].readX(0) delay = mon_raw_t[2] - mon_raw_t[1] - mon_raw_t = mon_raw_t - delay # The original EVS loader, raw.for/rawb.for, does this. Done here to match results + # The original EVS loader, raw.for/rawb.for, does this. Done here to match results + mon_raw_t = mon_raw_t - delay self.mon_pt_times = mon_raw_t[1:] self.delta_tmon = (mon_raw_t[1:] - mon_raw_t[:-1]) @@ -310,7 +313,8 @@ def _get_runs(self): # Load is not doing the right thing when summing. The numbers don't look correct if "-" in run_str: lower,upper = run_str.split("-") - runs = range(int(lower),int(upper)+1) #range goes lower to up-1 but we want to include the last number + # Range goes lower to up-1 but we want to include the last number + runs = range(int(lower),int(upper)+1) elif "," in run_str: runs = run_str.split(",") @@ -322,9 +326,9 @@ def _get_runs(self): def _set_spectra_type(self, spectrum_no): """ - Set whether this spectrum no is forward/backward scattering - and set the normalization range appropriately - @param spectrum_no The current spectrum no + Set whether this spectrum no is forward/backward scattering + and set the normalization range appropriately + @param spectrum_no The current spectrum no """ if spectrum_no >= self._backward_spectra_list[0] and spectrum_no <= self._backward_spectra_list[-1]: self._spectra_type=BACKWARD @@ -385,7 +389,8 @@ def _create_foil_workspaces(self): nhists = first_ws.getNumberHistograms() data_kwargs = {'NVectors':nhists,'XLength':ndata_bins,'YLength':ndata_bins} - self.foil_out = WorkspaceFactory.create(first_ws, **data_kwargs) # This will be used as the result workspace + # This will be used as the result workspace + self.foil_out = WorkspaceFactory.create(first_ws, **data_kwargs) self.foil_out.setDistribution(True) self.foil_thin = WorkspaceFactory.create(first_ws, **data_kwargs) @@ -417,20 +422,21 @@ def _sum_foil_periods(self): foil_out_periods, foil_thin_periods, foil_thick_periods = self._get_foil_periods() if self._nperiods == 6 and self._spectra_type == FORWARD: - mon_out_periods = (5,6) - mon_thin_periods = (3,4) - mon_thick_periods = foil_thick_periods + mon_out_periods = (5,6) + mon_thin_periods = (3,4) + mon_thick_periods = foil_thick_periods else: # None indicates same as standard foil mon_out_periods, mon_thin_periods, mon_thick_periods = (None,None,None) -# + # Foil out self._sum_foils(self.foil_out, self.mon_out, IOUT, foil_out_periods, mon_out_periods) # Thin foil self._sum_foils(self.foil_thin, self.mon_thin, ITHIN, foil_thin_periods, mon_thin_periods) # Thick foil if foil_thick_periods is not None: - self._sum_foils(self.foil_thick, self.mon_thick, ITHICK, foil_thick_periods, mon_thick_periods) + self._sum_foils(self.foil_thick, self.mon_thick, ITHICK, + foil_thick_periods, mon_thick_periods) #---------------------------------------------------------------------------------------- def _get_foil_periods(self): @@ -467,13 +473,14 @@ def _get_foil_periods(self): #---------------------------------------------------------------------------------------- def _sum_foils(self, foil_ws, mon_ws, sum_index, foil_periods, mon_periods=None): """ - Sums the counts from the given foil periods in the raw data group - @param foil_ws :: The workspace that will receive the summed counts - @param mon_ws :: The monitor workspace that will receive the summed monitor counts - @param sum_index :: An index into the sum3 array where the integrated counts will be accumulated - @param foil_periods :: The period numbers that contribute to this sum - @param mon_periods :: The period numbers of the monitors that contribute to this monitor sum - (if None then uses the foil_periods) + Sums the counts from the given foil periods in the raw data group + @param foil_ws :: The workspace that will receive the summed counts + @param mon_ws :: The monitor workspace that will receive the summed monitor counts + @param sum_index :: An index into the sum3 array where the integrated counts will be + accumulated + @param foil_periods :: The period numbers that contribute to this sum + @param mon_periods :: The period numbers of the monitors that contribute to this monitor sum + (if None then uses the foil_periods) """ raw_grp_indices = self.foil_map.get_indices(self._spectrum_no, foil_periods) wsindex = self._ws_index @@ -511,7 +518,9 @@ def _normalise_by_monitor(self): wsindex = self._ws_index # inner function to apply normalization def monitor_normalization(foil_ws, mon_ws): - """Applies monitor normalization to the given foil spectrum from the given monitor spectrum + """ + Applies monitor normalization to the given foil spectrum from the given + monitor spectrum. """ mon_values = mon_ws.readY(wsindex) mon_values_sum = np.sum(mon_values[indices_in_range]) @@ -542,7 +551,8 @@ def normalise_to_out(foil_ws, foil_type): values = foil_ws.dataY(wsindex) sum_values = np.sum(values[range_indices]) if sum_values == 0.0: - self.getLogger().warning("No counts in %s foil spectrum %d." % (foil_type,self._spectrum_no)) + self.getLogger().warning("No counts in %s foil spectrum %d." % ( + foil_type,self._spectrum_no)) sum_values = 1.0 norm_factor = (sum_out/sum_values) values *= norm_factor @@ -611,7 +621,8 @@ def _calculate_double_difference(self, ws_index): eout = self.foil_out.dataE(ws_index) ethin = self.foil_thin.readE(ws_index) ethick = self.foil_thick.readE(ws_index) - np.sqrt((one_min_beta*eout)**2 + ethin**2 + (self._beta**2)*ethick**2, eout) # The second argument makes it happen in place + # The second argument makes it happen in place + np.sqrt((one_min_beta*eout)**2 + ethin**2 + (self._beta**2)*ethick**2, eout) #---------------------------------------------------------------------------------------- def _calculate_thick_difference(self, ws_index): @@ -693,7 +704,8 @@ def _get_header_format(self, ip_filename): try: return IP_HEADERS[len(columns)] except KeyError: - raise ValueError("Unknown format for IP file. Currently support 5/6 column variants. ncols=%d" % (len(columns))) + raise ValueError("Unknown format for IP file. Currently support 5/6 column " + "variants. ncols=%d" % (len(columns))) #---------------------------------------------------------------------------------------- def _store_results(self): @@ -794,11 +806,13 @@ def get_foil_periods(self, spectrum_no, state): return foil_periods def get_indices(self, spectrum_no, foil_state_numbers): - """Returns a tuple of indices that can be used to access the Workspace within + """ + Returns a tuple of indices that can be used to access the Workspace within a WorkspaceGroup that corresponds to the foil state numbers given - @param spectrum_no :: A spectrum number (1->nspectra) - @param foil_state_no :: A number between 1 & 9(inclusive) that defines which foil state is required - @returns A tuple of indices in a WorkspaceGroup that gives the associated Workspace + @param spectrum_no :: A spectrum number (1->nspectra) + @param foil_state_no :: A number between 1 & 9(inclusive) that defines which foil + state is required + @returns A tuple of indices in a WorkspaceGroup that gives the associated Workspace """ indices = [] for state in foil_state_numbers: @@ -834,11 +848,13 @@ def get_index(self, spectrum_no, foil_state_no): def _validate_foil_number(self, foil_number): if foil_number < 1 or foil_number > 9: - raise ValueError("Invalid foil state given, expected a number between 1 and 9. number=%d" % foil_number) + raise ValueError("Invalid foil state given, expected a number between " + "1 and 9. number=%d" % foil_number) def _validate_spectrum_number(self, spectrum_no): if spectrum_no < 1 or spectrum_no > 198: - raise ValueError("Invalid spectrum given, expected a number between 3 and 198. spectrum=%d" % spectrum_no) + raise ValueError("Invalid spectrum given, expected a number between 3 " + "and 198. spectrum=%d" % spectrum_no) ######################################################################################### diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py index 700ec5b13b40..08652064d2c2 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py @@ -1,9 +1,8 @@ -from mantid.api import PythonAlgorithm, AlgorithmFactory,WorkspaceProperty,PropertyMode -from mantid.kernel import Direction,IntArrayProperty, FloatArrayProperty +from mantid.api import PythonAlgorithm, AlgorithmFactory +from mantid.kernel import Direction, IntArrayProperty, FloatArrayProperty import mantid,math,numpy - class SortDetectors(PythonAlgorithm): """ Sort detectors by distance """ @@ -25,21 +24,23 @@ def summary(self): def PyInit(self): """ Declare properties """ - self.declareProperty(mantid.api.WorkspaceProperty("Workspace","",direction=mantid.kernel.Direction.Input, validator=mantid.api.InstrumentValidator()), "Input workspace") + self.declareProperty(mantid.api.WorkspaceProperty("Workspace", "", + direction=mantid.kernel.Direction.Input, + validator=mantid.api.InstrumentValidator()), + "Input workspace") - self.declareProperty(IntArrayProperty("UpstreamSpectra",Direction.Output)) - self.declareProperty(FloatArrayProperty("UpstreamDetectorDistances",Direction.Output)) - self.declareProperty(IntArrayProperty("DownstreamSpectra",Direction.Output)) - self.declareProperty(FloatArrayProperty("DownstreamDetectorDistances",Direction.Output)) - return + self.declareProperty(IntArrayProperty("UpstreamSpectra", Direction.Output)) + self.declareProperty(FloatArrayProperty("UpstreamDetectorDistances", Direction.Output)) + self.declareProperty(IntArrayProperty("DownstreamSpectra", Direction.Output)) + self.declareProperty(FloatArrayProperty("DownstreamDetectorDistances", Direction.Output)) def PyExec(self): """ Main execution body """ - w = self.getProperty("Workspace").value - samplePos=w.getInstrument().getSample().getPos() - moderatorPos=w.getInstrument().getSource().getPos() - incident=samplePos-moderatorPos + workspace = self.getProperty("Workspace").value + samplePos = workspace.getInstrument().getSample().getPos() + moderatorPos = workspace.getInstrument().getSource().getPos() + incident = samplePos - moderatorPos upstream=[] upinds=[] @@ -47,8 +48,8 @@ def PyExec(self): downstream=[] downinds=[] downdist=[] - for i in range(w.getNumberHistograms()): - detPos=w.getDetector(i).getPos() + for i in range(workspace.getNumberHistograms()): + detPos=workspace.getDetector(i).getPos() scattered=detPos-samplePos if abs(scattered.angle(incident))>0.999*math.pi: upstream.append((i,scattered.norm())) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py index dd677756799f..cd8608d1a65e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py @@ -111,8 +111,9 @@ def _calculate_resolution(self, workspace, output_ws_name): fit.initialize() fit.setChild(True) mantid.simpleapi._set_properties(fit, function, InputWorkspace=workspace, MaxIterations=0, - CreateOutput=True, Output=fit_naming_stem, WorkspaceIndex=self._spectrum_index, - OutputCompositeMembers=True) + CreateOutput=True, Output=fit_naming_stem, + WorkspaceIndex=self._spectrum_index, + OutputCompositeMembers=True) fit.execute() fit_ws = fit.getProperty('OutputWorkspace').value diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py index 3fe3e42c49c3..4e8c1750c553 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py @@ -1,7 +1,7 @@ from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * -from mantid import config, logger +from mantid import logger class IndirectResolution(DataProcessorAlgorithm): @@ -36,17 +36,20 @@ def PyInit(self): self.declareProperty(FloatArrayProperty(name='BackgroundRange', values=[0.0, 0.0]), doc='Energy range to use as background') - self.declareProperty(name='RebinParam', defaultValue='', doc='Rebinning parameters (min,width,max)') - self.declareProperty(name='ScaleFactor', defaultValue=1.0, doc='Factor to scale resolution curve by') - self.declareProperty(name='Smooth', defaultValue=False, doc='Apply WienerSmooth to resolution') + self.declareProperty(name='RebinParam', defaultValue='', + doc='Rebinning parameters (min,width,max)') + self.declareProperty(name='ScaleFactor', defaultValue=1.0, + doc='Factor to scale resolution curve by') + self.declareProperty(name='Smooth', defaultValue=False, + doc='Apply WienerSmooth to resolution') self.declareProperty(name='Plot', defaultValue=False, doc='Plot resolution curve') - self.declareProperty(name='Save', defaultValue=False, doc='Save resolution workspace as a Nexus file') + self.declareProperty(name='Save', defaultValue=False, + doc='Save resolution workspace as a Nexus file') def PyExec(self): from IndirectCommon import StartTime, EndTime, getWSprefix - import inelastic_indirect_reducer StartTime('IndirectResolution') self._setup() @@ -113,20 +116,28 @@ def _post_process(self): """ use_scale_factor = self._scale_factor == 1.0 - AddSampleLog(Workspace=self._out_ws, LogName='scale', LogType='String', LogText=str(use_scale_factor)) + AddSampleLog(Workspace=self._out_ws, LogName='scale', + LogType='String', LogText=str(use_scale_factor)) if use_scale_factor: - AddSampleLog(Workspace=self._out_ws, LogName='scale_factor', LogType='Number', LogText=str(self._scale_factor)) + AddSampleLog(Workspace=self._out_ws, LogName='scale_factor', + LogType='Number', LogText=str(self._scale_factor)) - AddSampleLog(Workspace=self._out_ws, LogName='res_smoothing_applied', LogType='String', LogText=str(self._smooth)) + AddSampleLog(Workspace=self._out_ws, LogName='res_smoothing_applied', + LogType='String', LogText=str(self._smooth)) - AddSampleLog(Workspace=self._out_ws, LogName='back_start', LogType='Number', LogText=str(self._background[0])) - AddSampleLog(Workspace=self._out_ws, LogName='back_end', LogType='Number', LogText=str(self._background[1])) + AddSampleLog(Workspace=self._out_ws, LogName='back_start', + LogType='Number', LogText=str(self._background[0])) + AddSampleLog(Workspace=self._out_ws, LogName='back_end', + LogType='Number', LogText=str(self._background[1])) rebin_params = self._rebin_string.split(',') if len(rebin_params) == 3: - AddSampleLog(Workspace=self._out_ws, LogName='rebin_low', LogType='Number', LogText=rebin_params[0]) - AddSampleLog(Workspace=self._out_ws, LogName='rebin_width', LogType='Number', LogText=rebin_params[1]) - AddSampleLog(Workspace=self._out_ws, LogName='rebin_high', LogType='Number', LogText=rebin_params[2]) + AddSampleLog(Workspace=self._out_ws, LogName='rebin_low', + LogType='Number', LogText=rebin_params[0]) + AddSampleLog(Workspace=self._out_ws, LogName='rebin_width', + LogType='Number', LogText=rebin_params[1]) + AddSampleLog(Workspace=self._out_ws, LogName='rebin_high', + LogType='Number', LogText=rebin_params[2]) self.setProperty('OutputWorkspace', self._out_ws) From 3dfa3e9f9e76b4fa083b6f638e094bf7fa6fc80b Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Tue, 17 Feb 2015 14:50:04 +0000 Subject: [PATCH 243/414] Revert "Pull request #102 from mantidproject/feature/9843_integrate_sysmonitor_widget" This reverts commit 8efc44804a5bc9a95ac8952cb55c573569c4472b, reversing changes made to fbe8a6f8dd16bd42ed10ce466f03bc1116fac3ed. --- Code/Mantid/CMakeLists.txt | 10 +- Code/Mantid/MantidPlot/CMakeLists.txt | 24 +- Code/Mantid/MantidPlot/SysMon/README.md | 25 - Code/Mantid/MantidPlot/SysMon/SysMon.pyw | 114 --- Code/Mantid/MantidPlot/SysMon/__init__.py | 0 Code/Mantid/MantidPlot/SysMon/_version.py | 4 - Code/Mantid/MantidPlot/SysMon/config.py | 20 - Code/Mantid/MantidPlot/SysMon/sysmon.py | 272 ------- Code/Mantid/MantidPlot/SysMon/sysmon_tools.py | 658 ---------------- Code/Mantid/MantidPlot/SysMon/ui_sysmon.py | 390 ---------- Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui | 735 ------------------ .../MantidPlot/SysMon/ui_sysmonMainWindow.py | 69 -- .../MantidPlot/SysMon/ui_sysmonMainWindow.ui | 81 -- .../MantidPlot/src/ApplicationWindow.cpp | 106 +-- .../Mantid/MantidPlot/src/ApplicationWindow.h | 23 +- .../MantidPlot/src/Mantid/MantidDock.cpp | 49 +- Code/Mantid/MantidPlot/src/Mantid/MantidUI.h | 26 +- Code/Mantid/MantidPlot/src/qti.sip | 10 +- 18 files changed, 72 insertions(+), 2544 deletions(-) delete mode 100644 Code/Mantid/MantidPlot/SysMon/README.md delete mode 100755 Code/Mantid/MantidPlot/SysMon/SysMon.pyw delete mode 100644 Code/Mantid/MantidPlot/SysMon/__init__.py delete mode 100644 Code/Mantid/MantidPlot/SysMon/_version.py delete mode 100644 Code/Mantid/MantidPlot/SysMon/config.py delete mode 100644 Code/Mantid/MantidPlot/SysMon/sysmon.py delete mode 100644 Code/Mantid/MantidPlot/SysMon/sysmon_tools.py delete mode 100644 Code/Mantid/MantidPlot/SysMon/ui_sysmon.py delete mode 100644 Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui delete mode 100644 Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.py delete mode 100644 Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.ui diff --git a/Code/Mantid/CMakeLists.txt b/Code/Mantid/CMakeLists.txt index aa0093eee2df..2b79286d6eb5 100644 --- a/Code/Mantid/CMakeLists.txt +++ b/Code/Mantid/CMakeLists.txt @@ -197,8 +197,8 @@ if ( ENABLE_CPACK ) set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},poco-crypto,poco-data,poco-mysql,poco-sqlite,poco-odbc,poco-util,poco-xml,poco-zip,poco-net,poco-netssl,poco-foundation,PyQt4,sip" ) set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},python-ipython >= 1.1.0" ) - # scipy, matplotlib, psutil - set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},scipy,python-matplotlib,python-psutil" ) + # scipy & matplotlib + set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},scipy,python-matplotlib" ) set ( CPACK_RPM_PACKAGE_REQUIRES "${CPACK_RPM_PACKAGE_REQUIRES},mxml,hdf,hdf5,jsoncpp" ) if( "${UNIX_CODENAME}" MATCHES "Santiago" ) @@ -226,19 +226,19 @@ if ( ENABLE_CPACK ) set ( PERFTOOLS_DEB_PACKAGE "libgoogle-perftools0 (>= 1.7)" ) if( "${UNIX_CODENAME}" MATCHES "lucid" ) list ( APPEND DEPENDS_LIST ",libqscintilla2-5," - "libopencascade-foundation-6.3.0 (>= 6.3.0),libopencascade-modeling-6.3.0 (>= 6.3.0),python-psutil," + "libopencascade-foundation-6.3.0 (>= 6.3.0),libopencascade-modeling-6.3.0 (>= 6.3.0)," "libmuparser0,libpocofoundation9,libpocoutil9,libpoconet9,libpoconetssl9,libpococrypto9,libpocoxml9" ) elseif( "${UNIX_CODENAME}" MATCHES "precise" ) list ( APPEND DEPENDS_LIST ",libqscintilla2-8," "libopencascade-foundation-6.5.0 (>= 6.5.0),libopencascade-modeling-6.5.0 (>= 6.5.0)," "libmuparser0debian1," - "ipython-qtconsole (>= 1.1),python-matplotlib,python-scipy,python-psutil," + "ipython-qtconsole (>= 1.1),python-matplotlib,python-scipy," "libpocofoundation9,libpocoutil9,libpoconet9,libpoconetssl9,libpococrypto9,libpocoxml9") elseif( "${UNIX_CODENAME}" STREQUAL "trusty" ) list ( APPEND DEPENDS_LIST ",libqscintilla2-11," "liboce-foundation8,liboce-modeling8," "libmuparser2," - "ipython-qtconsole (>= 1.1),python-matplotlib,python-scipy,python-psutil," + "ipython-qtconsole (>= 1.1),python-matplotlib,python-scipy," "libpocofoundation11,libpocoutil11,libpoconet11,libpoconetssl11,libpococrypto11,libpocoxml11") set ( PERFTOOLS_DEB_PACKAGE "libgoogle-perftools4 (>= 1.7)" ) else() diff --git a/Code/Mantid/MantidPlot/CMakeLists.txt b/Code/Mantid/MantidPlot/CMakeLists.txt index 63f091d4a3b0..68daaff89d6f 100644 --- a/Code/Mantid/MantidPlot/CMakeLists.txt +++ b/Code/Mantid/MantidPlot/CMakeLists.txt @@ -880,21 +880,6 @@ copy_files_to_dir ( "${IPY_FILES}" ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/ipython_widget IPYTHON_INSTALL_FILES ) -# SysMon scripts -set( SYSMON_FILES - __init__.py - _version.py - config.py - sysmon.py - sysmon_tools.py - ui_sysmon.py - ui_sysmon.ui -) -copy_files_to_dir ( "${SYSMON_FILES}" - ${CMAKE_CURRENT_SOURCE_DIR}/SysMon - ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/SysMon - SYSMON_INSTALL_FILES ) - ########################################################################### # MantidPlot executable ########################################################################### @@ -902,7 +887,7 @@ copy_files_to_dir ( "${SYSMON_FILES}" add_executable ( MantidPlot ${WIN_CONSOLE} MACOSX_BUNDLE ${ALL_SRC} src/main.cpp ${INC_FILES} ${QTIPLOT_C_SRC} ${UI_HDRS} ${RES_FILES} ${MANTID_RC_FILE} - ${PYTHON_INSTALL_FILES} ${MTDPLOT_INSTALL_FILES} ${CONFIG_RESET_SCRIPT_FILE} ${MTDPLOT_FUTURE_INSTALL_FILES} ${IPYTHON_INSTALL_FILES} ${SYSMON_INSTALL_FILES} + ${PYTHON_INSTALL_FILES} ${MTDPLOT_INSTALL_FILES} ${CONFIG_RESET_SCRIPT_FILE} ${MTDPLOT_FUTURE_INSTALL_FILES} ${IPYTHON_INSTALL_FILES} ) # Library dependencies @@ -1050,9 +1035,6 @@ endforeach() foreach(PY_FILE ${IPY_FILES} ) install ( FILES ipython_widget/${PY_FILE} DESTINATION ${BIN_DIR}/ipython_widget ) endforeach() -foreach(PY_FILE ${SYSMON_FILES} ) - install ( FILES SysMon/${PY_FILE} DESTINATION ${BIN_DIR}/SysMon ) -endforeach() install ( FILES ${CONFIG_RESET_SCRIPT} DESTINATION ${BIN_DIR} ) # file make_package.rb contains hard-coded path to the libraries @@ -1060,11 +1042,11 @@ install ( FILES ${CONFIG_RESET_SCRIPT} DESTINATION ${BIN_DIR} ) # therefore MACPORTS option is introduced if ( APPLE ) if (OSX_VERSION VERSION_LESS 10.9 OR MACPORTS) - configure_file ( ${CMAKE_CURRENT_SOURCE_DIR}/FixBundle.cmake.in + configure_file ( ${CMAKE_CURRENT_SOURCE_DIR}/FixBundle.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/FixBundle.cmake @ONLY ) - install ( SCRIPT ${CMAKE_CURRENT_BINARY_DIR}/FixBundle.cmake ) + install ( SCRIPT ${CMAKE_CURRENT_BINARY_DIR}/FixBundle.cmake ) else () install ( FILES make_package.rb DESTINATION MantidPlot.app/ ) configure_file ( ${CMAKE_CURRENT_SOURCE_DIR}/FixMavericksBundle.cmake.in diff --git a/Code/Mantid/MantidPlot/SysMon/README.md b/Code/Mantid/MantidPlot/SysMon/README.md deleted file mode 100644 index 8ef2ab770d04..000000000000 --- a/Code/Mantid/MantidPlot/SysMon/README.md +++ /dev/null @@ -1,25 +0,0 @@ -SysMon -====== - -Python qt system monitor which utilizes the Python psutil and platform modules to provide system information for display. - -This application has been adapted to work with psutil version 1 and version 2 modules as there are some command syntax changes between these two versions. - -The SysMon user interface has been divided into a main window which imports the tabs to make a standalone application, or the tabs can be imported into other applications as a QWidget. Thus there are separate .ui files corresponding to each. - -The code which imports the tabs into the main program resides in SysMon.pyw. This is where to look to see how to include the tabs into your own application. All files except SysMon.pyw and ui_sysmonMainWindow.* will be required when tabs are incorporated in other applications. - -The following command line arguments have been added: - --help to print out the help message. - --nompl to run the application minus matplotlib in support of the current MantidPlot (removes those tabs requiring matplotlib). - --custom to enable the custom menubar item in the standalone application (currently supports checking Matlab license status on SNS analysis computers). - -To run as a standalone application via the corresponding command lines: - *Change to the folder containing the Sysmon software, then: - *DOS: python SysMon.pyw - *Linux: ./SysMon.pyw - -The standalone application been tested on Windows and RHEL Linux, but not on Mac yet. - -Note that configuration and global constants and variables now reside in config.py. - diff --git a/Code/Mantid/MantidPlot/SysMon/SysMon.pyw b/Code/Mantid/MantidPlot/SysMon/SysMon.pyw deleted file mode 100755 index 638813a2990d..000000000000 --- a/Code/Mantid/MantidPlot/SysMon/SysMon.pyw +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/python -""" -SysMon.pyw -Initial application development 03Sep14 by S. Miller -The application utilizes the psutil and platform python modules to provide system information -for display via text fields, a table and Matplotlib plots. - -The application utilizes a timer with user selectable timer intervals to update information -provided to the application. -""" -import config -import sys - -__version__="unknown" -try: - from _version import __version__ -except ImportError: - #_version.py file not found - version not known in this case so use - #the default previously given. - pass - -#parse args - doing it here as config structure needs to be filled prior to importing sysmon -if ['--nompl'] == [s for s in sys.argv if '--nompl' in s]: - #case to not use matplotlib - config.nompl=True -else: - #case to use matplotlib (default case) - config.nompl=False - -if ['--help'] == [s for s in sys.argv if '--help' in s]: - print "SysMon Help" - print "--help - this message" - print "--nompl - flag to disable using matplotlib, also disables History and Users tabs" - print "--custom: - flag to use facility specific options" - sys.exit() - -if ['--custom'] == [s for s in sys.argv if '--custom' in s]: - config.custom=True - -from PyQt4 import QtGui - -from ui_sysmonMainWindow import * -#from ui_sysmonTabs import * -from sysmon import * - -class SysMonMainWindow(QtGui.QMainWindow): - - def __init__(self, parent=None): - #setup main window - QtGui.QMainWindow.__init__(self, parent) - self.setWindowTitle("System Status") - self.ui = Ui_MainWindow() #defined from ui_sysmon.py - self.ui.setupUi(self) - #setup tabs - class imported from sysmon.py - self.sysmontabs=SysMon(self) - self.setCentralWidget(self.sysmontabs) - - #setup menu bar actions - self.connect(self.ui.actionExit, QtCore.SIGNAL('triggered()'), self.confirmExit) #define function to confirm and perform exit - self.connect(self.ui.actionAbout, QtCore.SIGNAL('triggered()'), self.About) - self.connect(self.ui.actionCheck_Matlab_Licenses, QtCore.SIGNAL('triggered()'), self.updateMatlab) - - #check if custom menu bar enabled via command line flag --custom and if not, remove it as it's built by default from Qt - if not(config.custom): - self.ui.menubar.removeAction(self.ui.menuCustom.menuAction()) - - - #define methods for menu bar options - def confirmExit(self): - reply = QtGui.QMessageBox.question(self, 'Message', - "Are you sure to quit?", QtGui.QMessageBox.Yes | - QtGui.QMessageBox.No, QtGui.QMessageBox.No) - - if reply == QtGui.QMessageBox.Yes: - #close application - self.close() - else: - #do nothing and return - pass - - def About(self): - dialog=QtGui.QMessageBox(self) - dialog.setText("PyQt4 System Monitoring Application "+__version__) - info='Application Info: \n\r * Changing the Update Rate Clears plots \n\r * It may take one full new update cycle for changes to take effect \n\r * Update rate shown in History plot xaxis label \n\r * Process tab CPU percentage can be greater than 100 when more than a single core is involved' - dialog.setDetailedText(info) #give full info in detailed text - dialog.exec_() - - def updateMatlab(self): - #run license server command to extract license info - info=commands.getstatusoutput(config.matlabchk) - info=str(info[1]) #seem to need to make this a string for Linux to work properly - #test if info string contains MATLAB info - if info.find("MATLAB") < 0: - #case where no license server found - outstr="No Matlab License Server Found to Check" - else: - indx0=info.find("Users of MATLAB:") - indx1=info.find("licenses in use") - if indx0 > -1 and indx1 > -1: - outstr=info[indx0:indx1+15+1] - else: - outstr="Unable to determine Matlab license information" - dialog=QtGui.QMessageBox(self) - #print "outstr: "+outstr - dialog.setText(outstr) - dialog.setDetailedText(info) #give full info in detailed text - dialog.exec_() - -if __name__=="__main__": - app = QtGui.QApplication(sys.argv) - sysmon = SysMonMainWindow() - sysmon.show() - - sys.exit(app.exec_()) \ No newline at end of file diff --git a/Code/Mantid/MantidPlot/SysMon/__init__.py b/Code/Mantid/MantidPlot/SysMon/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/Code/Mantid/MantidPlot/SysMon/_version.py b/Code/Mantid/MantidPlot/SysMon/_version.py deleted file mode 100644 index b88b26dd7c4b..000000000000 --- a/Code/Mantid/MantidPlot/SysMon/_version.py +++ /dev/null @@ -1,4 +0,0 @@ -#File to identify the current version of the software -#Note that this file must be manually updated to contain the same -#version number as the git tag for the check-in. -__version__="v0.29" \ No newline at end of file diff --git a/Code/Mantid/MantidPlot/SysMon/config.py b/Code/Mantid/MantidPlot/SysMon/config.py deleted file mode 100644 index f52dcf1e520e..000000000000 --- a/Code/Mantid/MantidPlot/SysMon/config.py +++ /dev/null @@ -1,20 +0,0 @@ - -#global definitions for constants and variables - -#Tab indices - based upon the order of the tabs as built via Qt and these must be the same as the Qt GUI. -SYST_TAB=0 -HIST_TAB=1 -PROC_TAB=2 -USER_TAB=3 -OPTS_TAB=4 - -#Global Variables: -psutilVer=0 #flag for the version of psutil being used -nompl=False #Flag to indicate if using matplotlib - True, then do not use plots, False, then try to use matplotlib plots -mplLoaded=False #flag for matplotlib loading -custom=False #flag to indicate if the custom interface is to be used (usually not) -matlabchk='lmstat -S -c 27010@licenses1.sns.gov' #text command to status the Matlab license server (only for custom mode with SysMon.pyw) -basefontsize=9 #basic font size when GUI is at minimum size -fscl=0.5 #scale factor for font size change with GUI resizing - less than one, font size slower than GUI size change, and greater than one font size faster than GUI size change -pltFont=9 #initial font size for matplotlib plots -linewidth=1 #initial line widths for matplotlib plots \ No newline at end of file diff --git a/Code/Mantid/MantidPlot/SysMon/sysmon.py b/Code/Mantid/MantidPlot/SysMon/sysmon.py deleted file mode 100644 index 33249856c52c..000000000000 --- a/Code/Mantid/MantidPlot/SysMon/sysmon.py +++ /dev/null @@ -1,272 +0,0 @@ - - -import sys, os, time -import re -import config #application constants and variables -#suppress deprecation warnings that can occur when importing psutil version 2 -#note - all deprecation warnings will probably be suppressed using this filterwarnings -#as specifying the psutil module specifically in filterwarnings did not suppress -#these warnings -import warnings -warnings.filterwarnings('ignore',category=DeprecationWarning) -import psutil - -#check psutil version as command syntax changes between version 1 and version 2 -ver=psutil.__version__ -#using positional numeric wildcards for re.match() to check sub versions -#match returns a match object if a match is found else returns NoneType -if re.match('0.[0-9].[0-9]',ver) or re.match('1.[0-9].[0-9]',ver) != None: - #set flag to version 1 if either version 0 or version 1 psutil imported - config.psutilVer=1 -else: - #set flat to version 2 for any versions higher than version 1 - config.psutilVer=2 - -from ui_sysmon import * -from sysmon_tools import * - - -import platform -import commands - -try: - _fromUtf8 = QtCore.QString.fromUtf8 -except AttributeError: - _fromUtf8 = lambda s: s - -#import application version information -__version__="unknown" -try: - from _version import __version__ -except ImportError: - #_version.py file not found - version not known in this case so use - #the default previously given. - pass - -class SysMon(QtGui.QWidget): - - def __init__(self, parent=None): - QtGui.QWidget.__init__(self, parent) - self.ui = Ui_Form() #defined from ui_sysmon.py - self.ui.setupUi(self) - self.ui.parent=parent - self.ui.progressBarStatusMemory.setStyleSheet("QProgressBar {width: 25px;border: 1px solid black; border-radius: 3px; background: white;text-align: center;padding: 0px;}" - +"QProgressBar::chunk:horizontal {background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #00CCEE, stop: 0.3 #00DDEE, stop: 0.6 #00EEEE, stop:1 #00FFEE);}") - self.ui.progressBarStatusCPU.setStyleSheet("QProgressBar {width: 25px;border: 1px solid black; border-radius: 3px; background: white;text-align: center;padding: 0px;}" - +"QProgressBar::chunk:horizontal {background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #00CCEE, stop: 0.3 #00DDEE, stop: 0.6 #00EEEE, stop:1 #00FFEE);}") - - #setup timer to enable periodic events such as status update checks - self.ctimer = QtCore.QTimer() - self.ctimer.start(2000) #time in mSec - set default update timer cycle to 2 seconds - QtCore.QObject.connect(self.ctimer, QtCore.SIGNAL("timeout()"), self.constantUpdate) - - #update rate actions - QtCore.QObject.connect(self.ui.radioButton1Sec, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update1Sec) - QtCore.QObject.connect(self.ui.radioButton2Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update2Sec) - QtCore.QObject.connect(self.ui.radioButton5Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update5Sec) - QtCore.QObject.connect(self.ui.radioButton10Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update10Sec) - self.update=2 #set default to 2 seconds update rate - - #duration actions - QtCore.QObject.connect(self.ui.radioButton60Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update60Duration) - QtCore.QObject.connect(self.ui.radioButton300Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update300Duration) - QtCore.QObject.connect(self.ui.radioButton600Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update600Duration) - QtCore.QObject.connect(self.ui.radioButton3600Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update3600Duration) - self.duration=60 #set default plot duration to 60 seconds - - QtCore.QObject.connect(self.ui.pushButtonUpdate, QtCore.SIGNAL('clicked(bool)'), self.updateProcesses) - - #Initialize System Tab - self.ui.tabWidget.setCurrentIndex(config.SYST_TAB) - self.ui.labelComputerName.setText("Computer Name: "+platform.node()) - if platform.os.name == 'nt': - info=platform.win32_ver() - oslabel="Windows "+info[0]+" Version: "+info[1] - elif platform.os.name == 'posix': - info=platform.linux_distribution() - oslabel=info[0]+" Version: "+info[1] - elif platform.os.name == 'mac': - info=platform.mac_ver() - oslabel=info[0]+" Version: "+info[1] - else: - oslabel=" " - - self.ui.labelOS.setText("Operating System: "+oslabel) - info=platform.uname() - self.ui.labelProcFam.setText("Processor Family: "+info[5]) - - #determine the number of users on the computer - userInfo=psutil.get_users() if config.psutilVer==1 else psutil.users() - lst=[] - for item in userInfo: - lst.append(item.name) - uusers=set(lst) - Nuusers=len(uusers) - self.ui.labelNUsers.setText("Number of Users Logged On: "+str(Nuusers)) - - #determine the computer uptime - if config.psutilVer == 1: - uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.BOOT_TIME)) - else: - uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.boot_time())) - self.ui.labelUptime.setText("System Uptime: "+uptime) - - if config.mplLoaded: - #if matplotlib loaded OK, initialize plotting - #Initialize History Tab - self.ui.tabWidget.setCurrentIndex(config.HIST_TAB) - #Place Matplotlib figure within the GUI frame - #create drawing canvas - # a figure instance to plot on - - #rc_context in matplotlib requires version 1.2.0 or later, so check we don't have an older version of matplotlib - if not re.match('1.[0-1]',matplotlib.__version__) and not re.match('0.',matplotlib.__version__): - #if not an old version of matplotlib, then use the following command - matplotlib.rc_context({'toolbar':False}) - #initialize figure 1 and its canvas for cpu and memory history plots - self.ui.figure = plt.figure(1) - # the Canvas Widget displays the `figure` - # it takes the `figure` instance as a parameter to __init__ - self.ui.canvas = FigureCanvas(self.ui.figure) - layout=QtGui.QVBoxLayout(self.ui.framePlot) - layout.addWidget(self.ui.canvas) - self.ui.layout=layout - - #initialize figure 2 and its canvas for user usage bar chart - self.ui.figure2 = plt.figure(2) - self.ui.canvas2 = FigureCanvas(self.ui.figure2) - layout2=QtGui.QVBoxLayout(self.ui.frameBar) - layout2.addWidget(self.ui.canvas2) - self.ui.layout2=layout2 - - - else: - #if matplotlib not loaded, remove the tabs that depend upon it - self.removeMPLTabs() - - #initialize history plot arrays - easier just to initialize these even if not doing plotting in case when matplotlib not available. - Nsamples=3600 - self.ui.Nsamples=Nsamples - #need one extra sample to fill the plotting interval - self.ui.cpu=np.zeros(Nsamples+1) - self.ui.mem=np.zeros(Nsamples+1) - self.ui.dt=[None]*(Nsamples+1) - self.ui.cpuMe=np.zeros(Nsamples+1) - self.ui.memMe=np.zeros(Nsamples+1) - - self.ui.tabWidget.setTabsClosable(False) #disable the ability to close tabs once state of matplotlib is handled - - #initialize the process table - self.doUpdates=True #flag for updating the process tab table - updateProcTable(self,config) - - #upon initialization completion, set System tab (first tab on left) as the visible tab - self.ui.tabWidget.setCurrentIndex(config.SYST_TAB) - - #initialize version label - self.ui.labelVersion.setText("Version: "+__version__+"_"+matplotlib.__version__+"_"+psutil.__version__) - - def constantUpdate(self): - #redirct to global function - constantUpdateActor(self,config) - - def update1Sec(self): - self.update=1 - self.ctimer.stop() - self.ctimer.start(1000) - #clear persistent arrays when update rate changed - self.ui.cpu=self.ui.cpu*0 - self.ui.mem=self.ui.mem*0 - self.ui.cpuMe=self.ui.cpuMe*0 - self.ui.memMe=self.ui.memMe*0 - self.ui.dt=[None]*self.ui.Nsamples - - def update2Sec(self): - self.update=2 - self.ctimer.stop() - self.ctimer.start(2000) - #clear persistent arrays when update rate changed - self.ui.cpu=self.ui.cpu*0 - self.ui.mem=self.ui.mem*0 - self.ui.cpuMe=self.ui.cpuMe*0 - self.ui.memMe=self.ui.memMe*0 - self.ui.dt=[None]*self.ui.Nsamples - - def update5Sec(self): - self.update=5 - self.ctimer.stop() - self.ctimer.start(5000) - #clear persistent arrays when update rate changed - self.ui.cpu=self.ui.cpu*0 - self.ui.mem=self.ui.mem*0 - self.ui.cpuMe=self.ui.cpuMe*0 - self.ui.memMe=self.ui.memMe*0 - self.ui.dt=[None]*self.ui.Nsamples - - def update10Sec(self): - self.update=10 - self.ctimer.stop() - self.ctimer.start(10000) - #clear persistent arrays when update rate changed - self.ui.cpu=self.ui.cpu*0 - self.ui.mem=self.ui.mem*0 - self.ui.cpuMe=self.ui.cpuMe*0 - self.ui.memMe=self.ui.memMe*0 - self.ui.dt=[None]*self.ui.Nsamples - - def update60Duration(self): - self.duration=60 - def update300Duration(self): - self.duration=300 - def update600Duration(self): - self.duration=600 - def update3600Duration(self): - self.duration=3600 - - def updateProcesses(self): - if self.doUpdates == True: - #case to toggle to False - self.doUpdates=False - self.ui.pushButtonUpdate.setText('Continue') - else: - #case where updates must be off - self.doUpdates=True - self.ui.pushButtonUpdate.setText('Hold Updates') - - def resizeEvent(self,resizeEvent): - sz=self.ui.tableWidgetProcess.size() - w=sz.width() - wmin=self.ui.parent.minimumSize().width() #establish minimum table size based upon parent widget minimum size - if w < wmin: - w=wmin - #now use widget width to determine process table column width - self.ui.tableWidgetProcess.setColumnWidth(0,3.5*w/20) #PID - self.ui.tableWidgetProcess.setColumnWidth(1,4*w/20) #User - self.ui.tableWidgetProcess.setColumnWidth(2,3.5*w/20) #CPU% - self.ui.tableWidgetProcess.setColumnWidth(3,3.5*w/20) #MEM% - self.ui.tableWidgetProcess.setColumnWidth(4,5.5*w/20) #Name - - #check size of GUI to determine the size of font to use. - minSz=self.ui.parent.minimumSize().width() #establish minimum table size based upon parent widget minimum size - curSz=self.ui.parent.size().width() - #print "current size: ",curSz," type: ",type(curSz)," min size: ",minSz," type: ",type(minSz) - fsize=max([int(config.basefontsize*float(curSz)/float(minSz)*config.fscl),config.basefontsize]) - #print "Font Size: ",fsize - config.pltFont=fsize - - #adapt plot line width to GUI size change - config.linewidth=min([max([int(float(curSz)/float(minSz)),1]),3]) - - def removeMPLTabs(self): - #In case matplotlib not available, remove tabs requiring this - #Note to developers - removing tabs changes the tab index numbers! - #Keep this in mind regarding setting and using tab indices - self.ui.tabWidget.removeTab(config.HIST_TAB) #History tab - config.HIST_TAB=-1 - config.PROC_TAB-=1 - config.USER_TAB-=1 - config.OPTS_TAB-=1 - self.ui.tabWidget.removeTab(config.USER_TAB) #Users tab - originally tab 3, but becomes tab 2 once history tab is removed - config.USER_TAB=-1 - config.OPTS_TAB-=1 - self.ui.tabWidget.setTabsClosable(False) diff --git a/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py b/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py deleted file mode 100644 index e0dc66da4615..000000000000 --- a/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py +++ /dev/null @@ -1,658 +0,0 @@ -#suppress deprecation warnings that can occur when importing psutil version 2 -#note - all deprecation warnings will probably be suppressed using this filterwarnings -#as specifying the psutil module specifically in filterwarnings did not suppress -#these warnings -import warnings -warnings.filterwarnings('ignore',category=DeprecationWarning) -import psutil - -from PyQt4 import Qt, QtCore, QtGui -import datetime -import numpy as np -import config -import math -import getpass -import re -import sys -import time - -#check if command line flag --nompl set to disable matplotlib -if not(config.nompl): - try: - import matplotlib - if matplotlib.get_backend() != 'QT4Agg': - matplotlib.use('QT4Agg') - from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas - from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as NavigationToolbar - import matplotlib.pyplot as plt - config.mplLoaded=True - # print "matplotlib try successful" - except: - # print "matplotlib except case" - #case where matplotlib not available - need to know this for handling plotting tabs - config.mplLoaded=False - pass -else: - config.mplLoaded=False #use this flag to test case when matplotlib is not available - -def constantUpdateActor(self,config): - - #set duration number - Ndur=self.duration - - #get current CPU percent busy - percentcpubusy = psutil.cpu_percent() - - percentmembusy=psutil.virtual_memory().percent - self.ui.progressBarStatusMemory.setValue(round(percentmembusy)) - Ncpus=len(psutil.cpu_percent(percpu=True)) - self.ui.Ncpus=Ncpus - totalcpustr='CPU Count: '+str(Ncpus) -# print "Total CPU str: ",totalcpustr - self.ui.labelCPUCount.setText(totalcpustr+' - CPU Utilization:') - totalmem=int(round(float(psutil.virtual_memory().total)/(1024*1024*1024))) #psutil syntax OK for both versions -# print "Total Mem: ",totalmem - self.ui.totalmem=totalmem - totalmemstr=str(totalmem)+' GB' - self.ui.labelMemUsage.setText('Memory Usage: '+str(totalmem*percentmembusy/100)+' GB of '+totalmemstr) -# print "Total Mem str: ",totalmemstr - - # update system tab - if self.ui.tabWidget.currentIndex() == config.SYST_TAB: - #determine the computer uptime - if config.psutilVer == 1: - uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.BOOT_TIME)) - else: - uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.boot_time())) - self.ui.labelUptime.setText("System Uptime: "+uptime) - - - - #update the number of users each time interval as well - userInfo=psutil.get_users() if config.psutilVer == 1 else psutil.users() - lst=[] - for item in userInfo: - lst.append(item.name) - uusers=set(lst) - Nuusers=len(uusers) - self.ui.labelNUsers.setText("Number of Users Logged On: "+str(Nuusers)) - - #determine "Me" user CPU and memory statistics - Me=getpass.getuser() - cpupctMe=0 - memValMe=0 - cpupctTot=0 - memValTot=0 - for proc in psutil.process_iter(): - try: - #check if process still exists, if so, update dictionaries - cpupct=proc.get_cpu_percent(interval=0) if config.psutilVer == 1 else proc.cpu_percent(interval=0) - memVal=proc.get_memory_percent() if config.psutilVer == 1 else proc.memory_percent() - - try: - #some processes give permission denied when getting the name, if so, fail out gracefully using this try. - if config.psutilVer == 1: - uname=proc.username - else: - uname=proc.username() - #print "proc.username: ",uname," type: ",type(uname)," Me: ",Me," type: ",type(Me) - except: - uname='' - except: - #skip process - case where process no longer exists - cpupct=0 - memVal=0 - uname='' - cpupctTot+=cpupct - memValTot+=memVal - #print "uname: ",uname," Me: ",Me - #note that on Windows systems that getpass.getuser() does not return the same base username as proc.username, so check for the smaller - if Me in uname: - cpupctMe+=cpupct - memValMe+=memVal - #print "cpupctMe: ",cpupctMe," memValMe: ",memValMe - - #update first position with most recent value overwriting oldest value which has been shifted to first position - self.ui.cpu=np.roll(self.ui.cpu,1) - #check if CPU smoothing to be applied - sm=int(str(self.ui.comboBoxCPUHistSmooth.currentText())) - if sm == 1: - self.ui.cpu[0]=percentcpubusy - elif sm >1: - self.ui.cpu[0]=(percentcpubusy+np.sum(self.ui.cpu[1:sm]))/sm - else: - #unknown case - default to no smoothing - self.ui.cpu[0]=percentcpubusy - #update progress bar with (potentially) smoothed cpu percentage - self.ui.progressBarStatusCPU.setValue(round(self.ui.cpu[0])) - self.ui.mem=np.roll(self.ui.mem,1) - self.ui.mem[0]=percentmembusy - self.ui.cpuMe=np.roll(self.ui.cpuMe,1) - #check if CPU smoothing to be applied - if sm == 1: - self.ui.cpuMe[0]=cpupctMe/(Ncpus) - elif sm>1: - self.ui.cpuMe[0]=(cpupctMe/(Ncpus)+np.sum(self.ui.cpuMe[1:sm]))/sm - else: - #use no filtering in case sm is unknown (should never happen...) - self.ui.cpuMe[0]=cpupctMe/(Ncpus) - self.ui.memMe=np.roll(self.ui.memMe,1) - self.ui.memMe[0]=memValMe - - - #update the history plot - if self.ui.tabWidget.currentIndex() == config.HIST_TAB: - #only update history plot if tab is active - font = {'family' : 'sans-serif', - 'weight' : 'bold', - 'size' : config.pltFont+1} - matplotlib.rc('font', **font) - - xtime=range(0,self.ui.Nsamples+1,self.update) - - Npts=Ndur/self.update - - plt.figure(self.ui.figure.number) #make plot figure active - plt.clf() #clear figure each time for rolling updates to show - plt.plot(xtime[0:Npts+1],self.ui.cpu[0:Npts+1],color='Blue',label='CPU: All',linewidth=config.linewidth) - plt.plot(xtime[0:Npts+1],self.ui.mem[0:Npts+1],color='Green',label='Mem: All',linewidth=config.linewidth) - plt.plot(xtime[0:Npts+1],self.ui.cpuMe[0:Npts+1],color='red',label='CPU: '+Me,linewidth=config.linewidth) - plt.plot(xtime[0:Npts+1],self.ui.memMe[0:Npts+1],color='cyan',label='Mem: '+Me,linewidth=config.linewidth) - - plt.title('Composite CPU and Memory Activity',fontsize=config.pltFont+1,fontweight='bold') - plt.ylabel('% Used',fontsize=config.pltFont+0.5,fontweight='bold') - - if self.update == 1: - xlab="Seconds with 1 Second Updates" - elif self.update == 2: - xlab="Seconds with 2 Second Updates" - elif self.update == 5: - xlab="Seconds with 5 Second Updates" - elif self.update == 10: - xlab="Seconds with 10 Second Updates" - plt.xlabel(xlab,fontsize=config.pltFont+0.5,fontweight='bold') - plt.legend(loc="upper right",prop={'size':config.pltFont}) - - plt.xlim([0,Ndur]) - self.ui.canvas.draw() - - #update the process table - if self.ui.tabWidget.currentIndex() == config.PROC_TAB: - #only update process table if tab is active - updateProcTable(self,config) - - #update the Users bar chart - if self.ui.tabWidget.currentIndex() == config.USER_TAB: - #only update bar chart if the tab is active. - updateUserChart(self,config) - - - -def updateProcTable(self,config): - if self.doUpdates==True: - - Ncpus=len(psutil.cpu_percent(percpu=True)) - - table=self.ui.tableWidgetProcess - #first remove all rows - Nrows=table.rowCount() - for row in range(Nrows): - table.removeRow(0) - - #get the processes - pidList=psutil.get_pid_list() if config.psutilVer == 1 else psutil.pids() - Npids=len(pidList) - - #now add rows to the table according to the number of processes - # for row in range(Npids): - # table.insertRow(0) - - #now populate the table - row=0 #table row counter incremented for each row added to the process table - rout=0 #counter for number of rows to remove due to invalid processes - memtot=psutil.virtual_memory() #psutil syntax OK for both versions - - #determine which column has been selected for sorting - column_sorted=table.horizontalHeader().sortIndicatorSection() - order = table.horizontalHeader().sortIndicatorOrder() - #temporarily set sort column to outside column range so that table items can be filled properly - table.sortItems(5,order=QtCore.Qt.AscendingOrder) - #print table.horizontalHeader().sortIndicatorSection() - - #create empty dictionaries to be used by the process table - d_user={} - d_cpu={} - d_mem={} - d_name={} - d_cpuTimes={} - d_procTimes={} - - #fill the dictionaries - seems to need to be done faster than within loop which also fills the table...not sure why... - - try: - #check if this dictionary exists or not - self.ui.d_procTimes - self.ui.d_cpuTimes - #if so, move on - pass - except: - #case to initialize the dictionary - for proc in psutil.process_iter(): - try: - #check if acess denied - pname=proc.name - proctime=proc.get_cpu_times() #get - cputime=psutil.cpu_times() - d_procTimes.update({proc.pid:proctime}) - d_cpuTimes.update({proc.pid:cputime}) - except: - #case we skip a process - pass - self.ui.d_cpuTimes=d_cpuTimes - self.ui.d_procTimes=d_procTimes - d_cpuTimes={} - d_procTimes={} - - updateInterval=float(self.update) #timer interval in seconds - for proc in psutil.process_iter(): - #try: - if psutil.Process(proc.pid).is_running(): - #if proc.pid == 37196: - #check if process still exists, if so, update dictionaries - try: - #check if process previously existed - if so we can calculate a cpupct - proctimeHold=self.ui.d_procTimes[proc.pid] - proctime=proc.get_cpu_times() #get - deltaProcTime=(proctime.user+proctime.system) - (proctimeHold.user+proctimeHold.system) - - cputimeHold=self.ui.d_cpuTimes[proc.pid] - cputime=psutil.cpu_times() - deltaCPUTime=(cputime.user+cputime.system+cputime.idle) - (cputimeHold.user+cputimeHold.system+cputimeHold.idle) - - if deltaProcTime > 0: - if deltaCPUTime < updateInterval: - deltaCPUTime=updateInterval - else: - pass - cpupct=float(deltaProcTime)/float(deltaCPUTime)*100.0 - - else: - cpupct=0 - - if cpupct < 0: - cpupct=0 - - cpupct=float(int(float(cpupct)*100))/100 #only keep two decimal places - memVal=float(int(float(proc.get_memory_percent())*100.0))/100.0 if config.psutilVer == 1 else float(int(float(proc.memory_percent())*100.0))/100.0 - - try: - #don't update dictionaries if name gives an access denied error when checking process name - #print "Updating" - pname=proc.name if config.psutilVer == 1 else proc.name() - d_user.update({proc.pid:proc.username}) if config.psutilVer == 1 else d_user.update({proc.pid:proc.username()}) - d_cpu.update({proc.pid:cpupct}) - d_mem.update({proc.pid:memVal}) - d_name.update({proc.pid:pname}) - d_cpuTimes.update({proc.pid:cputime}) - d_procTimes.update({proc.pid:proctime}) - - except: - #print "psutil General Error: ",sys.exc_info()[0] - pass - - except: - #else process did not previously exist and we cannot give an update this iteration - #print "except - pid: ",proc.pid - - pass - - - #once the dictionarys are updated, update cpu times for next loop - self.ui.d_cpuTimes=d_cpuTimes - self.ui.d_procTimes=d_procTimes - - #now fill the table for display - for proc in d_user.keys(): - #print "proc: ",proc," type: ",type(proc) - pid=int(proc) - #print "pid: ",pid - - table.insertRow(0) - #print "inserting row" - #set process id - item=QtGui.QTableWidgetItem() - item.setData(QtCore.Qt.DisplayRole,pid) - table.setItem(0,0,item) - #set username - #print " d_user[proc]: ",d_user[proc]," proc: ",proc - table.setItem(0,1,QtGui.QTableWidgetItem(d_user[proc])) - #set CPU % - item=QtGui.QTableWidgetItem() - item.setData(QtCore.Qt.DisplayRole,d_cpu[proc]) - table.setItem(0,2,item) - #set memory % - item=QtGui.QTableWidgetItem() - item.setData(QtCore.Qt.DisplayRole,d_mem[proc]) - table.setItem(0,3,item) - #set process name - table.setItem(0,4,QtGui.QTableWidgetItem(d_name[proc])) - row+=1 - - - # for row in range(rout): - # table.removeRow(Npids-row) - #restore sort to previously selected column - #table.sortItems(column_sorted,order=QtCore.Qt.AscendingOrder) - table.sortItems(column_sorted,order=order) - self.ui.labelLastUpdate.setText("Last Update: "+str(datetime.datetime.now())) - -def updateUserChart(self,config): - - font = {'family' : 'sans-serif', - 'weight' : 'bold', - 'size' : config.pltFont} - - matplotlib.rc('font', **font) - - f=plt.figure(self.ui.figure2.number) - -# self.ui.figure2=plt.figure(2) - plt.clf() - plt.cla() -# f.gca().cla() - plt.subplot(121) #divide plot area into two: plot on left and legend on right - #create empty dictionaries to be used by the process table - d_user={} - d_cpu={} - d_mem={} - d_name={} - d_cpuTimes={} - d_procTimes={} - - try: - #check if this dictionary exists or not - self.ui.d_procTimes - self.ui.d_cpuTimes - #if so, move on - pass - except: - #case to initialize the dictionary - for proc in psutil.process_iter(): - try: - #check if acess denied - pname=proc.name - proctime=proc.get_cpu_times() #get - cputime=psutil.cpu_times() - d_procTimes.update({proc.pid:proctime}) - d_cpuTimes.update({proc.pid:cputime}) - except: - #case we skip a process - pass - self.ui.d_cpuTimes=d_cpuTimes - self.ui.d_procTimes=d_procTimes - d_cpuTimes={} - d_procTimes={} - - updateInterval=float(self.update) #timer interval in seconds - totcpupct=0 - for proc in psutil.process_iter(): - try: - psutil.Process(proc.pid).is_running() - #if proc.pid == 37196: - #check if process still exists, if so, update dictionaries - try: - #check if process previously existed - if so we can calculate a cpupct - proctimeHold=self.ui.d_procTimes[proc.pid] - proctime=proc.get_cpu_times() #get - deltaProcTime=(proctime.user+proctime.system) - (proctimeHold.user+proctimeHold.system) - - cputimeHold=self.ui.d_cpuTimes[proc.pid] - cputime=psutil.cpu_times() - deltaCPUTime=(cputime.user+cputime.system+cputime.idle) - (cputimeHold.user+cputimeHold.system+cputimeHold.idle) - - if deltaProcTime > 0: - if deltaCPUTime < updateInterval: - deltaCPUTime=updateInterval - else: - pass - cpupct=float(deltaProcTime)/float(deltaCPUTime)*100.0 - - else: - cpupct=0 - - if cpupct < 0: - cpupct=0 - - cpupct=float(int(float(cpupct)*100))/100 #only keep two decimal places - totcpupct+=cpupct - memVal=float(int(float(proc.get_memory_percent())*100.0))/100.0 if config.psutilVer == 1 else float(int(float(proc.memory_percent())*100.0))/100.0 - - try: - #don't update dictionaries if name gives an access denied error when checking process name - #print "Updating" - pname=proc.name if config.psutilVer == 1 else proc.name() - d_user.update({proc.pid:proc.username}) if config.psutilVer == 1 else d_user.update({proc.pid:proc.username()}) - #System Idle process should not be listed in users cpu totals so set it to zero - if pname =="System Idle Process": - cpupct=0 - d_cpu.update({proc.pid:cpupct}) - d_mem.update({proc.pid:memVal}) - d_name.update({proc.pid:pname}) - d_cpuTimes.update({proc.pid:cputime}) - d_procTimes.update({proc.pid:proctime}) - - except: - #print "psutil General Error: ",sys.exc_info()[0] - pass - - except: - #else process did not previously exist and we cannot give an update this iteration - #print "except - pid: ",proc.pid - - pass - except: - #process no longer exists - do nothing - pass - - - self.ui.d_cpuTimes=d_cpuTimes - self.ui.d_procTimes=d_procTimes - - #print "** Total Mem Used: ",sum(d_mem.values()) - users=d_user.values() - users_unique=list(set(users)) #use set() to find unique users then convert the resulting set to a list via list() - Nusers=len(users_unique) - - #create cpu and memory by users dictionaries - cpu_by_users={} - mem_by_users={} - for u in range(Nusers): - cpu_by_users.update({users_unique[u]:0}) - mem_by_users.update({users_unique[u]:0}) - #apparently update does not order keys in sequence to users_unique - #thus need to re-create users_unique according to the order of the users - #in the cpu and mem dictionary keys - users_unique=list(cpu_by_users.keys()) - - #fill cpu and memory dictionaries sequencing thru each PID - for pid in d_user.keys(): - user=d_user[pid] - cpu_by_users[user]=cpu_by_users[user] + d_cpu[pid] - mem_by_users[user]=mem_by_users[user] + d_mem[pid] - #print d_cpu[35296],d_cpu[37196],d_cpu[35296]+d_cpu[37196] - #now convert to a list which we can index - cpu_by_users_lst=cpu_by_users.values() - mem_by_users_lst=mem_by_users.values() - - width=0.85 - - colors=['b','g','r','c','m','y','gray','hotpink','brown','k'] - Nmax=len(colors) #don't want to have more users than colors... - - if self.ui.radioButtonCPU.isChecked(): - sortBy='cpu' - elif self.ui.radioButtonMem.isChecked(): - sortBy='mem' - elif self.ui.radioButtonMax.isChecked(): - sortBy='max' - else: - print "invalid radio button selection - using CPU sort as default" - sortBy='cpu' - #sortBy='cpu' # 'cpu' or 'mem' - use for debugging - #create sort index - if sortBy=='cpu': - indx=sorted(range(len(cpu_by_users_lst)), key=cpu_by_users_lst.__getitem__,reverse=True) - elif sortBy=='mem': - indx=sorted(range(len(mem_by_users_lst)), key=mem_by_users_lst.__getitem__,reverse=True) - elif sortBy=='max': - #determine if cpu or mem is larger - if sum(cpu_by_users_lst) > sum(mem_by_users_lst): - #case where cpu usage is larger value - indx=sorted(range(len(cpu_by_users_lst)), key=cpu_by_users_lst.__getitem__,reverse=True) - else: - #case where mem usage is larger - indx=sorted(range(len(mem_by_users_lst)), key=mem_by_users_lst.__getitem__,reverse=True) - else: - print 'Incorrect sort parameter' - - #sort lists - cpu_by_users_sorted=[cpu_by_users_lst[x] for x in indx] - mem_by_users_sorted=[mem_by_users_lst[x] for x in indx] - users_unique_sorted=[users_unique[x] for x in indx] - - #restrict the number of users we'll show to Nmax - if Nusers > Nmax: - #replace the Nmaxth - 1 element with the total of the values from index Nmax - 1 to the end of the list - cpu_by_users_sorted[Nmax-1]=sum(cpu_by_users_sorted[Nmax-1:]) - mem_by_users_sorted[Nmax-1]=sum(mem_by_users_sorted[Nmax-1:]) - users_unique_sorted[Nmax-1]='Remaining' - Nshow=Nmax - else: - Nshow=Nusers - - if min(cpu_by_users_sorted) < 0: - print " *** cpu_by_users_sorted has values less than zero - should not occur, please check" - print cpu_by_users_sorted - print " ***" - if min(mem_by_users_sorted) < 0: - print " *** mem_by_users_sorted has values less than zero - should not occur, please check" - print mem_by_users_sorted - print " ***" - - #range check the values of the sorted lists - may not be necessary, just being cautious... - tst=np.array(cpu_by_users_sorted)<0 #need an array for summing - indx=list(np.array(cpu_by_users_sorted)<0) #need bool list for indexing - #check if any users have less than zero CPU usage and set usage to 0 for these users - if sum(tst) > 0: - print "cpu_by_users < 0: ",sum(indx) - cpu_by_users_sorted=[0 if x<0 else x for x in cpu_by_users_sorted] - tst=np.array(cpu_by_users_sorted)>(self.ui.Ncpus*100) - indx=list(np.array(cpu_by_users_sorted)>self.ui.Ncpus*100) - #check if any users have CPU usage greater than possible number of CPUs and set usage to max CPU usage for those users - if sum(tst) > 0: - print "cpu_by_users > Ncpus*100: ",sum(indx) - cpu_by_users_sorted=[self.ui.Ncpus*100 if x>self.ui.Ncpus*100 else x for x in cpu_by_users_sorted] - tst=np.array(mem_by_users_sorted)<0 - indx=list(np.array(mem_by_users_sorted)<0) - #check if any users have less than zero memory usage and set these users to zero usage - if sum(tst) > 0: - print "mem_by_users < 0: ",sum(indx) - mem_by_users_sorted=[0 if x<0 else x for x in mem_by_users_sorted] - tst=np.array(mem_by_users_sorted)>self.ui.totalmem - indx=np.array(mem_by_users_sorted)>self.ui.totalmem - #check if any users have memory usage greater than the total system memory - should never happen... - if sum(tst) > 0: - #if true, then need to adjust maximum usage for these users to the total memory possible - #print "mem_by_users > totalmem: ",sum(indx)," indx: ",indx," mem_by_users: ",mem_by_users_sorted - mem_by_users_sorted=[self.ui.totalmem if x>self.ui.totalmem else x for x in mem_by_users_sorted] - - - p=[] #list to contain plot objects for use by the legend - ind=np.arange(2) - #print "**************" - #print mem_by_users_sorted[0:Nshow] - for u in range(Nshow): - if u == 0: - p.append(plt.bar(ind,(cpu_by_users_sorted[u],mem_by_users_sorted[u]),width,bottom=(0,0),color=colors[u])) - else: - p.append(plt.bar(ind,(cpu_by_users_sorted[u],mem_by_users_sorted[u]),width,bottom=(sum(cpu_by_users_sorted[0:u]),sum(mem_by_users_sorted[0:u])),color=colors[u])) - - plt.title('Usage by User',fontsize=config.pltFont+1,fontweight='bold') - - #remove default yaxis ticks then redraw them via ax1 and ax2 below - frame=plt.gca() - frame.axes.get_yaxis().set_ticks([]) - plt.xticks(np.arange(2)+width/2.,('CPU','Mem'),fontsize=config.pltFont,fontweight='bold') - ymaxCPU=int(round(sum(cpu_by_users_sorted)+10))/10*10 #range ymaxCPU to nearest 10% - ymaxMEM=int(round(sum(mem_by_users_sorted)+10))/10*10 #range ymaxMEM to nearest 10% - - ymaxMAX=max([ymaxCPU,ymaxMEM]) - - if sortBy == 'cpu': - ymax=max([ymaxCPU,10]) - auto=False - elif sortBy == 'mem': - ymax=max([ymaxMEM,10]) - auto=False - elif sortBy == 'max': - ymax=max([ymaxMAX,10]) - auto=True - #print 'ymaxCPU: ',ymaxCPU,' ymaxMEM: ',ymaxMEM,' ymaxMAX: ',ymaxMAX,' ymax: ',ymax - #print 'sum(cpu_by_users_sorted): ',sum(cpu_by_users_sorted),'sum(mem_by_users_sorted): ',sum(mem_by_users_sorted) - #print cpu_by_users - plt.ylim(0,ymax,auto=True) - - - - #compute composite % - sumCPU=sum(cpu_by_users_sorted) - sumCPU=float(int(sumCPU*100))/100 #use two digits - ylab=np.arange(5)/4.0*float(sumCPU)#/float(self.ui.Ncpus) - scl=float(ymax)/float(sumCPU) - ylab=ylab*100*scl - tmp=ylab.astype('int') - tmp1=tmp.astype('float') - tmp1=tmp1/100 - ylab1=np.round(tmp1) - - ax1=plt.twinx() - ax1.set_ylabel('Composite CPU Percent',fontsize=config.pltFont,fontweight='bold') - ax1.yaxis.set_ticks_position('left') - ax1.yaxis.set_label_position('left') - ax1.set_ybound(lower=0,upper=max(ylab1)) - ax1.set_yticks(ylab1) - -# print 'ylab1: ',ylab1 - - #place warnings if MEM or CPU go out of range - if ymax < ymaxCPU: - plt.text(2.7,0.0,'CPU Above Axis',color='red') - if ymax < ymaxMEM: - plt.text(2.7,0.0,'MEM Above Axis',color='green') - - usersLegend=users_unique_sorted[0:Nshow] - #reverse legend print order to have legend correspond with the order data are placed in the bar chart - usersLegend.reverse() - p.reverse() - #place legend outside of plot to the right - if not re.match('1.[0-1]',matplotlib.__version__): - #if not an old version of matplotlib, then use the following command - plt.legend(p,usersLegend,bbox_to_anchor=(1.45, 1.1), loc="upper left", borderaxespad=0.1,fontsize=config.pltFont-0.5,title='Users') - else: - plt.legend(p,usersLegend,bbox_to_anchor=(1.45, 1.1), loc="upper left", borderaxespad=0.1,title='Users') - - #place second y axis label on plot - ylab2=np.arange(5)/4.0*float(ymax) - ax2=plt.twinx() - ax2.set_ylabel('Memory Percent',fontsize=config.pltFont,fontweight='bold',position=(0.9,0.5)) - ax2.set_yticks(ylab2) - #ax2.set_yticks(ylab2) - ax2.yaxis.set_ticks_position('right') - ax2.yaxis.set_label_position('right') - - self.ui.canvas2.draw() - -def reLayout(self): - tmpWidget=QtGui.QWidget() - tmpWidget.setLayout(self.ui.layout2) - tmpLayout = QtGui.QVBoxLayout(self.ui.frameBar) \ No newline at end of file diff --git a/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py deleted file mode 100644 index 351c80dd4287..000000000000 --- a/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py +++ /dev/null @@ -1,390 +0,0 @@ -# -*- coding: utf-8 -*- - -# Form implementation generated from reading ui file 'ui_sysmon.ui' -# -# Created: Fri Dec 05 09:55:29 2014 -# by: PyQt4 UI code generator 4.8.3 -# -# WARNING! All changes made in this file will be lost! - -from PyQt4 import QtCore, QtGui - -try: - _fromUtf8 = QtCore.QString.fromUtf8 -except AttributeError: - _fromUtf8 = lambda s: s - -class Ui_Form(object): - def setupUi(self, Form): - Form.setObjectName(_fromUtf8("Form")) - Form.resize(230, 331) - Form.setMinimumSize(QtCore.QSize(230, 331)) - Form.setMaximumSize(QtCore.QSize(16777215, 16777215)) - self.horizontalLayout = QtGui.QHBoxLayout(Form) - self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) - self.tabWidget = QtGui.QTabWidget(Form) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth()) - self.tabWidget.setSizePolicy(sizePolicy) - self.tabWidget.setObjectName(_fromUtf8("tabWidget")) - self.tab = QtGui.QWidget() - self.tab.setObjectName(_fromUtf8("tab")) - self.verticalLayout = QtGui.QVBoxLayout(self.tab) - self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) - self.scrollArea = QtGui.QScrollArea(self.tab) - self.scrollArea.setWidgetResizable(True) - self.scrollArea.setObjectName(_fromUtf8("scrollArea")) - self.scrollAreaWidgetContents = QtGui.QWidget() - self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 179, 267)) - self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents")) - self.verticalLayout_2 = QtGui.QVBoxLayout(self.scrollAreaWidgetContents) - self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) - self.groupBox_3 = QtGui.QGroupBox(self.scrollAreaWidgetContents) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().hasHeightForWidth()) - self.groupBox_3.setSizePolicy(sizePolicy) - self.groupBox_3.setMinimumSize(QtCore.QSize(0, 0)) - self.groupBox_3.setObjectName(_fromUtf8("groupBox_3")) - self.gridLayout_4 = QtGui.QGridLayout(self.groupBox_3) - self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4")) - self.gridLayout_7 = QtGui.QGridLayout() - self.gridLayout_7.setObjectName(_fromUtf8("gridLayout_7")) - self.labelComputerName = QtGui.QLabel(self.groupBox_3) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.labelComputerName.sizePolicy().hasHeightForWidth()) - self.labelComputerName.setSizePolicy(sizePolicy) - self.labelComputerName.setMinimumSize(QtCore.QSize(0, 0)) - self.labelComputerName.setObjectName(_fromUtf8("labelComputerName")) - self.gridLayout_7.addWidget(self.labelComputerName, 0, 0, 1, 1) - self.labelOS = QtGui.QLabel(self.groupBox_3) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.labelOS.sizePolicy().hasHeightForWidth()) - self.labelOS.setSizePolicy(sizePolicy) - self.labelOS.setMinimumSize(QtCore.QSize(0, 0)) - self.labelOS.setObjectName(_fromUtf8("labelOS")) - self.gridLayout_7.addWidget(self.labelOS, 1, 0, 1, 1) - self.labelProcFam = QtGui.QLabel(self.groupBox_3) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.labelProcFam.sizePolicy().hasHeightForWidth()) - self.labelProcFam.setSizePolicy(sizePolicy) - self.labelProcFam.setMinimumSize(QtCore.QSize(0, 0)) - self.labelProcFam.setObjectName(_fromUtf8("labelProcFam")) - self.gridLayout_7.addWidget(self.labelProcFam, 2, 0, 1, 1) - self.labelNUsers = QtGui.QLabel(self.groupBox_3) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.labelNUsers.sizePolicy().hasHeightForWidth()) - self.labelNUsers.setSizePolicy(sizePolicy) - self.labelNUsers.setMinimumSize(QtCore.QSize(0, 0)) - self.labelNUsers.setObjectName(_fromUtf8("labelNUsers")) - self.gridLayout_7.addWidget(self.labelNUsers, 3, 0, 1, 1) - self.labelUptime = QtGui.QLabel(self.groupBox_3) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.labelUptime.sizePolicy().hasHeightForWidth()) - self.labelUptime.setSizePolicy(sizePolicy) - self.labelUptime.setMinimumSize(QtCore.QSize(0, 0)) - self.labelUptime.setObjectName(_fromUtf8("labelUptime")) - self.gridLayout_7.addWidget(self.labelUptime, 4, 0, 1, 1) - self.gridLayout_4.addLayout(self.gridLayout_7, 0, 0, 1, 1) - self.groupBox_5 = QtGui.QGroupBox(self.groupBox_3) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.groupBox_5.sizePolicy().hasHeightForWidth()) - self.groupBox_5.setSizePolicy(sizePolicy) - self.groupBox_5.setMinimumSize(QtCore.QSize(0, 0)) - font = QtGui.QFont() - font.setWeight(50) - font.setUnderline(False) - font.setBold(False) - self.groupBox_5.setFont(font) - self.groupBox_5.setObjectName(_fromUtf8("groupBox_5")) - self.verticalLayout_7 = QtGui.QVBoxLayout(self.groupBox_5) - self.verticalLayout_7.setObjectName(_fromUtf8("verticalLayout_7")) - self.labelMemUsage = QtGui.QLabel(self.groupBox_5) - font = QtGui.QFont() - font.setUnderline(False) - self.labelMemUsage.setFont(font) - self.labelMemUsage.setObjectName(_fromUtf8("labelMemUsage")) - self.verticalLayout_7.addWidget(self.labelMemUsage) - self.progressBarStatusMemory = QtGui.QProgressBar(self.groupBox_5) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Fixed) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.progressBarStatusMemory.sizePolicy().hasHeightForWidth()) - self.progressBarStatusMemory.setSizePolicy(sizePolicy) - self.progressBarStatusMemory.setMaximumSize(QtCore.QSize(210, 16777215)) - self.progressBarStatusMemory.setToolTip(_fromUtf8("")) - self.progressBarStatusMemory.setObjectName(_fromUtf8("progressBarStatusMemory")) - self.verticalLayout_7.addWidget(self.progressBarStatusMemory) - self.labelCPUCount = QtGui.QLabel(self.groupBox_5) - self.labelCPUCount.setObjectName(_fromUtf8("labelCPUCount")) - self.verticalLayout_7.addWidget(self.labelCPUCount) - self.progressBarStatusCPU = QtGui.QProgressBar(self.groupBox_5) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Fixed) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.progressBarStatusCPU.sizePolicy().hasHeightForWidth()) - self.progressBarStatusCPU.setSizePolicy(sizePolicy) - self.progressBarStatusCPU.setMaximumSize(QtCore.QSize(210, 16777215)) - self.progressBarStatusCPU.setToolTip(_fromUtf8("")) - self.progressBarStatusCPU.setStatusTip(_fromUtf8("")) - self.progressBarStatusCPU.setProperty(_fromUtf8("value"), 24) - self.progressBarStatusCPU.setObjectName(_fromUtf8("progressBarStatusCPU")) - self.verticalLayout_7.addWidget(self.progressBarStatusCPU) - self.gridLayout_4.addWidget(self.groupBox_5, 1, 0, 1, 1) - self.verticalLayout_2.addWidget(self.groupBox_3) - self.scrollArea.setWidget(self.scrollAreaWidgetContents) - self.verticalLayout.addWidget(self.scrollArea) - self.tabWidget.addTab(self.tab, _fromUtf8("")) - self.tab_2 = QtGui.QWidget() - self.tab_2.setObjectName(_fromUtf8("tab_2")) - self.horizontalLayout_2 = QtGui.QHBoxLayout(self.tab_2) - self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) - self.framePlot = QtGui.QFrame(self.tab_2) - self.framePlot.setFrameShape(QtGui.QFrame.StyledPanel) - self.framePlot.setFrameShadow(QtGui.QFrame.Raised) - self.framePlot.setObjectName(_fromUtf8("framePlot")) - self.horizontalLayout_2.addWidget(self.framePlot) - self.tabWidget.addTab(self.tab_2, _fromUtf8("")) - self.tab_3 = QtGui.QWidget() - self.tab_3.setObjectName(_fromUtf8("tab_3")) - self.verticalLayout_3 = QtGui.QVBoxLayout(self.tab_3) - self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3")) - self.horizontalLayout_3 = QtGui.QHBoxLayout() - self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3")) - self.labelLastUpdate = QtGui.QLabel(self.tab_3) - self.labelLastUpdate.setMinimumSize(QtCore.QSize(0, 0)) - self.labelLastUpdate.setMaximumSize(QtCore.QSize(300, 16777215)) - self.labelLastUpdate.setObjectName(_fromUtf8("labelLastUpdate")) - self.horizontalLayout_3.addWidget(self.labelLastUpdate) - self.verticalLayout_3.addLayout(self.horizontalLayout_3) - self.tableWidgetProcess = QtGui.QTableWidget(self.tab_3) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) - sizePolicy.setHorizontalStretch(100) - sizePolicy.setVerticalStretch(100) - sizePolicy.setHeightForWidth(self.tableWidgetProcess.sizePolicy().hasHeightForWidth()) - self.tableWidgetProcess.setSizePolicy(sizePolicy) - self.tableWidgetProcess.setMinimumSize(QtCore.QSize(0, 0)) - self.tableWidgetProcess.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) - self.tableWidgetProcess.setRowCount(10) - self.tableWidgetProcess.setColumnCount(5) - self.tableWidgetProcess.setObjectName(_fromUtf8("tableWidgetProcess")) - self.tableWidgetProcess.setColumnCount(5) - self.tableWidgetProcess.setRowCount(10) - item = QtGui.QTableWidgetItem() - self.tableWidgetProcess.setHorizontalHeaderItem(0, item) - item = QtGui.QTableWidgetItem() - self.tableWidgetProcess.setHorizontalHeaderItem(1, item) - item = QtGui.QTableWidgetItem() - self.tableWidgetProcess.setHorizontalHeaderItem(2, item) - item = QtGui.QTableWidgetItem() - self.tableWidgetProcess.setHorizontalHeaderItem(3, item) - item = QtGui.QTableWidgetItem() - self.tableWidgetProcess.setHorizontalHeaderItem(4, item) - self.tableWidgetProcess.horizontalHeader().setDefaultSectionSize(57) - self.tableWidgetProcess.horizontalHeader().setSortIndicatorShown(True) - self.tableWidgetProcess.horizontalHeader().setStretchLastSection(True) - self.tableWidgetProcess.verticalHeader().setVisible(False) - self.tableWidgetProcess.verticalHeader().setDefaultSectionSize(20) - self.tableWidgetProcess.verticalHeader().setStretchLastSection(True) - self.verticalLayout_3.addWidget(self.tableWidgetProcess) - self.horizontalLayout_7 = QtGui.QHBoxLayout() - self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7")) - spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) - self.horizontalLayout_7.addItem(spacerItem) - self.pushButtonUpdate = QtGui.QPushButton(self.tab_3) - self.pushButtonUpdate.setMinimumSize(QtCore.QSize(0, 0)) - self.pushButtonUpdate.setMaximumSize(QtCore.QSize(80, 15)) - font = QtGui.QFont() - font.setPointSize(7) - self.pushButtonUpdate.setFont(font) - self.pushButtonUpdate.setObjectName(_fromUtf8("pushButtonUpdate")) - self.horizontalLayout_7.addWidget(self.pushButtonUpdate) - self.verticalLayout_3.addLayout(self.horizontalLayout_7) - self.tabWidget.addTab(self.tab_3, _fromUtf8("")) - self.tab_5 = QtGui.QWidget() - self.tab_5.setObjectName(_fromUtf8("tab_5")) - self.verticalLayout_6 = QtGui.QVBoxLayout(self.tab_5) - self.verticalLayout_6.setObjectName(_fromUtf8("verticalLayout_6")) - self.groupBox = QtGui.QGroupBox(self.tab_5) - self.groupBox.setObjectName(_fromUtf8("groupBox")) - self.horizontalLayout_6 = QtGui.QHBoxLayout(self.groupBox) - self.horizontalLayout_6.setContentsMargins(-1, 3, -1, 2) - self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6")) - self.radioButtonCPU = QtGui.QRadioButton(self.groupBox) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.radioButtonCPU.sizePolicy().hasHeightForWidth()) - self.radioButtonCPU.setSizePolicy(sizePolicy) - self.radioButtonCPU.setMinimumSize(QtCore.QSize(0, 0)) - self.radioButtonCPU.setObjectName(_fromUtf8("radioButtonCPU")) - self.horizontalLayout_6.addWidget(self.radioButtonCPU) - self.radioButtonMem = QtGui.QRadioButton(self.groupBox) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.radioButtonMem.sizePolicy().hasHeightForWidth()) - self.radioButtonMem.setSizePolicy(sizePolicy) - self.radioButtonMem.setMinimumSize(QtCore.QSize(0, 0)) - self.radioButtonMem.setChecked(False) - self.radioButtonMem.setObjectName(_fromUtf8("radioButtonMem")) - self.horizontalLayout_6.addWidget(self.radioButtonMem) - self.radioButtonMax = QtGui.QRadioButton(self.groupBox) - self.radioButtonMax.setChecked(True) - self.radioButtonMax.setObjectName(_fromUtf8("radioButtonMax")) - self.horizontalLayout_6.addWidget(self.radioButtonMax) - self.verticalLayout_6.addWidget(self.groupBox) - self.frameBar = QtGui.QFrame(self.tab_5) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Expanding) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.frameBar.sizePolicy().hasHeightForWidth()) - self.frameBar.setSizePolicy(sizePolicy) - self.frameBar.setFrameShape(QtGui.QFrame.StyledPanel) - self.frameBar.setFrameShadow(QtGui.QFrame.Raised) - self.frameBar.setObjectName(_fromUtf8("frameBar")) - self.verticalLayout_6.addWidget(self.frameBar) - self.tabWidget.addTab(self.tab_5, _fromUtf8("")) - self.tab_4 = QtGui.QWidget() - self.tab_4.setObjectName(_fromUtf8("tab_4")) - self.horizontalLayout_4 = QtGui.QHBoxLayout(self.tab_4) - self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4")) - self.scrollArea_2 = QtGui.QScrollArea(self.tab_4) - self.scrollArea_2.setWidgetResizable(True) - self.scrollArea_2.setObjectName(_fromUtf8("scrollArea_2")) - self.scrollAreaWidgetContents_2 = QtGui.QWidget() - self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 238, 250)) - self.scrollAreaWidgetContents_2.setObjectName(_fromUtf8("scrollAreaWidgetContents_2")) - self.horizontalLayout_5 = QtGui.QHBoxLayout(self.scrollAreaWidgetContents_2) - self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5")) - self.groupBox_6 = QtGui.QGroupBox(self.scrollAreaWidgetContents_2) - self.groupBox_6.setMinimumSize(QtCore.QSize(0, 0)) - self.groupBox_6.setObjectName(_fromUtf8("groupBox_6")) - self.verticalLayout_5 = QtGui.QVBoxLayout(self.groupBox_6) - self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5")) - self.radioButton60Secs = QtGui.QRadioButton(self.groupBox_6) - self.radioButton60Secs.setChecked(True) - self.radioButton60Secs.setObjectName(_fromUtf8("radioButton60Secs")) - self.verticalLayout_5.addWidget(self.radioButton60Secs) - self.radioButton300Secs = QtGui.QRadioButton(self.groupBox_6) - self.radioButton300Secs.setObjectName(_fromUtf8("radioButton300Secs")) - self.verticalLayout_5.addWidget(self.radioButton300Secs) - self.radioButton600Secs = QtGui.QRadioButton(self.groupBox_6) - self.radioButton600Secs.setObjectName(_fromUtf8("radioButton600Secs")) - self.verticalLayout_5.addWidget(self.radioButton600Secs) - self.radioButton3600Secs = QtGui.QRadioButton(self.groupBox_6) - self.radioButton3600Secs.setObjectName(_fromUtf8("radioButton3600Secs")) - self.verticalLayout_5.addWidget(self.radioButton3600Secs) - self.line = QtGui.QFrame(self.groupBox_6) - self.line.setFrameShape(QtGui.QFrame.HLine) - self.line.setFrameShadow(QtGui.QFrame.Sunken) - self.line.setObjectName(_fromUtf8("line")) - self.verticalLayout_5.addWidget(self.line) - self.label = QtGui.QLabel(self.groupBox_6) - self.label.setObjectName(_fromUtf8("label")) - self.verticalLayout_5.addWidget(self.label) - self.comboBoxCPUHistSmooth = QtGui.QComboBox(self.groupBox_6) - self.comboBoxCPUHistSmooth.setObjectName(_fromUtf8("comboBoxCPUHistSmooth")) - self.comboBoxCPUHistSmooth.addItem(_fromUtf8("")) - self.comboBoxCPUHistSmooth.addItem(_fromUtf8("")) - self.comboBoxCPUHistSmooth.addItem(_fromUtf8("")) - self.comboBoxCPUHistSmooth.addItem(_fromUtf8("")) - self.comboBoxCPUHistSmooth.addItem(_fromUtf8("")) - self.verticalLayout_5.addWidget(self.comboBoxCPUHistSmooth) - spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) - self.verticalLayout_5.addItem(spacerItem1) - self.labelVersion = QtGui.QLabel(self.groupBox_6) - self.labelVersion.setObjectName(_fromUtf8("labelVersion")) - self.verticalLayout_5.addWidget(self.labelVersion) - self.horizontalLayout_5.addWidget(self.groupBox_6) - self.groupBox_4 = QtGui.QGroupBox(self.scrollAreaWidgetContents_2) - self.groupBox_4.setMinimumSize(QtCore.QSize(0, 0)) - self.groupBox_4.setObjectName(_fromUtf8("groupBox_4")) - self.verticalLayout_4 = QtGui.QVBoxLayout(self.groupBox_4) - self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4")) - self.radioButton1Sec = QtGui.QRadioButton(self.groupBox_4) - self.radioButton1Sec.setObjectName(_fromUtf8("radioButton1Sec")) - self.verticalLayout_4.addWidget(self.radioButton1Sec) - self.radioButton2Secs = QtGui.QRadioButton(self.groupBox_4) - self.radioButton2Secs.setChecked(True) - self.radioButton2Secs.setObjectName(_fromUtf8("radioButton2Secs")) - self.verticalLayout_4.addWidget(self.radioButton2Secs) - self.radioButton5Secs = QtGui.QRadioButton(self.groupBox_4) - self.radioButton5Secs.setObjectName(_fromUtf8("radioButton5Secs")) - self.verticalLayout_4.addWidget(self.radioButton5Secs) - self.radioButton10Secs = QtGui.QRadioButton(self.groupBox_4) - self.radioButton10Secs.setObjectName(_fromUtf8("radioButton10Secs")) - self.verticalLayout_4.addWidget(self.radioButton10Secs) - spacerItem2 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) - self.verticalLayout_4.addItem(spacerItem2) - self.horizontalLayout_5.addWidget(self.groupBox_4) - self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2) - self.horizontalLayout_4.addWidget(self.scrollArea_2) - self.tabWidget.addTab(self.tab_4, _fromUtf8("")) - self.horizontalLayout.addWidget(self.tabWidget) - - self.retranslateUi(Form) - self.tabWidget.setCurrentIndex(0) - QtCore.QMetaObject.connectSlotsByName(Form) - - def retranslateUi(self, Form): - Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8)) - self.groupBox_3.setTitle(QtGui.QApplication.translate("Form", "System Info", None, QtGui.QApplication.UnicodeUTF8)) - self.labelComputerName.setText(QtGui.QApplication.translate("Form", "Computer Name: ", None, QtGui.QApplication.UnicodeUTF8)) - self.labelOS.setText(QtGui.QApplication.translate("Form", "Operating System:", None, QtGui.QApplication.UnicodeUTF8)) - self.labelProcFam.setText(QtGui.QApplication.translate("Form", "Processor Family:", None, QtGui.QApplication.UnicodeUTF8)) - self.labelNUsers.setText(QtGui.QApplication.translate("Form", "Number of Users Logged On:", None, QtGui.QApplication.UnicodeUTF8)) - self.labelUptime.setText(QtGui.QApplication.translate("Form", "System Uptime: ", None, QtGui.QApplication.UnicodeUTF8)) - self.groupBox_5.setTitle(QtGui.QApplication.translate("Form", "Composite System Status", None, QtGui.QApplication.UnicodeUTF8)) - self.labelMemUsage.setText(QtGui.QApplication.translate("Form", "Memory Usage", None, QtGui.QApplication.UnicodeUTF8)) - self.labelCPUCount.setText(QtGui.QApplication.translate("Form", "CPU count:", None, QtGui.QApplication.UnicodeUTF8)) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtGui.QApplication.translate("Form", "System", None, QtGui.QApplication.UnicodeUTF8)) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), QtGui.QApplication.translate("Form", "History", None, QtGui.QApplication.UnicodeUTF8)) - self.labelLastUpdate.setText(QtGui.QApplication.translate("Form", "Last Update: ", None, QtGui.QApplication.UnicodeUTF8)) - self.tableWidgetProcess.setSortingEnabled(True) - self.tableWidgetProcess.horizontalHeaderItem(0).setText(QtGui.QApplication.translate("Form", "PID", None, QtGui.QApplication.UnicodeUTF8)) - self.tableWidgetProcess.horizontalHeaderItem(1).setText(QtGui.QApplication.translate("Form", "USER", None, QtGui.QApplication.UnicodeUTF8)) - self.tableWidgetProcess.horizontalHeaderItem(2).setText(QtGui.QApplication.translate("Form", "CPU%", None, QtGui.QApplication.UnicodeUTF8)) - self.tableWidgetProcess.horizontalHeaderItem(3).setText(QtGui.QApplication.translate("Form", "MEM%", None, QtGui.QApplication.UnicodeUTF8)) - self.tableWidgetProcess.horizontalHeaderItem(4).setText(QtGui.QApplication.translate("Form", "NAME", None, QtGui.QApplication.UnicodeUTF8)) - self.pushButtonUpdate.setText(QtGui.QApplication.translate("Form", "Hold Updates", None, QtGui.QApplication.UnicodeUTF8)) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), QtGui.QApplication.translate("Form", "Processes", None, QtGui.QApplication.UnicodeUTF8)) - self.groupBox.setTitle(QtGui.QApplication.translate("Form", "Sort", None, QtGui.QApplication.UnicodeUTF8)) - self.radioButtonCPU.setText(QtGui.QApplication.translate("Form", "CPU", None, QtGui.QApplication.UnicodeUTF8)) - self.radioButtonMem.setText(QtGui.QApplication.translate("Form", "Memory", None, QtGui.QApplication.UnicodeUTF8)) - self.radioButtonMax.setText(QtGui.QApplication.translate("Form", "Max", None, QtGui.QApplication.UnicodeUTF8)) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_5), QtGui.QApplication.translate("Form", "Users", None, QtGui.QApplication.UnicodeUTF8)) - self.groupBox_6.setTitle(QtGui.QApplication.translate("Form", "Display Period", None, QtGui.QApplication.UnicodeUTF8)) - self.radioButton60Secs.setText(QtGui.QApplication.translate("Form", "60 Seconds", None, QtGui.QApplication.UnicodeUTF8)) - self.radioButton300Secs.setText(QtGui.QApplication.translate("Form", "300 Seconds", None, QtGui.QApplication.UnicodeUTF8)) - self.radioButton600Secs.setText(QtGui.QApplication.translate("Form", "600 Seconds", None, QtGui.QApplication.UnicodeUTF8)) - self.radioButton3600Secs.setText(QtGui.QApplication.translate("Form", "3600 Seconds", None, QtGui.QApplication.UnicodeUTF8)) - self.label.setText(QtGui.QApplication.translate("Form", "CPU History Smooth", None, QtGui.QApplication.UnicodeUTF8)) - self.comboBoxCPUHistSmooth.setItemText(0, QtGui.QApplication.translate("Form", "1", None, QtGui.QApplication.UnicodeUTF8)) - self.comboBoxCPUHistSmooth.setItemText(1, QtGui.QApplication.translate("Form", "2", None, QtGui.QApplication.UnicodeUTF8)) - self.comboBoxCPUHistSmooth.setItemText(2, QtGui.QApplication.translate("Form", "5", None, QtGui.QApplication.UnicodeUTF8)) - self.comboBoxCPUHistSmooth.setItemText(3, QtGui.QApplication.translate("Form", "10", None, QtGui.QApplication.UnicodeUTF8)) - self.comboBoxCPUHistSmooth.setItemText(4, QtGui.QApplication.translate("Form", "15", None, QtGui.QApplication.UnicodeUTF8)) - self.labelVersion.setText(QtGui.QApplication.translate("Form", "Version: ", None, QtGui.QApplication.UnicodeUTF8)) - self.groupBox_4.setTitle(QtGui.QApplication.translate("Form", "Update Rate", None, QtGui.QApplication.UnicodeUTF8)) - self.radioButton1Sec.setText(QtGui.QApplication.translate("Form", "1 Second", None, QtGui.QApplication.UnicodeUTF8)) - self.radioButton2Secs.setText(QtGui.QApplication.translate("Form", "2 Seconds", None, QtGui.QApplication.UnicodeUTF8)) - self.radioButton5Secs.setText(QtGui.QApplication.translate("Form", "5 Seconds", None, QtGui.QApplication.UnicodeUTF8)) - self.radioButton10Secs.setText(QtGui.QApplication.translate("Form", "10 Seconds", None, QtGui.QApplication.UnicodeUTF8)) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), QtGui.QApplication.translate("Form", "Options", None, QtGui.QApplication.UnicodeUTF8)) - diff --git a/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui deleted file mode 100644 index 265c066807af..000000000000 --- a/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui +++ /dev/null @@ -1,735 +0,0 @@ - - - Form - - - - 0 - 0 - 230 - 331 - - - - - 230 - 331 - - - - - 16777215 - 16777215 - - - - Form - - - - - - - 0 - 0 - - - - 0 - - - - System - - - - - - true - - - - - 0 - 0 - 179 - 267 - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - System Info - - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - Computer Name: - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - Operating System: - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - Processor Family: - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - Number of Users Logged On: - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - System Uptime: - - - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 50 - false - false - - - - Composite System Status - - - - - - - false - - - - Memory Usage - - - - - - - - 0 - 0 - - - - - 210 - 16777215 - - - - - - - - - - - CPU count: - - - - - - - - 0 - 0 - - - - - 210 - 16777215 - - - - - - - - - - 24 - - - - - - - - - - - - - - - - - - History - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - - - Processes - - - - - - - - - 0 - 0 - - - - - 300 - 16777215 - - - - Last Update: - - - - - - - - - - 100 - 100 - - - - - 0 - 0 - - - - QAbstractItemView::NoEditTriggers - - - true - - - 10 - - - 5 - - - 57 - - - true - - - true - - - false - - - 20 - - - true - - - - - - - - - - - - - - PID - - - - - USER - - - - - CPU% - - - - - MEM% - - - - - NAME - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 80 - 15 - - - - - 7 - - - - Hold Updates - - - - - - - - - - Users - - - - - - Sort - - - - 3 - - - 2 - - - - - - 0 - 0 - - - - - 0 - 0 - - - - CPU - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - Memory - - - false - - - - - - - Max - - - true - - - - - - - - - - - 0 - 0 - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - - - Options - - - - - - true - - - - - 0 - 0 - 238 - 250 - - - - - - - - 0 - 0 - - - - Display Period - - - - - - 60 Seconds - - - true - - - - - - - 300 Seconds - - - - - - - 600 Seconds - - - - - - - 3600 Seconds - - - - - - - Qt::Horizontal - - - - - - - CPU History Smooth - - - - - - - - 1 - - - - - 2 - - - - - 5 - - - - - 10 - - - - - 15 - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Version: - - - - - - - - - - - 0 - 0 - - - - Update Rate - - - - - - 1 Second - - - - - - - 2 Seconds - - - true - - - - - - - 5 Seconds - - - - - - - 10 Seconds - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - - - - - - - - - diff --git a/Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.py b/Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.py deleted file mode 100644 index a7c6a67caaf2..000000000000 --- a/Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.py +++ /dev/null @@ -1,69 +0,0 @@ -# -*- coding: utf-8 -*- - -# Form implementation generated from reading ui file 'ui_sysmonMainWindow.ui' -# -# Created: Wed Sep 17 15:59:14 2014 -# by: PyQt4 UI code generator 4.8.3 -# -# WARNING! All changes made in this file will be lost! - -from PyQt4 import QtCore, QtGui - -try: - _fromUtf8 = QtCore.QString.fromUtf8 -except AttributeError: - _fromUtf8 = lambda s: s - -class Ui_MainWindow(object): - def setupUi(self, MainWindow): - MainWindow.setObjectName(_fromUtf8("MainWindow")) - MainWindow.resize(427, 323) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) - MainWindow.setSizePolicy(sizePolicy) - MainWindow.setMinimumSize(QtCore.QSize(336, 282)) - self.centralwidget = QtGui.QWidget(MainWindow) - self.centralwidget.setObjectName(_fromUtf8("centralwidget")) - self.gridLayout = QtGui.QGridLayout(self.centralwidget) - self.gridLayout.setObjectName(_fromUtf8("gridLayout")) - MainWindow.setCentralWidget(self.centralwidget) - self.statusbar = QtGui.QStatusBar(MainWindow) - self.statusbar.setObjectName(_fromUtf8("statusbar")) - MainWindow.setStatusBar(self.statusbar) - self.menubar = QtGui.QMenuBar(MainWindow) - self.menubar.setGeometry(QtCore.QRect(0, 0, 427, 21)) - self.menubar.setObjectName(_fromUtf8("menubar")) - self.menuFile = QtGui.QMenu(self.menubar) - self.menuFile.setObjectName(_fromUtf8("menuFile")) - self.menuHelp = QtGui.QMenu(self.menubar) - self.menuHelp.setObjectName(_fromUtf8("menuHelp")) - self.menuCustom = QtGui.QMenu(self.menubar) - self.menuCustom.setObjectName(_fromUtf8("menuCustom")) - MainWindow.setMenuBar(self.menubar) - self.actionExit = QtGui.QAction(MainWindow) - self.actionExit.setObjectName(_fromUtf8("actionExit")) - self.actionAbout = QtGui.QAction(MainWindow) - self.actionAbout.setObjectName(_fromUtf8("actionAbout")) - self.actionCheck_Matlab_Licenses = QtGui.QAction(MainWindow) - self.actionCheck_Matlab_Licenses.setObjectName(_fromUtf8("actionCheck_Matlab_Licenses")) - self.menuFile.addAction(self.actionExit) - self.menuHelp.addAction(self.actionAbout) - self.menuCustom.addAction(self.actionCheck_Matlab_Licenses) - self.menubar.addAction(self.menuFile.menuAction()) - self.menubar.addAction(self.menuHelp.menuAction()) - self.menubar.addAction(self.menuCustom.menuAction()) - - self.retranslateUi(MainWindow) - QtCore.QMetaObject.connectSlotsByName(MainWindow) - - def retranslateUi(self, MainWindow): - MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "System Monitor", None, QtGui.QApplication.UnicodeUTF8)) - self.menuFile.setTitle(QtGui.QApplication.translate("MainWindow", "File", None, QtGui.QApplication.UnicodeUTF8)) - self.menuHelp.setTitle(QtGui.QApplication.translate("MainWindow", "Help", None, QtGui.QApplication.UnicodeUTF8)) - self.menuCustom.setTitle(QtGui.QApplication.translate("MainWindow", "Custom", None, QtGui.QApplication.UnicodeUTF8)) - self.actionExit.setText(QtGui.QApplication.translate("MainWindow", "Exit", None, QtGui.QApplication.UnicodeUTF8)) - self.actionAbout.setText(QtGui.QApplication.translate("MainWindow", "About", None, QtGui.QApplication.UnicodeUTF8)) - self.actionCheck_Matlab_Licenses.setText(QtGui.QApplication.translate("MainWindow", "Check Matlab Licenses", None, QtGui.QApplication.UnicodeUTF8)) - diff --git a/Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.ui b/Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.ui deleted file mode 100644 index 75196f8911a9..000000000000 --- a/Code/Mantid/MantidPlot/SysMon/ui_sysmonMainWindow.ui +++ /dev/null @@ -1,81 +0,0 @@ - - - MainWindow - - - - 0 - 0 - 427 - 323 - - - - - 0 - 0 - - - - - 336 - 282 - - - - System Monitor - - - - - - - - - 0 - 0 - 427 - 21 - - - - - File - - - - - - Help - - - - - - Custom - - - - - - - - - - Exit - - - - - About - - - - - Check Matlab Licenses - - - - - - diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index 299958fd8dee..a13343453c9d 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -179,9 +179,8 @@ #include //Mantid -#include "Mantid/MantidAbout.h" -#include "Mantid/MantidDock.h" #include "Mantid/MantidUI.h" +#include "Mantid/MantidAbout.h" #include "Mantid/PeakPickerTool.h" #include "Mantid/ManageCustomMenus.h" #include "Mantid/ManageInterfaceCategories.h" @@ -439,10 +438,6 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args) explorerSplitter->setSizes( splitterSizes << 45 << 45); explorerWindow->hide(); - // Other docked widgets - m_interpreterDock = new QDockWidget(this); - m_sysMonitorDock = new QDockWidget(this); - // Needs to be done after initialization of dock windows, // because we now use QDockWidget::toggleViewAction() createActions(); @@ -573,7 +568,7 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args) setScriptingLanguage(defaultScriptingLang); m_iface_script = NULL; - // -- IPython docked widget -- + m_interpreterDock = new QDockWidget(this); m_interpreterDock->setObjectName("interpreterDock"); // this is needed for QMainWindow::restoreState() m_interpreterDock->setWindowTitle("Script Interpreter"); runPythonScript("from ipython_widget import *\nw = _qti.app._getInterpreterDock()\nw.setWidget(MantidIPythonWidget())",false,true,true); @@ -583,54 +578,6 @@ void ApplicationWindow::init(bool factorySettings, const QStringList& args) addDockWidget( Qt::BottomDockWidgetArea, m_interpreterDock ); } - // Algorithms, Workspaces & SysMonitor - if ( !restoreDockWidget(mantidUI->m_exploreMantid)) - { - addDockWidget(Qt::RightDockWidgetArea, mantidUI->m_exploreMantid); - } - if ( !restoreDockWidget(mantidUI->m_exploreAlgorithms)) - { - addDockWidget(Qt::RightDockWidgetArea, mantidUI->m_exploreAlgorithms); - } - if(psutilPresent()) - { - m_sysMonitorDock->setObjectName("systemMonitor"); // this is needed for QMainWindow::restoreState() - m_sysMonitorDock->setWindowTitle("System Monitor"); - runPythonScript("from SysMon import sysmon\n" - "w = sysmon.SysMon(_qti.app._getSysMonitorDock())\n" - "_qti.app._getSysMonitorDock().setWidget(w)", - false, true, true); - if ( !restoreDockWidget(m_sysMonitorDock)) - { - // Setting the max width to 300 and then to -1 later seems to - // be the only way that I found to get the dock to have a decent initial - // size but then still be resizable. - m_sysMonitorDock->setMaximumWidth(300); - addDockWidget(Qt::RightDockWidgetArea, m_sysMonitorDock); - m_sysMonitorDock->setMaximumWidth(QWIDGETSIZE_MAX); // reset it - } - tabifyDockWidget(mantidUI->m_exploreAlgorithms, m_sysMonitorDock); // first, second in that order on tabs - mantidUI->m_exploreAlgorithms->raise(); - - } - else - { - // Remove menu item - auto actions = view->actions(); - auto itr = actions.constBegin(); - auto iend = actions.constEnd(); - for(; itr != iend; ++itr) - { - if(*itr == m_sysMonitorDock->toggleViewAction()) break; - } - // Move back for the separator - if(itr != actions.constBegin()) --itr; - view->removeAction(*itr); - ++itr; - view->removeAction(*itr); - delete m_sysMonitorDock; - } - loadCustomActions(); // Nullify catalogSearch @@ -694,13 +641,13 @@ bool ApplicationWindow::shouldWeShowFirstTimeSetup(const QStringList& commandArg { const Mantid::Kernel::FacilityInfo& facilityInfo = config.getFacility(facility); const Mantid::Kernel::InstrumentInfo& instrumentInfo = config.getInstrument(instrument); - g_log.information()<<"Default facility '" << facilityInfo.name() + g_log.information()<<"Default facility '" << facilityInfo.name() << "', instrument '" << instrumentInfo.name() << "'" << std::endl; } catch (Mantid::Kernel::Exception::NotFoundError&) { //failed to find the facility or instrument - g_log.error()<<"Could not find your default facility '" << facility + g_log.error()<<"Could not find your default facility '" << facility <<"' or instrument '" << instrument << "' in facilities.xml, showing please select again." << std::endl; return true; } @@ -1308,12 +1255,6 @@ void ApplicationWindow::initMainMenu() mantidUI->addMenuItems(view); - // System monitor (might get removed later after check) - view->insertSeparator(); - m_sysMonitorDock->toggleViewAction()->setChecked(false); - view->addAction(m_sysMonitorDock->toggleViewAction()); - - view->insertSeparator(); toolbarsMenu = view->addMenu(tr("&Toolbars")); view->addAction(actionShowConfigureDialog); @@ -6173,7 +6114,7 @@ void ApplicationWindow::savetoNexusFile() else { throw std::runtime_error("Invalid input for SaveNexus, you cannot save this type of object as a NeXus file"); - } + } } else { @@ -7177,7 +7118,7 @@ void ApplicationWindow::showGeneralPlotDialog() return; } if (ml && ml->layers()) - showPlotDialog(); + showPlotDialog(); } else if (plot->isA("Graph3D")) { @@ -7186,7 +7127,7 @@ void ApplicationWindow::showGeneralPlotDialog() try { plot3D = dynamic_cast(gd); - } + } catch(std::runtime_error& ) { g_log.error() << "Failed to open general plot dialog for 3D plot"; @@ -7217,7 +7158,7 @@ void ApplicationWindow::showAxisDialog() return; } if (ml && ml->layers()) - dynamic_cast(gd)->showAxesPage(); + dynamic_cast(gd)->showAxesPage(); } else if (gd && plot->isA("Graph3D")) { @@ -11665,13 +11606,13 @@ void ApplicationWindow::analyzeCurve(Graph *g, Analysis operation, const QString ScaleEngine *se = dynamic_cast(g->plotWidget()->axisScaleEngine(c->xAxis())); if(se) { - if(se->type() == QwtScaleTransformation::Log10) - fitter = new LogisticFit (this, g); - else - fitter = new SigmoidalFit (this, g); + if(se->type() == QwtScaleTransformation::Log10) + fitter = new LogisticFit (this, g); + else + fitter = new SigmoidalFit (this, g); + } } } - } break; } @@ -14686,7 +14627,7 @@ bool ApplicationWindow::deleteFolder(Folder *f) auto newParent = dynamic_cast(currentFolder()->parent()); if(newParent) parent = newParent; - } + } } folders->blockSignals(true); @@ -15584,25 +15525,6 @@ bool ApplicationWindow::runPythonScript(const QString & code, bool async, return success; } -/// @return True if the psuitl python module is present and importable otherwise return false -bool ApplicationWindow::psutilPresent() -{ - static bool checkPerformed(false); - static bool pkgPresent(false); - - if(!checkPerformed) - { - g_log.debug("Checking for psutil\n"); - using Mantid::Kernel::Logger; - bool verbose = g_log.is(Logger::Priority::PRIO_DEBUG); - pkgPresent = runPythonScript("import psutil", false, false, verbose); - if(pkgPresent) g_log.debug() << "Found psutil package"; - else g_log.debug() << "Unable to find psutil package"; - checkPerformed = true; - } - - return pkgPresent; -} bool ApplicationWindow::validFor2DPlot(Table *table) diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.h b/Code/Mantid/MantidPlot/src/ApplicationWindow.h index 451818e34762..c984bd2ea01a 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.h +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.h @@ -226,9 +226,7 @@ public slots: void onScriptExecuteError(const QString & message, const QString & scriptName, int lineNumber); /// Runs an arbitrary lump of python code, return true/false on success/failure. bool runPythonScript(const QString & code, bool async = false, bool quiet=false, bool redirect=true); - /// Checks for the presence of the Python psutil module for the system monitor widget - bool psutilPresent(); - + QList windowsList() const; QList getAllWindows() const; void updateWindowLists(MdiSubWindow *w); @@ -597,8 +595,8 @@ public slots: //! Creates a new empty multilayer plot MultiLayer* newGraph(const QString& caption = tr("Graph")); - /// Prepares MultiLayer for plotting - creates if necessary, clears, applies initial settings - MultiLayer* prepareMultiLayer(bool& isNew, MultiLayer* window, const QString& newWindowName = "Graph", + /// Prepares MultiLayer for plotting - creates if necessary, clears, applies initial settings + MultiLayer* prepareMultiLayer(bool& isNew, MultiLayer* window, const QString& newWindowName = "Graph", bool clearWindow = false); void openRecentProject(int index); @@ -1007,12 +1005,12 @@ public slots: //@{ //! show scripting language selection dialog void showScriptingLangDialog(); - //! switches to the given scripting language; + //! switches to the given scripting language; bool setScriptingLanguage(const QString &lang); void scriptsDirPathChanged(const QString& path); //@} - + void makeToolbarsMenu(); void savetoNexusFile(); @@ -1322,7 +1320,7 @@ private slots: bool applyCurveStyleToMantid; ///< if true defaultCurveStyle, defaultSymbolSize are applyed to MantidCurves /// if true all errors are drawn on new plots with error bars, for a particular graph can be overridden /// form Add Error bars dialog - bool drawAllErrors; + bool drawAllErrors; QFont appFont, plot3DTitleFont, plot3DNumbersFont, plot3DAxesFont; QFont tableTextFont, tableHeaderFont, plotAxesFont, plotLegendFont, plotNumbersFont, plotTitleFont; QColor tableBkgdColor, tableTextColor, tableHeaderColor; @@ -1356,8 +1354,7 @@ private slots: QString defaultScriptingLang; QDockWidget *m_interpreterDock; - QDockWidget *m_sysMonitorDock; - + QSet allCategories() const { return m_allCategories; } private: @@ -1403,7 +1400,7 @@ private slots: QMenu *windowsMenu, *foldersMenu, *view, *graph, *fileMenu, *format, *edit; QMenu *recentProjectsMenu, *recentFilesMenu, *interfaceMenu; - + QMenu *help, *plot2DMenu, *analysisMenu, *multiPeakMenu, *icat; QMenu *matrixMenu, *plot3DMenu, *plotDataMenu, *tablesDepend, *scriptingMenu; QMenu *tableMenu, *fillMenu, *normMenu, *newMenu, *exportPlotMenu, *smoothMenu, *filterMenu, *decayMenu,*saveMenu,*openMenu, *toolbarsMenu; @@ -1486,7 +1483,7 @@ private slots: QList d_user_actions; QList d_user_menus; //Mantid - + QList m_interfaceActions; /// list of mantidmatrix windows opened from project file. @@ -1505,7 +1502,7 @@ private slots: QList m_floatingWindows; // To block activating new window when a floating window is in process of resetting flags bool blockWindowActivation; - /// + /// bool m_enableQtiPlotFitting; #ifdef SHARED_MENUBAR diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp index 4cbce1df41e6..e9434bad6802 100644 --- a/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp +++ b/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp @@ -43,6 +43,7 @@ MantidDockWidget::MantidDockWidget(MantidUI *mui, ApplicationWindow *parent) : setObjectName("exploreMantid"); // this is needed for QMainWindow::restoreState() setMinimumHeight(150); setMinimumWidth(200); + parent->addDockWidget( Qt::RightDockWidgetArea, this ); m_appParent = parent; @@ -71,13 +72,13 @@ MantidDockWidget::MantidDockWidget(MantidUI *mui, ApplicationWindow *parent) : buttonLayout->addWidget(m_saveButton); m_workspaceFilter = new MantidQt::MantidWidgets::LineEditWithClear(); - m_workspaceFilter->setPlaceholderText("Filter Workspaces"); - m_workspaceFilter->setToolTip("Type here to filter the workspaces"); + m_workspaceFilter->setPlaceholderText("Filter Workspaces"); + m_workspaceFilter->setToolTip("Type here to filter the workspaces"); connect(m_workspaceFilter, SIGNAL(textChanged(const QString&)), this, SLOT(filterWorkspaceTree(const QString&))); QVBoxLayout * layout = new QVBoxLayout(); - f->setLayout(layout); + f->setLayout(layout); layout->setSpacing(0); layout->setMargin(0); layout->addLayout(buttonLayout); @@ -197,7 +198,7 @@ void MantidDockWidget::createWorkspaceMenuActions() connect(m_showMDPlot, SIGNAL(activated()), m_mantidUI, SLOT(showMDPlot())); m_showListData = new QAction(tr("List Data"), this); - connect(m_showListData, SIGNAL(activated()), m_mantidUI, SLOT(showListData())); + connect(m_showListData, SIGNAL(activated()), m_mantidUI, SLOT(showListData())); m_showSpectrumViewer = new QAction(tr("Show Spectrum Viewer"), this); connect(m_showSpectrumViewer, SIGNAL(activated()), m_mantidUI, SLOT(showSpectrumViewer())); @@ -682,7 +683,7 @@ void MantidDockWidget::filterWorkspaceTree(const QString &text) //show all items QTreeWidgetItemIterator it(m_tree); - while (*it) + while (*it) { (*it)->setHidden(false); ++it; @@ -705,7 +706,7 @@ void MantidDockWidget::filterWorkspaceTree(const QString &text) { expanded << item->text(0); } - else + else { //expand everything that is at the top level (as we lazy load this is required) item->setExpanded(true); @@ -714,12 +715,12 @@ void MantidDockWidget::filterWorkspaceTree(const QString &text) //filter based on the string QTreeWidgetItemIterator it(m_tree,QTreeWidgetItemIterator::All); - while (*it) + while (*it) { QTreeWidgetItem *item = (*it); QVariant userData = item->data(0, Qt::UserRole); - if (!userData.isNull() ) + if (!userData.isNull() ) { Workspace_sptr workspace = userData.value(); if (workspace) @@ -770,10 +771,10 @@ void MantidDockWidget::filterWorkspaceTree(const QString &text) //make children of visible groups visible for (auto itGroup = visibleGroups.begin(); itGroup != visibleGroups.end(); ++itGroup) { - QTreeWidgetItem *group = (*itGroup); + QTreeWidgetItem *group = (*itGroup); for (int i = 0; i < group->childCount(); i++) { - QTreeWidgetItem *child = group->child(i); + QTreeWidgetItem *child = group->child(i); if (child->isHidden()) { //I was previously hidden, show me @@ -811,7 +812,7 @@ void MantidDockWidget::clickedWorkspace(QTreeWidgetItem* item, int) } void MantidDockWidget::workspaceSelected() -{ +{ QList selectedItems=m_tree->selectedItems(); if(selectedItems.isEmpty()) return; @@ -1076,7 +1077,7 @@ void MantidDockWidget::saveToProgram(const QString & name) } //Check to see if mandatory information is included - if ((programKeysAndDetails.count("name") != 0) && (programKeysAndDetails.count("target") != 0) && (programKeysAndDetails.count("saveusing") != 0)) + if ((programKeysAndDetails.count("name") != 0) && (programKeysAndDetails.count("target") != 0) && (programKeysAndDetails.count("saveusing") != 0)) { std::string expTarget = Poco::Path::expand(programKeysAndDetails.find("target")->second); @@ -1240,7 +1241,7 @@ void MantidDockWidget::popupMenu(const QPoint & pos) } // Add the items that are appropriate for the type - if( MatrixWorkspace_const_sptr matrixWS = boost::dynamic_pointer_cast(ws) ) + if( MatrixWorkspace_const_sptr matrixWS = boost::dynamic_pointer_cast(ws) ) { addMatrixWorkspaceMenuItems(menu, matrixWS); } @@ -1256,7 +1257,7 @@ void MantidDockWidget::popupMenu(const QPoint & pos) { addPeaksWorkspaceMenuItems(menu, peaksWS); } - else if( boost::dynamic_pointer_cast(ws) ) + else if( boost::dynamic_pointer_cast(ws) ) { addWorkspaceGroupMenuItems(menu); } @@ -1303,16 +1304,16 @@ void MantidDockWidget::popupMenu(const QPoint & pos) connect(m_program,SIGNAL(activated()),m_programMapper,SLOT(map())); //Send name of program when clicked m_programMapper->setMapping(m_program, name); - m_saveToProgram->addAction(m_program); + m_saveToProgram->addAction(m_program); // Set first pass to false so that it doesn't set up another menu entry for all programs. firstPass = false; } - } + } } //Tell the button what to listen for and what to do once clicked (if there is anything to connect it will be set to false) - if (firstPass == false) + if (firstPass == false) connect(m_programMapper, SIGNAL(mapped(const QString &)), this, SLOT(saveToProgram(const QString &))); //Rename is valid for all workspace types @@ -1529,11 +1530,11 @@ void MantidTreeWidget::dragEnterEvent(QDragEnterEvent *de) void MantidTreeWidget::dropEvent(QDropEvent *de) { QStringList filenames; - const QMimeData *mimeData = de->mimeData(); - if (mimeData->hasUrls()) + const QMimeData *mimeData = de->mimeData(); + if (mimeData->hasUrls()) { QList urlList = mimeData->urls(); - for (int i = 0; i < urlList.size(); ++i) + for (int i = 0; i < urlList.size(); ++i) { QString fName = urlList[i].toLocalFile(); if (fName.size()>0) @@ -1544,7 +1545,7 @@ void MantidTreeWidget::dropEvent(QDropEvent *de) } de->acceptProposedAction(); - for (int i = 0; i < filenames.size(); ++i) + for (int i = 0; i < filenames.size(); ++i) { try { @@ -1559,7 +1560,7 @@ void MantidTreeWidget::dropEvent(QDropEvent *de) catch (std::runtime_error& error) { treelog.error()<<"Failed to Load the file "< > MantidTreeWidget::chooseSpectrumFromSelected() return spectrumToPlot; } - // Else, one or more workspaces + // Else, one or more workspaces MantidWSIndexDialog *dio = new MantidWSIndexDialog(m_mantidUI, 0, selectedMatrixWsNameList); dio->exec(); return dio->getPlots(); @@ -1893,6 +1894,7 @@ AlgorithmDockWidget::AlgorithmDockWidget(MantidUI *mui, ApplicationWindow *w): setObjectName("exploreAlgorithms"); // this is needed for QMainWindow::restoreState() setMinimumHeight(150); setMinimumWidth(200); + w->addDockWidget( Qt::RightDockWidgetArea, this );//*/ //Add the AlgorithmSelectorWidget m_selector = new MantidQt::MantidWidgets::AlgorithmSelectorWidget(this); @@ -2005,3 +2007,4 @@ void AlgorithmDockWidget::hideProgressBar() //-------------------- ----------------------// + diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h b/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h index 744af6c1eaf9..d776af0a3779 100644 --- a/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h +++ b/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h @@ -204,7 +204,7 @@ class MantidUI:public QObject void showAlgWidget(bool on = true); /// Plot a 1D graph for an integrated mdworkspace - MultiLayer* plotMDList(const QStringList& wsNames, const int plotAxis, + MultiLayer* plotMDList(const QStringList& wsNames, const int plotAxis, const Mantid::API::MDNormalization normalization, const bool showError, MultiLayer* plotWindow = NULL, bool clearWindow = false); @@ -256,7 +256,7 @@ class MantidUI:public QObject /// Create a table showing detector information for the given workspace and indices and optionally the data for that detector Table* createDetectorTable(const QString & wsName, const std::vector& indices, bool include_data = false); /// Create the instrument detector table from a MatrixWorkspace - Table* createDetectorTable(const QString & wsName, const Mantid::API::MatrixWorkspace_sptr & ws, + Table* createDetectorTable(const QString & wsName, const Mantid::API::MatrixWorkspace_sptr & ws, const std::vector& indices, bool include_data = false); /// Create a table of detectors from a PeaksWorkspace Table* createDetectorTable(const QString & wsName, const Mantid::API::IPeaksWorkspace_sptr & ws); @@ -271,7 +271,7 @@ class MantidUI:public QObject void renameWorkspace(QStringList = QStringList()); /** - * Set the currently used fit property browser. Is needed because e.g. Muon Analysis is using its + * Set the currently used fit property browser. Is needed because e.g. Muon Analysis is using its * own fit browser. * @param newBrowser The browser to be used. If is null, is set to default one. */ @@ -314,15 +314,6 @@ class MantidUI:public QObject public: - // QMainWindow needs the dock widgets to be accessible - MantidDockWidget *m_exploreMantid; // Dock window for manipulating workspaces - AlgorithmDockWidget *m_exploreAlgorithms; // Dock window for using algorithms - RemoteClusterDockWidget *m_exploreRemoteTasks; // Dock window for using remote tasks - /// Current fit property browser being used - MantidQt::MantidWidgets::FitPropertyBrowser* m_fitFunction; - /// Default fit property browser (the one docked on the left) - MantidQt::MantidWidgets::FitPropertyBrowser* m_defaultFitFunction; - signals: // These signals are to be fired from methods run in threads other than the main one @@ -493,11 +484,11 @@ private slots: void handleRenameWorkspace(Mantid::API::WorkspaceRenameNotification_ptr pNf); Poco::NObserver m_renameObserver; - //handles notification send by Groupworkspaces algorithm + //handles notification send by Groupworkspaces algorithm void handleGroupWorkspaces(Mantid::API::WorkspacesGroupedNotification_ptr pNf); Poco::NObserver m_groupworkspacesObserver; - //handles notification send by UnGroupworkspaces algorithm + //handles notification send by UnGroupworkspaces algorithm void handleUnGroupWorkspace(Mantid::API::WorkspaceUnGroupingNotification_ptr pNf); Poco::NObserver m_ungroupworkspaceObserver; @@ -532,6 +523,13 @@ private slots: // Private variables ApplicationWindow *m_appWindow; // QtiPlot main ApplicationWindow + MantidDockWidget *m_exploreMantid; // Dock window for manipulating workspaces + AlgorithmDockWidget *m_exploreAlgorithms; // Dock window for using algorithms + RemoteClusterDockWidget *m_exploreRemoteTasks; // Dock window for using remote tasks + /// Current fit property browser being used + MantidQt::MantidWidgets::FitPropertyBrowser* m_fitFunction; + /// Default fit property browser (the one docked on the left) + MantidQt::MantidWidgets::FitPropertyBrowser* m_defaultFitFunction; QAction *actionCopyRowToTable; QAction *actionCopyRowToGraph; diff --git a/Code/Mantid/MantidPlot/src/qti.sip b/Code/Mantid/MantidPlot/src/qti.sip index a15734f9e842..2d12a0cb2431 100644 --- a/Code/Mantid/MantidPlot/src/qti.sip +++ b/Code/Mantid/MantidPlot/src/qti.sip @@ -1123,9 +1123,9 @@ public: %End Matrix* newMatrix(); Matrix* newMatrix(const QString&, int=32, int=32); - + TiledWindow *newTiledWindow(); - + MultiLayer *plot(const QString&) /PyName=graph/; %MethodCode sipRes = sipCpp->currentFolder()->graph(*a0, false); @@ -1207,12 +1207,6 @@ public: sipRes = sipCpp->m_interpreterDock; %End - // Required for setting the SysMon widget - QDockWidget _getSysMonitorDock(); -%MethodCode - sipRes = sipCpp->m_sysMonitorDock; -%End - // folders Folder *activeFolder(); %MethodCode From 19dd2f769250ac67e61e8b82b5a9ffe66c6dd532 Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Tue, 17 Feb 2015 16:37:34 +0100 Subject: [PATCH 244/414] Make inheritance in PoldiSpectrumConstantBackground virtual This change should fix a compiler error on gcc 4.9.1 --- .../PoldiUtilities/PoldiSpectrumConstantBackground.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiSpectrumConstantBackground.h b/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiSpectrumConstantBackground.h index 88e8a6f9b6f3..b6dbf102bd6b 100644 --- a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiSpectrumConstantBackground.h +++ b/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiSpectrumConstantBackground.h @@ -38,8 +38,8 @@ namespace Poldi { Code Documentation is available at: */ class MANTID_SINQ_DLL PoldiSpectrumConstantBackground - : public API::ParamFunction, - public API::IFunction1D, + : virtual public API::ParamFunction, + virtual public API::IFunction1D, public IPoldiFunction1D { public: PoldiSpectrumConstantBackground(); From 2f78028cbc86ca177540c2b6b81ccc4e5f387a0e Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Tue, 17 Feb 2015 16:23:20 +0000 Subject: [PATCH 245/414] Fix failing UserInputValidator tests Forgot to update tests for changes made to the results output Refs #11072 --- .../test/UserInputValidatorTest.h | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/test/UserInputValidatorTest.h b/Code/Mantid/MantidQt/CustomInterfaces/test/UserInputValidatorTest.h index 4ed7c14a14e9..775ef03668e4 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/test/UserInputValidatorTest.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/test/UserInputValidatorTest.h @@ -32,7 +32,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite UserInputValidator uiv; TS_ASSERT(!uiv.checkBins(0.6, -0.1, 1.8)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nBin width must be a positive value."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nBin width must be a positive value."); } void test_zeroWidthRebin() @@ -40,7 +40,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite UserInputValidator uiv; TS_ASSERT(!uiv.checkBins(0.6, 0.0, 1.8)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nBin width must be non-zero."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nBin width must be non-zero."); } void test_zeroRangeRebin() @@ -48,7 +48,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite UserInputValidator uiv; TS_ASSERT(!uiv.checkBins(0.6, 0.1, 0.6)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nBinning ranges must be non-zero."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nBinning ranges must be non-zero."); } void test_reverseRangeRebin() @@ -56,7 +56,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite UserInputValidator uiv; TS_ASSERT(!uiv.checkBins(1.8, 0.1, 0.6)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nThe start of a binning range must be less than the end."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nThe start of a binning range must be less than the end."); } void test_binsNotFactorsRebin() @@ -64,7 +64,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite UserInputValidator uiv; TS_ASSERT(!uiv.checkBins(0.0, 0.2, 0.7)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nBin width must allow for even splitting of the range."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nBin width must allow for even splitting of the range."); } void test_validRange() @@ -81,7 +81,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite std::pair range(10, 5); TS_ASSERT(!uiv.checkValidRange("test range", range)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nThe start of test range must be less than the end."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nThe start of test range must be less than the end."); } void test_invalidRangeZeroWidth() @@ -90,7 +90,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite std::pair range(5, 5); TS_ASSERT(!uiv.checkValidRange("test range", range)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\ntest range must have a non-zero width."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\ntest range must have a non-zero width."); } void test_nonOverlappingRanges() @@ -109,7 +109,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite std::pair rangeB(3, 8); TS_ASSERT(!uiv.checkRangesDontOverlap(rangeA, rangeB)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nThe ranges must not overlap: [1,5], [3,8]."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nThe ranges must not overlap: [1,5], [3,8]."); } void test_enclosedRange() @@ -128,7 +128,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite std::pair inner(3, 15); TS_ASSERT(!uiv.checkRangeIsEnclosed("outer range", outer, "inner range", inner)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nouter range must completely enclose inner range."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nouter range must completely enclose inner range."); } }; From 029132cc2a45889d38f4b220f14fcd63c456c1bc Mon Sep 17 00:00:00 2001 From: Steven Hahn Date: Tue, 17 Feb 2015 12:03:16 -0500 Subject: [PATCH 246/414] Refs #11110. Fix compiler error and warning on AppleClang --- Code/Mantid/Framework/Kernel/src/InternetHelper.cpp | 2 +- .../CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp index 7e07db7f453d..3b7635e77575 100644 --- a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp +++ b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp @@ -134,7 +134,7 @@ int InternetHelper::sendRequestAndProcess(HTTPClientSession &session, std::ostream &responseStream) { // create a request this->createRequest(uri); - session.sendRequest(*m_request) << m_body; + session.sendRequest(*m_request) << m_body.rdbuf(); HTTPResponse res; std::istream &rs = session.receiveResponse(res); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp index 177dd6e9e71f..127a699513cd 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp @@ -275,7 +275,7 @@ namespace CustomInterfaces } // If we get this far then properties are valid so update mini plots - if((prop == m_properties["PreviewSpec"])) + if(prop == m_properties["PreviewSpec"]) updateMiniPlots(); } From 0f3df5223605eb54b31933f8516b5b3ada805e4e Mon Sep 17 00:00:00 2001 From: Steven Hahn Date: Tue, 17 Feb 2015 15:04:12 -0500 Subject: [PATCH 247/414] Refs #11110. switch from rdbuf() to str() --- Code/Mantid/Framework/Kernel/src/InternetHelper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp index 3b7635e77575..3a991e21cc53 100644 --- a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp +++ b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp @@ -134,7 +134,7 @@ int InternetHelper::sendRequestAndProcess(HTTPClientSession &session, std::ostream &responseStream) { // create a request this->createRequest(uri); - session.sendRequest(*m_request) << m_body.rdbuf(); + session.sendRequest(*m_request) << m_body.str(); HTTPResponse res; std::istream &rs = session.receiveResponse(res); From 6aa6a5c70a2659597170af3d37de43d41463f625 Mon Sep 17 00:00:00 2001 From: Wenduo Zhou Date: Tue, 17 Feb 2015 17:43:34 -0500 Subject: [PATCH 248/414] Refs #11112. Modified the property TimeInterval. Such that it can take a list of doubles instead of 1. - modified: ../Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp - modified: ../Mantid/Framework/Algorithms/test/GenerateEventsFilterTest.h - modified: ../Mantid/Framework/Kernel/src/InternetHelper.cpp: the cast of osstringstream to osstream on mac osx. Modify it only to make the compiling pass. --- .../Algorithms/src/GenerateEventsFilter.cpp | 20 ++++++++++++++----- .../test/GenerateEventsFilterTest.h | 4 ++-- .../Framework/Kernel/src/InternetHelper.cpp | 2 +- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp b/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp index c5e4e660b520..7784dcfb7869 100644 --- a/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp +++ b/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp @@ -10,6 +10,7 @@ #include "MantidAPI/WorkspaceProperty.h" #include "MantidAPI/Column.h" #include "MantidKernel/VisibleWhenProperty.h" +#include "MantidKernel/ArrayProperty.h" using namespace Mantid; using namespace Mantid::Kernel; @@ -74,8 +75,12 @@ void GenerateEventsFilter::init() { "while the relative time takes integer or float. "); // Split by time (only) in steps - declareProperty("TimeInterval", EMPTY_DBL(), - "Length of the time splices if filtered in time only."); + // TODO - clean this part + // auto timeintervalproperty = boost::make_shared >("TimeInterval"); + declareProperty(new ArrayProperty("TimeInterval"), + "Length..."); + // declareProperty("TimeInterval", EMPTY_DBL(), + // "Length of the time splices if filtered in time only."); setPropertySettings("TimeInterval", new VisibleWhenProperty("LogName", IS_EQUAL_TO, "")); @@ -379,10 +384,10 @@ void GenerateEventsFilter::processInputTime() { /** Set splitters by time value / interval only */ void GenerateEventsFilter::setFilterByTimeOnly() { - double timeinterval = this->getProperty("TimeInterval"); + vector vec_timeintervals = this->getProperty("TimeInterval"); bool singleslot = false; - if (timeinterval == EMPTY_DBL()) + if (vec_timeintervals.size() == 0) singleslot = true; // Progress @@ -401,7 +406,8 @@ void GenerateEventsFilter::setFilterByTimeOnly() { ss << "Time Interval From " << m_startTime << " to " << m_stopTime; addNewTimeFilterSplitter(m_startTime, m_stopTime, wsindex, ss.str()); - } else { + } else if (vec_timeintervals.size() == 1) { + double timeinterval = vec_timeintervals[0]; int64_t timeslot = 0; // Explicitly N time intervals @@ -439,6 +445,10 @@ void GenerateEventsFilter::setFilterByTimeOnly() { } } // END-WHILE } // END-IF-ELSE + else + { + throw std::runtime_error("Implement multiple time interval ASAP."); + } return; } diff --git a/Code/Mantid/Framework/Algorithms/test/GenerateEventsFilterTest.h b/Code/Mantid/Framework/Algorithms/test/GenerateEventsFilterTest.h index 33816f2d7cdf..10239c31d3d6 100644 --- a/Code/Mantid/Framework/Algorithms/test/GenerateEventsFilterTest.h +++ b/Code/Mantid/Framework/Algorithms/test/GenerateEventsFilterTest.h @@ -123,7 +123,7 @@ class GenerateEventsFilterTest : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING(alg.setProperty("InputWorkspace", eventWS)); TS_ASSERT_THROWS_NOTHING(alg.setProperty("OutputWorkspace", "Splitters01")); TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("InformationWorkspace", "InfoWS");) - TS_ASSERT_THROWS_NOTHING(alg.setProperty("TimeInterval", 15000.0)); + TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("TimeInterval", "15000.0")); TS_ASSERT_THROWS_NOTHING(alg.setProperty("UnitOfTime", "Nanoseconds")); // 3. Running and get result @@ -597,7 +597,7 @@ class GenerateEventsFilterTest : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("OutputWorkspace", "Splitters08")); TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("InformationWorkspace", "InfoWS08")); TS_ASSERT_THROWS_NOTHING(alg.setProperty("FastLog", true)); - TS_ASSERT_THROWS_NOTHING(alg.setProperty("TimeInterval", 15000.0)); + TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("TimeInterval", "15000.0")); TS_ASSERT_THROWS_NOTHING(alg.setProperty("UnitOfTime", "Nanoseconds")); // Running and get result diff --git a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp index 7e07db7f453d..3a991e21cc53 100644 --- a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp +++ b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp @@ -134,7 +134,7 @@ int InternetHelper::sendRequestAndProcess(HTTPClientSession &session, std::ostream &responseStream) { // create a request this->createRequest(uri); - session.sendRequest(*m_request) << m_body; + session.sendRequest(*m_request) << m_body.str(); HTTPResponse res; std::istream &rs = session.receiveResponse(res); From 813315ec985e7b5d25a5b36db03018239585e79c Mon Sep 17 00:00:00 2001 From: Wenduo Zhou Date: Tue, 17 Feb 2015 20:56:14 -0500 Subject: [PATCH 249/414] Refs #11112. Implemented the new feature and unit test. --- .../Algorithms/src/GenerateEventsFilter.cpp | 73 +++++++++++++++---- .../test/GenerateEventsFilterTest.h | 73 +++++++++++++++++++ 2 files changed, 131 insertions(+), 15 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp b/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp index 7784dcfb7869..6987d907070c 100644 --- a/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp +++ b/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp @@ -75,12 +75,8 @@ void GenerateEventsFilter::init() { "while the relative time takes integer or float. "); // Split by time (only) in steps - // TODO - clean this part - // auto timeintervalproperty = boost::make_shared >("TimeInterval"); declareProperty(new ArrayProperty("TimeInterval"), "Length..."); - // declareProperty("TimeInterval", EMPTY_DBL(), - // "Length of the time splices if filtered in time only."); setPropertySettings("TimeInterval", new VisibleWhenProperty("LogName", IS_EQUAL_TO, "")); @@ -118,16 +114,6 @@ void GenerateEventsFilter::init() { setPropertySettings("LogValueInterval", new VisibleWhenProperty("LogName", IS_NOT_EQUAL_TO, "")); - /* - Documentation doesn't include property options in property descriptions or - anywhere else. - For example, FilterLogValueByChangingDirection doesn't let me know that - Increasing and Decreasing - are valid options without using the MantidPlotGui to open the algorithm - dialog. - - */ - std::vector filteroptions; filteroptions.push_back("Both"); filteroptions.push_back("Increase"); @@ -447,7 +433,64 @@ void GenerateEventsFilter::setFilterByTimeOnly() { } // END-IF-ELSE else { - throw std::runtime_error("Implement multiple time interval ASAP."); + // Explicitly N time intervals with various interval + + // Construct a vector for time intervals in nanosecond + size_t numtimeintervals = vec_timeintervals.size(); + std::vector vec_dtimens(numtimeintervals); + for (size_t id = 0; id < numtimeintervals; ++id) + { + int64_t deltatime_ns = + static_cast(vec_timeintervals[id] * m_timeUnitConvertFactorToNS); + vec_dtimens[id] = deltatime_ns; + } + + // Build the splitters + int64_t timeslot = 0; + + int64_t curtime_ns = m_startTime.totalNanoseconds(); + int wsindex = 0; + while (curtime_ns < m_stopTime.totalNanoseconds()) { + int64_t deltatime_ns; + for (size_t id = 0; id < numtimeintervals; ++id) + { + // get next time interval value + deltatime_ns = vec_dtimens[id]; + // Calculate next.time + int64_t nexttime_ns = curtime_ns + deltatime_ns; + bool breaklater = false; + if (nexttime_ns > m_stopTime.totalNanoseconds()) + { + nexttime_ns = m_stopTime.totalNanoseconds(); + breaklater = true; + } + + // Create splitter and information + Kernel::DateAndTime t0(curtime_ns); + Kernel::DateAndTime tf(nexttime_ns); + std::stringstream ss; + ss << "Time Interval From " << t0 << " to " << tf; + + addNewTimeFilterSplitter(t0, tf, wsindex, ss.str()); + + // Update loop variable + curtime_ns = nexttime_ns; + ++wsindex; + + // Update progress + int64_t newtimeslot = + (curtime_ns - m_startTime.totalNanoseconds()) * 90 / totaltime; + if (newtimeslot > timeslot) { + // There is change and update progress + timeslot = newtimeslot; + double prog = 0.1 + double(timeslot) / 100.0; + progress(prog); + } + + if (breaklater) + break; + } // END-FOR + } // END-WHILE } return; diff --git a/Code/Mantid/Framework/Algorithms/test/GenerateEventsFilterTest.h b/Code/Mantid/Framework/Algorithms/test/GenerateEventsFilterTest.h index 10239c31d3d6..e9715535e5cb 100644 --- a/Code/Mantid/Framework/Algorithms/test/GenerateEventsFilterTest.h +++ b/Code/Mantid/Framework/Algorithms/test/GenerateEventsFilterTest.h @@ -941,6 +941,79 @@ class GenerateEventsFilterTest : public CxxTest::TestSuite } + //---------------------------------------------------------------------------------------------- + /** Test generation of splitters by various time intervals + * (1) Multiple time interval with various time interval lengths + * (2) Default start time and stop time + */ + void test_genTimeVariousIntervalMatrixSplitter() + { + // Create input Workspace & initial setup + DataObjects::EventWorkspace_sptr eventWS = createEventWorkspace(); + AnalysisDataService::Instance().addOrReplace("TestEventWorkspace08v", eventWS); + int64_t timeinterval_ns = 15000; + + // Init and set property + GenerateEventsFilter alg; + alg.initialize(); + + std::vector vectimeintervals; + vectimeintervals.push_back(static_cast(timeinterval_ns)); + vectimeintervals.push_back(static_cast(timeinterval_ns)*2.); + vectimeintervals.push_back(static_cast(timeinterval_ns)*3.); + TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("InputWorkspace", "TestEventWorkspace08v")); + TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("OutputWorkspace", "Splitters08v")); + TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("InformationWorkspace", "InfoWS08v")); + TS_ASSERT_THROWS_NOTHING(alg.setProperty("FastLog", true)); + TS_ASSERT_THROWS_NOTHING(alg.setProperty("TimeInterval", vectimeintervals)); + TS_ASSERT_THROWS_NOTHING(alg.setProperty("UnitOfTime", "Nanoseconds")); + + // Running and get result + TS_ASSERT_THROWS_NOTHING(alg.execute()); + TS_ASSERT(alg.isExecuted()); + + // Check output workspace + API::MatrixWorkspace_sptr splittersws = + boost::dynamic_pointer_cast(AnalysisDataService::Instance().retrieve("Splitters08v")); + + TS_ASSERT(splittersws); + + // Check values of output workspace + size_t numintervals = 38; + TS_ASSERT_EQUALS(splittersws->readY(0).size(), numintervals); + + std::string runstarttimestr = eventWS->run().getProperty("run_start")->value(); + Kernel::DateAndTime runstarttime(runstarttimestr); + int64_t runstarttime_ns = runstarttime.totalNanoseconds(); + + Kernel::TimeSeriesProperty *protonchargelog = + dynamic_cast* >(eventWS->run().getProperty("proton_charge")); + Kernel::DateAndTime runstoptime = Kernel::DateAndTime(protonchargelog->lastTime().totalNanoseconds() + 100000); + + // First 3 intervals + TS_ASSERT_EQUALS(static_cast(splittersws->readX(0)[0]), runstarttime_ns); + TS_ASSERT_EQUALS(static_cast(splittersws->readX(0)[1]), runstarttime_ns + timeinterval_ns); + TS_ASSERT_EQUALS(static_cast(splittersws->readY(0)[0]), 0); + + TS_ASSERT_EQUALS(static_cast(splittersws->readX(0)[2]), runstarttime_ns + timeinterval_ns*3); + TS_ASSERT_EQUALS(static_cast(splittersws->readY(0)[1]), 1); + + TS_ASSERT_EQUALS(static_cast(splittersws->readX(0)[3]), runstarttime_ns + timeinterval_ns*6); + TS_ASSERT_EQUALS(static_cast(splittersws->readY(0)[2]), 2); + + // Last interval + TS_ASSERT_EQUALS(static_cast(splittersws->readX(0).back()), runstoptime.totalNanoseconds()); + TS_ASSERT_EQUALS(static_cast(splittersws->readY(0).back()), numintervals-1); + + // Clean + AnalysisDataService::Instance().remove("Splitters08v"); + AnalysisDataService::Instance().remove("InfoWS08v"); + AnalysisDataService::Instance().remove("TestEventWorkspace08v"); + + return; + } + + //---------------------------------------------------------------------------------------------- /** Convert the splitters stored in a matrix workspace to a vector of SplittingInterval objects */ From 83c603965a3b19e30897ae27f942f668d7f4909d Mon Sep 17 00:00:00 2001 From: Wenduo Zhou Date: Tue, 17 Feb 2015 21:52:39 -0500 Subject: [PATCH 250/414] Refs #11112. Improved documentation. --- .../Algorithms/src/GenerateEventsFilter.cpp | 8 ++++- .../algorithms/GenerateEventsFilter-v1.rst | 33 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp b/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp index 6987d907070c..dd1f338b860c 100644 --- a/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp +++ b/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp @@ -76,7 +76,13 @@ void GenerateEventsFilter::init() { // Split by time (only) in steps declareProperty(new ArrayProperty("TimeInterval"), - "Length..."); + "Array for lengths of time intervals for splitters. " + "If the array is empty, then there will be one splitter " + "created from StartTime and StopTime. " + "If the array has one value, then all splitters will have " + "same time intervals. " + "If the size of the array is larger than one, then the " + "splitters can have various time interval values."); setPropertySettings("TimeInterval", new VisibleWhenProperty("LogName", IS_EQUAL_TO, "")); diff --git a/Code/Mantid/docs/source/algorithms/GenerateEventsFilter-v1.rst b/Code/Mantid/docs/source/algorithms/GenerateEventsFilter-v1.rst index 7eaaace49bfb..a97a47ec8c31 100644 --- a/Code/Mantid/docs/source/algorithms/GenerateEventsFilter-v1.rst +++ b/Code/Mantid/docs/source/algorithms/GenerateEventsFilter-v1.rst @@ -70,6 +70,12 @@ this algorithm: workspace index associated. These workspace indices are incremented by 1 from 0 along with their orders in time. +- A series of filters for multiple continuous time intervals, which + have various lengths of period. + Each of them has an individual workspace index associated. + These workspace indices are incremented by 1 from 0 along with their + order in time. + - A filter containing one or multiple time intervals according to a specified log value. Any log value of the time that falls into the selected time intervals is equal or within the tolerance of a user @@ -81,6 +87,33 @@ this algorithm: equal or within the tolerance of the log value as v\_0 + n x delta\_v +/- tolerance\_v. +Generate event filters by time +============================== + +Event filters can be created by defining start and stop time and time intervals. +The three input properties used are *StartTime*, *StopTime* and *TimeInterval*. +*TimeInterval* accepts an array of doubles. + +If the array size is zero, then there will be one and only splitter will be +created from *StartTime* and *StopTime*. + +If the size of the array is one, then all event splitters will have the same duration +of time. + +In general if the array is composed as :math:`t_1, t_2, \cdots, t_n`, +and :math:`T_0` is the run start time, +then the event splitters will have the time boudaries as + +.. math:: (T_0, T_0+t_1), (T_0+t_1, T_0+t_1+t_2), \cdots, (T_0+\sum_{i=1}^(n-1)t_i, T_0+\sum_{i=1}^nt_i), (T_0+\sum_{i=1}^nt_i, T_0+\sum_{i=1}^nt_i+t_1), \cdots + +until the stop time is reached. + +Unit of time +############ + +There are three types of units that are supported for time. +They are second, nanosecond and percentage of duration from *StartTime* to *StopTime*. + Generate event filters by sample log value ========================================== From dc730de977453c6805a6bec13700377fc738cc1d Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Wed, 18 Feb 2015 08:59:27 +0000 Subject: [PATCH 251/414] Re #10862 Adding workspace unit test --- .../test/LoadGSASInstrumentFileTest.h | 131 +++++++++++++++++- 1 file changed, 130 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/DataHandling/test/LoadGSASInstrumentFileTest.h b/Code/Mantid/Framework/DataHandling/test/LoadGSASInstrumentFileTest.h index 598f9758378a..7545b11fa3a6 100644 --- a/Code/Mantid/Framework/DataHandling/test/LoadGSASInstrumentFileTest.h +++ b/Code/Mantid/Framework/DataHandling/test/LoadGSASInstrumentFileTest.h @@ -205,6 +205,113 @@ class LoadGSASInstrumentFileTest : public CxxTest::TestSuite return; } + void test_workspace() + { + // Generate file with two banks + string filename("TestWorskpace.irf"); + generate2BankPrmFile(filename); + + // Create workspace group to put parameters into + // This is a group of two workspaces + createWorkspaceGroup(2,"loadGSASInstrumentFileWorkspace"); + + // Set up algorithm to load into the workspace + LoadGSASInstrumentFile alg; + alg.initialize(); + alg.setProperty("Filename", filename); + alg.setPropertyValue("Banks", "1,2"); + alg.setProperty("Workspace", wsName); + + // Execute + TS_ASSERT_THROWS_NOTHING(alg.execute()); + TS_ASSERT(alg.isExecuted()); + + // Check parameters in output workspace + // The output workspace is a workspace group with each + // member corresponding to each of the one banks in the prm file + + // First, check first workspace + WorkspaceGroup_sptr gws; + gws = AnalysisDataService::Instance().retrieveWS(wsName); + auto ws = boost::dynamic_pointer_cast(gws->getItem(0)); + Mantid::Geometry::ParameterMap& paramMap = ws->instrumentParameters(); + boost::shared_ptr instr = ws->getInstrument(); + + // To check parameters in workspace + Mantid::Geometry::FitParameter fitParam; + Mantid::Geometry::Parameter_sptr param; + + // Check Alpha0 parameter + param = paramMap.get(&(*instr), "Alpha0", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 0.00); + // Check Alpha1 parameter + param = paramMap.get(&(*instr), "Alpha1", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 0.21); + // Check Beta0 parameter + param = paramMap.get(&(*instr), "Beta0", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 31.7927); + // Check Beta1 parameter + param = paramMap.get(&(*instr), "Kappa", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 51.4205); + // Check SigmsSquared parameter + // This is a formula, so values are not exact + param = paramMap.get(&(*instr), "SigmaSquared", "fitting"); + fitParam = param->value(); + TS_ASSERT_DELTA( fitParam.getValue(0.0), 0.01, 0.000001); + TS_ASSERT_DELTA( fitParam.getValue(0.5), 7814.7468, 0.000001); + // Check Gamma parameter + // Although this is a formula, all coefficients should be zero + // and so values should be exactly 0 as well + param = paramMap.get(&(*instr), "Gamma", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( fitParam.getValue( 0.0 ), 0.0); + TS_ASSERT_EQUALS( fitParam.getValue( 0.0 ), 0.0); + + + // Now check second workspace + ws = boost::dynamic_pointer_cast(gws->getItem(1)); + paramMap = ws->instrumentParameters(); + instr = ws->getInstrument(); + + // Check Alpha0 parameter + param = paramMap.get(&(*instr), "Alpha0", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 0.001); + // Check Alpha1 parameter + param = paramMap.get(&(*instr), "Alpha1", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 0.22); + // Check Beta0 parameter + param = paramMap.get(&(*instr), "Beta0", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 32.7927); + // Check Beta1 parameter + param = paramMap.get(&(*instr), "Kappa", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 52.4205); + // Check SigmsSquared parameter + // This is a formula, so values are not exact + param = paramMap.get(&(*instr), "SigmaSquared", "fitting"); + fitParam = param->value(); + TS_ASSERT_DELTA( fitParam.getValue(0.0), 0.04, 0.000001); + TS_ASSERT_DELTA( fitParam.getValue(0.5), 21840.741796, 0.000001); + // Check Gamma parameter + // Although this is a formula, all coefficients should be zero + // and so values should be exactly 0 as well + param = paramMap.get(&(*instr), "Gamma", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( fitParam.getValue( 0.0 ), 0.0); + TS_ASSERT_EQUALS( fitParam.getValue( 0.0 ), 0.0); + + // Clean + Poco::File("TestWorskpace.irf").remove(); + AnalysisDataService::Instance().remove("loadGSASInstrumentFileWorkspace"); + } + //---------------------------------------------------------------------------------------------- /** Parse a TableWorkspace to a map */ @@ -353,6 +460,28 @@ class LoadGSASInstrumentFileTest : public CxxTest::TestSuite return; } + //---------------------------------------------------------------------------------------------- + /** Create a workspace group with specified number of workspaces. + */ + void createWorkspaceGroup( size_t numberOfWorkspaces, std::string workspaceName) + { + // create a workspace with some sample data + WorkspaceGroup_sptr gws(new API::WorkspaceGroup); + + for (size_t i=0; i < numberOfWorkspaces; ++i) + { + Workspace_sptr ws = WorkspaceFactory::Instance().create("Workspace2D",1,1,1); + Workspace2D_sptr ws2D = boost::dynamic_pointer_cast(ws); + gws->addWorkspace( ws2D ); + } + + // put this workspace in the analysis data service + TS_ASSERT_THROWS_NOTHING(AnalysisDataService::Instance().add(workspaceName, gws)); + + // save workspace name + wsName = workspaceName; + } + /* Return the number of rows the table must have */ int getExpectedNumberOfRows() @@ -361,7 +490,7 @@ class LoadGSASInstrumentFileTest : public CxxTest::TestSuite } private: - std::string wsName; // For Workspace property + std::string wsName; // For workspace property }; From cbebfee4fe7e3502d0b6b257f38e8fd2102c2a5e Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Wed, 18 Feb 2015 10:37:31 +0100 Subject: [PATCH 252/414] Refs #11104. Moving PeakFunctionIntegrator to API PeakFunctionIntegrator was moved from MantidSINQ to MantidAPI. PoldiFitPeaks2D had to be changed to use the correct header file. --- Code/Mantid/Framework/API/CMakeLists.txt | 3 + .../inc/MantidAPI}/PeakFunctionIntegrator.h | 22 +-- .../src}/PeakFunctionIntegrator.cpp | 8 +- .../test/PeakFunctionIntegratorTest.h | 21 +- .../PoldiBatchFitIndividualPeaks.py | 181 ++++++++++++++++++ Code/Mantid/Framework/SINQ/CMakeLists.txt | 3 - .../Framework/SINQ/src/PoldiFitPeaks2D.cpp | 2 +- .../SINQ/src/PoldiIndexKnownCompounds.cpp | 1 - 8 files changed, 211 insertions(+), 30 deletions(-) rename Code/Mantid/Framework/{SINQ/inc/MantidSINQ/PoldiUtilities => API/inc/MantidAPI}/PeakFunctionIntegrator.h (74%) rename Code/Mantid/Framework/{SINQ/src/PoldiUtilities => API/src}/PeakFunctionIntegrator.cpp (97%) rename Code/Mantid/Framework/{SINQ => API}/test/PeakFunctionIntegratorTest.h (92%) create mode 100644 Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PoldiBatchFitIndividualPeaks.py diff --git a/Code/Mantid/Framework/API/CMakeLists.txt b/Code/Mantid/Framework/API/CMakeLists.txt index cc62a6115e29..c59fd55a43a5 100644 --- a/Code/Mantid/Framework/API/CMakeLists.txt +++ b/Code/Mantid/Framework/API/CMakeLists.txt @@ -93,6 +93,7 @@ set ( SRC_FILES src/ParamFunction.cpp src/ParameterReference.cpp src/ParameterTie.cpp + src/PeakFunctionIntegrator.cpp src/PeakTransform.cpp src/PeakTransformHKL.cpp src/PeakTransformQLab.cpp @@ -252,6 +253,7 @@ set ( INC_FILES inc/MantidAPI/ParamFunction.h inc/MantidAPI/ParameterReference.h inc/MantidAPI/ParameterTie.h + inc/MantidAPI/PeakFunctionIntegrator.h inc/MantidAPI/PeakTransform.h inc/MantidAPI/PeakTransformFactory.h inc/MantidAPI/PeakTransformHKL.h @@ -348,6 +350,7 @@ set ( TEST_FILES ParamFunctionAttributeHolderTest.h ParameterReferenceTest.h ParameterTieTest.h + PeakFunctionIntegratorTest.h PeakTransformHKLTest.h PeakTransformQLabTest.h PeakTransformQSampleTest.h diff --git a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h b/Code/Mantid/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h similarity index 74% rename from Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h rename to Code/Mantid/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h index c287ca1bf842..a191dd280707 100644 --- a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h +++ b/Code/Mantid/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h @@ -1,12 +1,12 @@ #ifndef PEAKFUNCTIONINTEGRATOR_H #define PEAKFUNCTIONINTEGRATOR_H -#include "MantidSINQ/DllConfig.h" +#include "MantidAPI/DllConfig.h" #include "MantidAPI/IPeakFunction.h" #include "gsl/gsl_integration.h" namespace Mantid { -namespace Poldi { +namespace API { /** PeakFunctionIntegrator : * @@ -37,7 +37,7 @@ namespace Poldi { Code Documentation is available at: */ -struct MANTID_SINQ_DLL IntegrationResult { +struct MANTID_API_DLL IntegrationResult { double result; double error; size_t intervals; @@ -46,7 +46,7 @@ struct MANTID_SINQ_DLL IntegrationResult { bool success; }; -class MANTID_SINQ_DLL PeakFunctionIntegrator { +class MANTID_API_DLL PeakFunctionIntegrator { public: PeakFunctionIntegrator(double requiredRelativePrecision = 1e-8); virtual ~PeakFunctionIntegrator(); @@ -55,27 +55,27 @@ class MANTID_SINQ_DLL PeakFunctionIntegrator { double requiredRelativePrecision() const; IntegrationResult - integrateInfinity(API::IPeakFunction_const_sptr peakFunction) const; + integrateInfinity(IPeakFunction_const_sptr peakFunction) const; IntegrationResult - integratePositiveInfinity(API::IPeakFunction_const_sptr peakFunction, + integratePositiveInfinity(IPeakFunction_const_sptr peakFunction, double lowerLimit) const; IntegrationResult - integrateNegativeInfinity(API::IPeakFunction_const_sptr peakFunction, + integrateNegativeInfinity(IPeakFunction_const_sptr peakFunction, double upperLimit) const; - IntegrationResult integrate(API::IPeakFunction_const_sptr peakFunction, + IntegrationResult integrate(IPeakFunction_const_sptr peakFunction, double lowerLimit, double upperLimit) const; protected: - gsl_function getGSLFunction(API::IPeakFunction_const_sptr peakFunction) const; - void throwIfInvalid(API::IPeakFunction_const_sptr peakFunction) const; + gsl_function getGSLFunction(IPeakFunction_const_sptr peakFunction) const; + void throwIfInvalid(IPeakFunction_const_sptr peakFunction) const; gsl_integration_workspace *m_integrationWorkspace; double m_relativePrecision; }; -double MANTID_SINQ_DLL gsl_peak_wrapper(double x, void *parameters); +double MANTID_API_DLL gsl_peak_wrapper(double x, void *parameters); } } diff --git a/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PeakFunctionIntegrator.cpp b/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp similarity index 97% rename from Code/Mantid/Framework/SINQ/src/PoldiUtilities/PeakFunctionIntegrator.cpp rename to Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp index 620b41e9237a..056af5b73fe9 100644 --- a/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PeakFunctionIntegrator.cpp +++ b/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp @@ -1,4 +1,4 @@ -#include "MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h" +#include "MantidAPI/PeakFunctionIntegrator.h" #include "MantidAPI/FunctionDomain1D.h" #include "gsl/gsl_errno.h" @@ -6,9 +6,7 @@ #include namespace Mantid { -namespace Poldi { - -using namespace API; +namespace API { /** Constructor with required relative precision argument. The default is 1e-8. * See also PeakFunctionIntegrator::setRequiredRelativePrecision. @@ -153,7 +151,7 @@ PeakFunctionIntegrator::integrate(IPeakFunction_const_sptr peakFunction, gsl_function PeakFunctionIntegrator::getGSLFunction( IPeakFunction_const_sptr peakFunction) const { gsl_function f; - f.function = &Mantid::Poldi::gsl_peak_wrapper; + f.function = &Mantid::API::gsl_peak_wrapper; f.params = &peakFunction; return f; diff --git a/Code/Mantid/Framework/SINQ/test/PeakFunctionIntegratorTest.h b/Code/Mantid/Framework/API/test/PeakFunctionIntegratorTest.h similarity index 92% rename from Code/Mantid/Framework/SINQ/test/PeakFunctionIntegratorTest.h rename to Code/Mantid/Framework/API/test/PeakFunctionIntegratorTest.h index 59b641d58fb3..96162318a7be 100644 --- a/Code/Mantid/Framework/SINQ/test/PeakFunctionIntegratorTest.h +++ b/Code/Mantid/Framework/API/test/PeakFunctionIntegratorTest.h @@ -2,14 +2,12 @@ #define PEAKFUNCTIONINTEGRATORTEST_H #include -#include "MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h" - -#include "MantidCurveFitting/Gaussian.h" -#include "MantidCurveFitting/Lorentzian.h" +#include "MantidAPI/PeakFunctionIntegrator.h" +#include "MantidAPI/FrameworkManager.h" +#include "MantidAPI/FunctionFactory.h" #include "gsl/gsl_errno.h" -using namespace Mantid::Poldi; using namespace Mantid::API; using namespace Mantid::CurveFitting; @@ -30,10 +28,15 @@ class TestablePeakFunctionIntegrator : public PeakFunctionIntegrator class PeakFunctionIntegratorTest : public CxxTest::TestSuite { private: + PeakFunctionIntegratorTest() + { + FrameworkManager::Instance(); + } + IPeakFunction_sptr getGaussian(double center, double fwhm, double height) { - IPeakFunction_sptr gaussian(new Gaussian); - gaussian->initialize(); + IPeakFunction_sptr gaussian = boost::dynamic_pointer_cast( + FunctionFactory::Instance().createFunction("Gaussian")); gaussian->setCentre(center); gaussian->setFwhm(fwhm); gaussian->setHeight(height); @@ -48,8 +51,8 @@ class PeakFunctionIntegratorTest : public CxxTest::TestSuite IPeakFunction_sptr getLorentzian(double center, double fwhm, double height) { - IPeakFunction_sptr lorentzian(new Lorentzian); - lorentzian->initialize(); + IPeakFunction_sptr lorentzian = boost::dynamic_pointer_cast( + FunctionFactory::Instance().createFunction("Lorentzian")); lorentzian->setCentre(center); lorentzian->setFwhm(fwhm); lorentzian->setHeight(height); diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PoldiBatchFitIndividualPeaks.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PoldiBatchFitIndividualPeaks.py new file mode 100644 index 000000000000..b77beeb9d17c --- /dev/null +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PoldiBatchFitIndividualPeaks.py @@ -0,0 +1,181 @@ +from mantid.api import * +from mantid.kernel import * +from mantid.simpleapi import * +import os +import math +import sys + +class PoldiSample: + def __init__(self, initString): + self._name, self._runList = self.parseInitString(initString) + + def name(self): + return self._name + + def runList(self): + return self._runList + + def runNames(self): + return [x[0] for x in self._runList] + + def parseInitString(self, initString): + parts = initString.split(':') + + if not len(parts) == 2: + raise RuntimeError("Unable to parse init string.") + + sampleName = parts[0] + runDict = self.parseRunDictString(parts[1]) + + return (sampleName, runDict) + + def parseRunDictString(self, runDictString): + runRanges = filter(bool, runDictString.strip().split(';')) + + newRunList = [] + for runRange in runRanges: + runPoints = self.parseRunRangeString(runRange) + newRunList += runPoints + + return newRunList + + def parseRunRangeString(self, runRangeString): + runRangeParameters = [int(x) for x in runRangeString.split(',')] + + if not len(runRangeParameters) == 3: + raise RuntimeError("Unable to parse run range string.") + + begin, end, step = runRangeParameters + + runList = [] + for i in range(begin, end + 1, step): + runList.append((i + step - 1, [str(x) for x in range(i, i + step)])) + + print runList + + return runList + +class PoldiProject: + def __init__(self, projectName, sampleListFile): + self._name = projectName + self._sampleList = self.parseSampleListFile(sampleListFile) + + def sampleList(self): + return self._sampleList + + def name(self): + return self._name + + def parseSampleListFile(self, sampleListFile): + fh = open(sampleListFile, 'r') + + sampleList = [] + for line in fh: + if len(line.strip()) > 0 and not line.strip()[0] == '#': + sampleList.append(PoldiSample(line)) + + return sampleList + +class PoldiBatchFitIndividualPeaks(PythonAlgorithm): + prefixes = {'raw': 'raw_', + 'data': 'data_'} + + suffixes = {'correlation': '_correlation', + 'raw_peaks': '_peaks_raw', + 'fit_peaks_1d': '_peaks_fit_1d', + 'fit_peaks_2d': '_peaks_fit_2d', + 'calculated_2d': '_spectrum_fitted_2d', + 'residuals': '_residuals'} + + def category(self): + return "Workflow\\Poldi" + + def name(self): + return "PoldiBatchFitIndividualPeaks" + + def summary(self): + return "Load a file with instructions for batch processing POLDI fits." + + def PyInit(self): + self.declareProperty("ProjectName", "", "Project name to use for labeling") + self.declareProperty(FileProperty(name="SampleListFile", defaultValue="", + action=FileAction.Load)) + self.declareProperty(FileProperty(name="OutputDirectory", defaultValue="", + action=FileAction.OptionalDirectory)) + self.declareProperty(FileProperty(name="CrystalStructures", + defaultValue="", + action=FileAction.OptionalLoad)) + self.declareProperty("PeakNumber", 10, "Number of peaks to fit.") + + def PyExec(self): + poldiProject = PoldiProject(self.getProperty("ProjectName"), + self.getProperty("SampleListFile").valueAsStr) + + sampleCount = len(poldiProject.sampleList()) + progress = Progress(self, start=0.0, end=1.0, nreports=sampleCount) + + for i, sample in enumerate(poldiProject.sampleList()): + self.processSample(sample) + progress.report("Processed sample " + str(i + 1) + " of " + str(sampleCount)) + + def processSample(self, poldiSample): + sampleList = poldiSample.runList() + + for dataPoint in sampleList: + self.processDataPoint(dataPoint) + + def processDataPoint(self, dataPointTuple): + self.loadDataPoint(dataPointTuple) + self.runPoldiAnalysis(dataPointTuple[0]) + + def loadDataPoint(self, dataPointTuple): + dataWorkspaceName = self.prefixes['data'] + str(dataPointTuple[0]) + + rawWorkspaceNames = [ + self.prefixes['raw'] + str(x) for x in dataPointTuple[1]] + + for numor,rawWsName in zip(dataPointTuple[1], rawWorkspaceNames): + LoadSINQ(Instrument="POLDI", Year=2014, + Numor=numor, OutputWorkspace=rawWsName) + LoadInstrument(rawWsName, InstrumentName="POLDI") + + if len(dataPointTuple[1]) > 1: + PoldiMerge(rawWorkspaceNames, OutputWorkspace=dataWorkspaceName) + + for ws in rawWorkspaceNames: + DeleteWorkspace(ws) + + else: + RenameWorkspace(rawWorkspaceNames[0], OutputWorkspace=dataWorkspaceName) + + return dataWorkspaceName + + def runPoldiAnalysis(self, dataPointName): + dataWorkspaceName = self.prefixes['data'] + str(dataPointName) + + correlationWsName = dataWorkspaceName + self.suffixes['correlation'] + PoldiAutoCorrelation(dataWorkspaceName, wlenmin=1.1, wlenmax=5.0, + OutputWorkspace=correlationWsName) + + peakSearchWsName = dataWorkspaceName + self.suffixes['raw_peaks'] + PoldiPeakSearch(correlationWsName, OutputWorkspace=peakSearchWsName) + + DeleteTableRows(peakSearchWsName, + self.getProperty("PeakNumber").valueAsStr + '-30') + + peakFit1DWsName = dataWorkspaceName + self.suffixes['fit_peaks_1d'] + PoldiFitPeaks1D(correlationWsName, PoldiPeakTable=peakSearchWsName, + OutputWorkspace=peakFit1DWsName) + + peakFit2DWsName = dataWorkspaceName + self.suffixes['fit_peaks_2d'] + spectrum2DCalc = dataWorkspaceName + self.suffixes['calculated_2d'] + PoldiFitPeaks2D(dataWorkspaceName, PoldiPeakWorkspace=peakFit1DWsName, + MaximumIterations=100, OutputWorkspace=spectrum2DCalc, + RefinedPoldiPeakWorkspace=peakFit2DWsName) + + residualsWsName = dataWorkspaceName + self.suffixes['residuals'] + PoldiAnalyseResiduals(dataWorkspaceName, spectrum2DCalc, + OutputWorkspace=residualsWsName, + MaxIterations=5) + +AlgorithmFactory.subscribe(PoldiBatchFitIndividualPeaks) \ No newline at end of file diff --git a/Code/Mantid/Framework/SINQ/CMakeLists.txt b/Code/Mantid/Framework/SINQ/CMakeLists.txt index c308ea296586..2cf113c7486f 100644 --- a/Code/Mantid/Framework/SINQ/CMakeLists.txt +++ b/Code/Mantid/Framework/SINQ/CMakeLists.txt @@ -20,7 +20,6 @@ set ( SRC_FILES src/PoldiTruncateData.cpp src/PoldiUtilities/IPoldiFunction1D.cpp src/PoldiUtilities/MillerIndices.cpp - src/PoldiUtilities/PeakFunctionIntegrator.cpp src/PoldiUtilities/Poldi2DFunction.cpp src/PoldiUtilities/PoldiAutoCorrelationCore.cpp src/PoldiUtilities/PoldiBasicChopper.cpp @@ -71,7 +70,6 @@ set ( INC_FILES inc/MantidSINQ/PoldiUtilities/IPoldiFunction1D.h inc/MantidSINQ/PoldiUtilities/MillerIndices.h inc/MantidSINQ/PoldiUtilities/MillerIndicesIO.h - inc/MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h inc/MantidSINQ/PoldiUtilities/Poldi2DFunction.h inc/MantidSINQ/PoldiUtilities/PoldiAbstractChopper.h inc/MantidSINQ/PoldiUtilities/PoldiAbstractDetector.h @@ -107,7 +105,6 @@ set ( TEST_FILES MDHistoToWorkspace2DTest.h MillerIndicesIOTest.h MillerIndicesTest.h - PeakFunctionIntegratorTest.h Poldi2DFunctionTest.h PoldiAnalyseResidualsTest.h PoldiAutoCorrelationCoreTest.h diff --git a/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp b/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp index 6653f1c3cfbc..498f73ef7e27 100644 --- a/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp +++ b/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp @@ -18,7 +18,7 @@ use the Build/wiki_maker.py script to generate your full wiki page. #include "MantidSINQ/PoldiUtilities/PoldiPeakCollection.h" #include "MantidSINQ/PoldiUtilities/PoldiInstrumentAdapter.h" #include "MantidSINQ/PoldiUtilities/PoldiDeadWireDecorator.h" -#include "MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h" +#include "MantidAPI/PeakFunctionIntegrator.h" #include "MantidAPI/IPeakFunction.h" #include "MantidSINQ/PoldiUtilities/Poldi2DFunction.h" diff --git a/Code/Mantid/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp b/Code/Mantid/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp index 4f33df0617b0..ee0bf9f4dd06 100644 --- a/Code/Mantid/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp +++ b/Code/Mantid/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp @@ -1,5 +1,4 @@ #include "MantidSINQ/PoldiIndexKnownCompounds.h" -#include "MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h" #include "MantidKernel/ArrayProperty.h" #include "MantidKernel/MandatoryValidator.h" From 3d01a3f714b9d4eea7a7df4f6ae2ca1818e78e8a Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Wed, 18 Feb 2015 10:42:08 +0100 Subject: [PATCH 253/414] Refs #11104. Fixing doxygen comments --- .../inc/MantidAPI/PeakFunctionIntegrator.h | 5 +++- .../API/src/PeakFunctionIntegrator.cpp | 29 +++++++++---------- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h b/Code/Mantid/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h index a191dd280707..b1f6b71b83a8 100644 --- a/Code/Mantid/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h +++ b/Code/Mantid/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h @@ -13,10 +13,13 @@ namespace API { General integration of peaks (in the form of IPeakFunction) by wrapping the corresponding GSL-functions. Integration with infinity limits is supported. + PeakFunctionIntegrator allocates a GSL integration workspace on construction + and frees the memory when it's destroyed. + @author Michael Wedel, Paul Scherrer Institut - SINQ @date 24/04/2014 - Copyright © 2014 PSI-MSS + Copyright © 2014,2015 PSI-MSS This file is part of Mantid. diff --git a/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp b/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp index 056af5b73fe9..cc3673b46f3c 100644 --- a/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp +++ b/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp @@ -45,12 +45,11 @@ double PeakFunctionIntegrator::requiredRelativePrecision() const { } /** Integration of peak function on the interval [-Inf, +Inf]. Internally, - *gsl_integration_qagi is used - * for this. If a default constructed IPeakFunction_const_sptr is passed to the - *function, std::invalid_argument is thrown. - * The results are returned as IntegrationResult-struct, which contains the - *approximation of the integral along - * with other information such as an error estimate (absolute). + * gsl_integration_qagi is used for this. If a default constructed + * IPeakFunction_const_sptr is passed to the function, + * std::invalid_argument is thrown. The results are returned as + * IntegrationResult-struct, which contains the approximation of the integral + * along with other information such as an error estimate (absolute). * * @param peakFunction :: Peak function to integrate. */ @@ -72,9 +71,9 @@ IntegrationResult PeakFunctionIntegrator::integrateInfinity( } /** Integration of peak function on the interval [a, +Inf]. Internally, - *gsl_integration_qagiu is used - * for this. If a default constructed IPeakFunction_const_sptr is passed to the - *function, std::invalid_argument is thrown. + * gsl_integration_qagiu is used for this. If a default constructed + * IPeakFunction_const_sptr is passed to the function, + * std::invalid_argument is thrown. * * @param peakFunction :: Peak function to integrate. */ @@ -96,9 +95,9 @@ IntegrationResult PeakFunctionIntegrator::integratePositiveInfinity( } /** Integration of peak function on the interval [-Inf, b]. Internally, - *gsl_integration_qagil is used - * for this. If a default constructed IPeakFunction_const_sptr is passed to the - *function, std::invalid_argument is thrown. + * gsl_integration_qagil is used for this. If a default constructed + * IPeakFunction_const_sptr is passed to the function, + * std::invalid_argument is thrown. * * @param peakFunction :: Peak function to integrate. */ @@ -120,9 +119,9 @@ IntegrationResult PeakFunctionIntegrator::integrateNegativeInfinity( } /** Integration of peak function on the interval [a, b]. Internally, - *gsl_integration_qags is used - * for this. If a default constructed IPeakFunction_const_sptr is passed to the - *function, std::invalid_argument is thrown. + * gsl_integration_qags is used for this. If a default constructed + * IPeakFunction_const_sptr is passed to the function, + * std::invalid_argument is thrown. * * @param peakFunction :: Peak function to integrate. */ From eeea9bad4973c009e3ce0e371fa826380a95fd35 Mon Sep 17 00:00:00 2001 From: Roman Tolchenov Date: Wed, 18 Feb 2015 09:43:17 +0000 Subject: [PATCH 254/414] Re #11059. Added ISIS-specific properties to StartLiveData. --- .../inc/MantidLiveData/StartLiveData.h | 1 - .../Framework/LiveData/src/StartLiveData.cpp | 46 +++++------- .../source/algorithms/StartLiveData-v1.rst | 74 ++++++++++++++++++- 3 files changed, 88 insertions(+), 33 deletions(-) diff --git a/Code/Mantid/Framework/LiveData/inc/MantidLiveData/StartLiveData.h b/Code/Mantid/Framework/LiveData/inc/MantidLiveData/StartLiveData.h index a7c0c4b25230..fcd7bd1db9f9 100644 --- a/Code/Mantid/Framework/LiveData/inc/MantidLiveData/StartLiveData.h +++ b/Code/Mantid/Framework/LiveData/inc/MantidLiveData/StartLiveData.h @@ -59,7 +59,6 @@ class DLLExport StartLiveData : public LiveDataAlgorithm { private: void init(); void exec(); - void afterPropertySet(const std::string &); }; } // namespace LiveData diff --git a/Code/Mantid/Framework/LiveData/src/StartLiveData.cpp b/Code/Mantid/Framework/LiveData/src/StartLiveData.cpp index 1b44d91e750f..c890cac2ab60 100644 --- a/Code/Mantid/Framework/LiveData/src/StartLiveData.cpp +++ b/Code/Mantid/Framework/LiveData/src/StartLiveData.cpp @@ -6,6 +6,8 @@ #include "MantidAPI/AlgorithmProxy.h" #include "MantidAPI/AlgorithmProperty.h" #include "MantidAPI/LiveListenerFactory.h" +#include "MantidKernel/ArrayProperty.h" +#include "MantidKernel/ArrayBoundedValidator.h" #include @@ -65,6 +67,21 @@ void StartLiveData::init() { "If you specify 0, MonitorLiveData will not launch and you will get only " "one chunk."); + // Properties used with ISISHistoDataListener + declareProperty(new ArrayProperty("SpectraList"), + "An optional list of spectra to load. If blank, all " + "available spectra will be loaded. Applied to ISIS histogram" + " data only."); + getPointerToProperty("SpectraList")->setGroup(listenerPropertyGroup); + + auto validator = boost::make_shared>(); + validator->setLower(1); + declareProperty(new ArrayProperty("PeriodList", validator), + "An optional list of periods to load. If blank, all " + "available periods will be loaded. Applied to ISIS histogram" + " data only."); + getPointerToProperty("PeriodList")->setGroup(listenerPropertyGroup); + // Initialize the properties common to LiveDataAlgorithm. initProps(); @@ -190,34 +207,5 @@ void StartLiveData::exec() { } } -/** - * After Instrument property is set copy any properties that the instrument's - * listener may have to this algorithm. - */ -void StartLiveData::afterPropertySet(const std::string &propName) { - if (propName == "Instrument") { - // remove old listener's properties - auto properties = getProperties(); - for (auto prop = properties.begin(); prop != properties.end(); ++prop) { - if ((**prop).getGroup() == listenerPropertyGroup) { - removeProperty((**prop).name()); - } - } - // add new listener's properties - auto listener = LiveListenerFactory::Instance().create( - getPropertyValue(propName), false); - auto propertyManagerListener = - boost::dynamic_pointer_cast(listener); - if (propertyManagerListener) { - auto properties = propertyManagerListener->getProperties(); - for (auto prop = properties.begin(); prop != properties.end(); ++prop) { - propertyManagerListener->removeProperty((**prop).name(), false); - declareProperty(*prop); - (**prop).setGroup(listenerPropertyGroup); - } - } - } -} - } // namespace LiveData } // namespace Mantid diff --git a/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst b/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst index fc238c47314c..8469b83b2e82 100644 --- a/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst +++ b/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst @@ -77,9 +77,9 @@ you can do by your available memory and CPUs. Usage ----- -**Example:** +**Example 1:** -.. testcode:: exStartLiveData +.. testcode:: exStartLiveDataEvent from threading import Thread import time @@ -135,9 +135,77 @@ Usage Output: -.. testoutput:: exStartLiveData +.. testoutput:: exStartLiveDataEvent :options: +ELLIPSIS, +NORMALIZE_WHITESPACE The workspace contains ... events + + +**Example 2:** + +.. testcode:: exStartLiveDataisto + + from threading import Thread + import time + + def startFakeDAE(): + # This will generate 5 periods of histogram data, 10 spectra in each period, + # 100 bins in each spectrum + try: + FakeISISHistoDAE(NPeriods=5,NSpectra=10,NBins=100) + except RuntimeError: + pass + + def captureLive(): + ConfigService.setFacility("TEST_LIVE") + + # Start a Live data listener updating every second, + # that replaces the results each time with those of the last second. + # Load only spectra 2,4, and 6 from periods 1 and 3 + StartLiveData(Instrument='ISIS_Histogram', OutputWorkspace='wsOut', UpdateEvery=1, + AccumulationMethod='Replace', PeriodList=[1,3],SpectraList=[2,4,6]) + + # give it a couple of seconds before stopping it + time.sleep(2) + + # This will cancel both algorithms + # you can do the same in the GUI + # by clicking on the details button on the bottom right + AlgorithmManager.newestInstanceOf("MonitorLiveData").cancel() + AlgorithmManager.newestInstanceOf("FakeISISHistoDAE").cancel() + #-------------------------------------------------------------------------------------------------- + + oldFacility = ConfigService.getFacility().name() + thread = Thread(target = startFakeDAE) + thread.start() + time.sleep(2) # give it a small amount of time to get ready + if not thread.is_alive(): + raise RuntimeError("Unable to start FakeDAE") + + try: + captureLive() + except Exception, exc: + print "Error occurred starting live data" + finally: + thread.join() # this must get hit + + # put back the facility + ConfigService.setFacility(oldFacility) + + #get the ouput workspace + wsOut = mtd["wsOut"] + print "The workspace contains %i periods" % wsOut.getNumberOfEntries() + print "Each period contains %i spectra" % wsOut.getItem(0).getNumberHistograms() + + +Output: + +.. testoutput:: exStartLiveDataHisto + :options: +ELLIPSIS, +NORMALIZE_WHITESPACE + + The workspace contains ... periods + Each period contains ... spectra + + .. categories:: From 83b7389e874ed6568832546adef88453e3468af7 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Wed, 18 Feb 2015 10:17:24 +0000 Subject: [PATCH 255/414] Re #10862 Updating documentation --- .../algorithms/LoadGSASInstrumentFile-v1.rst | 52 ++++++++++++++++--- 1 file changed, 45 insertions(+), 7 deletions(-) diff --git a/Code/Mantid/docs/source/algorithms/LoadGSASInstrumentFile-v1.rst b/Code/Mantid/docs/source/algorithms/LoadGSASInstrumentFile-v1.rst index 4783efc33ea0..7e1340f2dfcb 100644 --- a/Code/Mantid/docs/source/algorithms/LoadGSASInstrumentFile-v1.rst +++ b/Code/Mantid/docs/source/algorithms/LoadGSASInstrumentFile-v1.rst @@ -9,12 +9,9 @@ Description ----------- -Load parameters from a GSAS instrument file into a table workspace +Load Ikeda-Carpenter PV parameters from a GSAS instrument file into a table workspace or a workspace group. -Later developments of this algorithm will enable these parameters to be -put into the instrument of a wotrkspace for either Ikeda-Carpender -pseudo-Voigt translated into :ref:`IkedaCarpenterPV ` or -back-to-back-exponential pseudo-Voigt translated into +Later developments of this algorithm will enable to load back-to-back-exponential pseudo-Voigt parameters translated into :ref:`BackToBackExponential `. @@ -28,8 +25,6 @@ Usage .. testcode:: ExLoadGSASInstrumentFileSimple # We load a GSAS Instrument file with 2 Banks - # which will suit MUSR00015189 at a later stage of devolpment - tws = LoadGSASInstrumentFile("GSAS_2bank.prm") #Print first four rows @@ -46,4 +41,47 @@ Output: {'Name': 'Alph1','Value_1': 0.21, 'Value_2': 0.22} {'Name': 'Beta0','Value_1': 31.79, 'Value_2': 31.79} + +**Example - Run LoadGSASInstrumentFile and put parameters into workspace** + +.. include:: ../usagedata-note.txt + +.. testcode:: ExLoadGSASInstrumentFileWorkspace + + # First we load MUSR00015189 workspace group + Load("MUSR00015189",OutputWorkspace="groupWs") + groupWs=mtd["groupWs"] + # We clear instrument parameters... + ClearInstrumentParameters(groupWs) + + # ...and check they do not exist + instrument = groupWs.getItem(0).getInstrument() + print "Alpha0 parameter exists: ", instrument.hasParameter("Alpha0") + print "Beta0 parameter exists: ", instrument.hasParameter("Beta0") + print "SigmaSquared parameter exists: " , instrument.hasParameter("SigmaSquared") + + # Now we load a GSAS Instrument file with 2 Banks into the workspace... + print "\nLoading parameters from GSAS\n" + tws = LoadGSASInstrumentFile(Filename="GSAS_2bank.prm",UseBankIDsInFile=True,Workspace=groupWs,Banks=[1,2]) + + # ...and check parameters are there again + instrument = groupWs.getItem(0).getInstrument() + print "Alpha0 parameter exists: ", instrument.hasParameter("Alpha0") + print "Beta0 parameter exists: ", instrument.hasParameter("Beta0") + print "SigmaSquared parameter exists: " , instrument.hasParameter("SigmaSquared") + +Output: + +.. testoutput:: ExLoadGSASInstrumentFileWorkspace + + Alpha0 parameter exists: False + Beta0 parameter exists: False + SigmaSquared parameter exists: False + + Loading parameters from GSAS + + Alpha0 parameter exists: True + Beta0 parameter exists: True + SigmaSquared parameter exists: True + .. categories:: From 3be3b0e8a6b427fd903460d9d1e1604474091e22 Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Wed, 18 Feb 2015 11:19:01 +0100 Subject: [PATCH 256/414] Refs #11104. Changing signatures of PeakFunctionIntegrator The interface is not limited to smart pointers anymore now, using references instead. --- .../inc/MantidAPI/PeakFunctionIntegrator.h | 11 ++-- .../API/src/PeakFunctionIntegrator.cpp | 53 ++++++------------- .../API/test/PeakFunctionIntegratorTest.h | 29 ++++------ .../Framework/SINQ/src/PoldiFitPeaks2D.cpp | 2 +- 4 files changed, 32 insertions(+), 63 deletions(-) diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h b/Code/Mantid/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h index b1f6b71b83a8..f07e262b1843 100644 --- a/Code/Mantid/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h +++ b/Code/Mantid/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h @@ -58,20 +58,19 @@ class MANTID_API_DLL PeakFunctionIntegrator { double requiredRelativePrecision() const; IntegrationResult - integrateInfinity(IPeakFunction_const_sptr peakFunction) const; + integrateInfinity(const IPeakFunction &peakFunction) const; IntegrationResult - integratePositiveInfinity(IPeakFunction_const_sptr peakFunction, + integratePositiveInfinity(const IPeakFunction &peakFunction, double lowerLimit) const; IntegrationResult - integrateNegativeInfinity(IPeakFunction_const_sptr peakFunction, + integrateNegativeInfinity(const IPeakFunction &peakFunction, double upperLimit) const; - IntegrationResult integrate(IPeakFunction_const_sptr peakFunction, + IntegrationResult integrate(const IPeakFunction &peakFunction, double lowerLimit, double upperLimit) const; protected: - gsl_function getGSLFunction(IPeakFunction_const_sptr peakFunction) const; - void throwIfInvalid(IPeakFunction_const_sptr peakFunction) const; + gsl_function getGSLFunction(const IPeakFunction &peakFunction) const; gsl_integration_workspace *m_integrationWorkspace; diff --git a/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp b/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp index cc3673b46f3c..75fcc48e3c40 100644 --- a/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp +++ b/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp @@ -29,8 +29,7 @@ PeakFunctionIntegrator::~PeakFunctionIntegrator() { } /** This method sets the desired numerical relative precision that's passed on - *to the - * GSL integration-routines. + * to the GSL integration-routines. * * @param newPrecision :: Desired relative precision for integrations. */ @@ -45,18 +44,14 @@ double PeakFunctionIntegrator::requiredRelativePrecision() const { } /** Integration of peak function on the interval [-Inf, +Inf]. Internally, - * gsl_integration_qagi is used for this. If a default constructed - * IPeakFunction_const_sptr is passed to the function, - * std::invalid_argument is thrown. The results are returned as + * gsl_integration_qagi is used for this. The results are returned as * IntegrationResult-struct, which contains the approximation of the integral * along with other information such as an error estimate (absolute). * * @param peakFunction :: Peak function to integrate. */ IntegrationResult PeakFunctionIntegrator::integrateInfinity( - IPeakFunction_const_sptr peakFunction) const { - throwIfInvalid(peakFunction); - + const IPeakFunction &peakFunction) const { IntegrationResult result; gsl_function f = getGSLFunction(peakFunction); @@ -71,16 +66,12 @@ IntegrationResult PeakFunctionIntegrator::integrateInfinity( } /** Integration of peak function on the interval [a, +Inf]. Internally, - * gsl_integration_qagiu is used for this. If a default constructed - * IPeakFunction_const_sptr is passed to the function, - * std::invalid_argument is thrown. + * gsl_integration_qagiu is used for this. * * @param peakFunction :: Peak function to integrate. */ IntegrationResult PeakFunctionIntegrator::integratePositiveInfinity( - IPeakFunction_const_sptr peakFunction, double lowerLimit) const { - throwIfInvalid(peakFunction); - + const IPeakFunction &peakFunction, double lowerLimit) const { IntegrationResult result; gsl_function f = getGSLFunction(peakFunction); @@ -95,16 +86,12 @@ IntegrationResult PeakFunctionIntegrator::integratePositiveInfinity( } /** Integration of peak function on the interval [-Inf, b]. Internally, - * gsl_integration_qagil is used for this. If a default constructed - * IPeakFunction_const_sptr is passed to the function, - * std::invalid_argument is thrown. + * gsl_integration_qagil is used for this. * * @param peakFunction :: Peak function to integrate. */ IntegrationResult PeakFunctionIntegrator::integrateNegativeInfinity( - IPeakFunction_const_sptr peakFunction, double upperLimit) const { - throwIfInvalid(peakFunction); - + const IPeakFunction &peakFunction, double upperLimit) const { IntegrationResult result; gsl_function f = getGSLFunction(peakFunction); @@ -119,17 +106,13 @@ IntegrationResult PeakFunctionIntegrator::integrateNegativeInfinity( } /** Integration of peak function on the interval [a, b]. Internally, - * gsl_integration_qags is used for this. If a default constructed - * IPeakFunction_const_sptr is passed to the function, - * std::invalid_argument is thrown. + * gsl_integration_qags is used for this. * * @param peakFunction :: Peak function to integrate. */ IntegrationResult -PeakFunctionIntegrator::integrate(IPeakFunction_const_sptr peakFunction, +PeakFunctionIntegrator::integrate(const IPeakFunction &peakFunction, double lowerLimit, double upperLimit) const { - throwIfInvalid(peakFunction); - IntegrationResult result; gsl_function f = getGSLFunction(peakFunction); @@ -148,24 +131,22 @@ PeakFunctionIntegrator::integrate(IPeakFunction_const_sptr peakFunction, * @param peakFunction :: Peak function to wrap. */ gsl_function PeakFunctionIntegrator::getGSLFunction( - IPeakFunction_const_sptr peakFunction) const { + const IPeakFunction &peakFunction) const { gsl_function f; f.function = &Mantid::API::gsl_peak_wrapper; - f.params = &peakFunction; + f.params = + reinterpret_cast(&const_cast(peakFunction)); return f; } -void PeakFunctionIntegrator::throwIfInvalid( - IPeakFunction_const_sptr peakFunction) const { +double gsl_peak_wrapper(double x, void *parameters) { + IPeakFunction *peakFunction = reinterpret_cast(parameters); + if (!peakFunction) { - throw std::invalid_argument("Can not integrate NULL-function."); + throw std::runtime_error( + "Cannot process NULL-pointer in gsl_peak_wrapper."); } -} - -double gsl_peak_wrapper(double x, void *parameters) { - IPeakFunction_const_sptr peakFunction = - *(IPeakFunction_const_sptr *)parameters; double y; diff --git a/Code/Mantid/Framework/API/test/PeakFunctionIntegratorTest.h b/Code/Mantid/Framework/API/test/PeakFunctionIntegratorTest.h index 96162318a7be..49c3be3b83e4 100644 --- a/Code/Mantid/Framework/API/test/PeakFunctionIntegratorTest.h +++ b/Code/Mantid/Framework/API/test/PeakFunctionIntegratorTest.h @@ -99,18 +99,7 @@ class PeakFunctionIntegratorTest : public CxxTest::TestSuite { IPeakFunction_sptr gaussian = getGaussian(0.0, 1.0, 2.0); - TS_ASSERT_EQUALS(gsl_peak_wrapper(0.0, &gaussian), 2.0); - } - - void testNullPointer() - { - PeakFunctionIntegrator integrator; - - TS_ASSERT_THROWS(integrator.integrateInfinity(IPeakFunction_sptr()), std::invalid_argument); - TS_ASSERT_THROWS(integrator.integratePositiveInfinity(IPeakFunction_sptr(), 0.0), std::invalid_argument); - TS_ASSERT_THROWS(integrator.integrateNegativeInfinity(IPeakFunction_sptr(), 0.0), std::invalid_argument); - TS_ASSERT_THROWS(integrator.integrate(IPeakFunction_sptr(), 0.0, 0.0), std::invalid_argument); - + TS_ASSERT_EQUALS(gsl_peak_wrapper(0.0, &(*gaussian)), 2.0); } void testIntegrateInfinityGaussian() @@ -118,13 +107,13 @@ class PeakFunctionIntegratorTest : public CxxTest::TestSuite IPeakFunction_sptr gaussian = getGaussian(0.0, 1.0, 1.0); PeakFunctionIntegrator integrator; - IntegrationResult result = integrator.integrateInfinity(gaussian); + IntegrationResult result = integrator.integrateInfinity(*gaussian); TS_ASSERT_EQUALS(result.errorCode, static_cast(GSL_SUCCESS)); TS_ASSERT_DELTA(result.result, getGaussianAnalyticalInfiniteIntegral(gaussian), integrator.requiredRelativePrecision()); TS_ASSERT_DELTA(result.error, 0.0, integrator.requiredRelativePrecision()); integrator.setRequiredRelativePrecision(1e-14); - IntegrationResult otherResult = integrator.integrateInfinity(gaussian); + IntegrationResult otherResult = integrator.integrateInfinity(*gaussian); TS_ASSERT_EQUALS(otherResult.errorCode, static_cast(GSL_EBADTOL)); TS_ASSERT_EQUALS(otherResult.result, 0.0); TS_ASSERT_EQUALS(otherResult.error, 0.0); @@ -134,7 +123,7 @@ class PeakFunctionIntegratorTest : public CxxTest::TestSuite { IPeakFunction_sptr gaussian = getGaussian(0.0, 1.0, 1.0); PeakFunctionIntegrator integrator; - IntegrationResult result = integrator.integratePositiveInfinity(gaussian, 0.0); + IntegrationResult result = integrator.integratePositiveInfinity(*gaussian, 0.0); TS_ASSERT_EQUALS(result.errorCode, static_cast(GSL_SUCCESS)); TS_ASSERT_DELTA(result.result, getGaussianAnalyticalInfiniteIntegral(gaussian) / 2.0, integrator.requiredRelativePrecision()); @@ -144,7 +133,7 @@ class PeakFunctionIntegratorTest : public CxxTest::TestSuite { IPeakFunction_sptr gaussian = getGaussian(0.0, 1.0, 1.0); PeakFunctionIntegrator integrator; - IntegrationResult result = integrator.integrateNegativeInfinity(gaussian, 0.0); + IntegrationResult result = integrator.integrateNegativeInfinity(*gaussian, 0.0); TS_ASSERT_EQUALS(result.errorCode, static_cast(GSL_SUCCESS)); TS_ASSERT_DELTA(result.result, getGaussianAnalyticalInfiniteIntegral(gaussian) / 2.0, integrator.requiredRelativePrecision()); @@ -161,15 +150,15 @@ class PeakFunctionIntegratorTest : public CxxTest::TestSuite IPeakFunction_sptr gaussian = getGaussian(0.0, 2.0 * sqrt(2.0 * log(2.0)), 1.0 / sqrt(2.0 * M_PI)); PeakFunctionIntegrator integrator(1e-10); - IntegrationResult rOneSigma = integrator.integrate(gaussian, -1.0, 1.0); + IntegrationResult rOneSigma = integrator.integrate(*gaussian, -1.0, 1.0); TS_ASSERT_EQUALS(rOneSigma.errorCode, static_cast(GSL_SUCCESS)); TS_ASSERT_DELTA(rOneSigma.result, 0.682689492137086, integrator.requiredRelativePrecision()); - IntegrationResult rTwoSigma = integrator.integrate(gaussian, -2.0, 2.0); + IntegrationResult rTwoSigma = integrator.integrate(*gaussian, -2.0, 2.0); TS_ASSERT_EQUALS(rTwoSigma.errorCode, static_cast(GSL_SUCCESS)); TS_ASSERT_DELTA(rTwoSigma.result, 0.954499736103642, integrator.requiredRelativePrecision()); - IntegrationResult rThreeSigma = integrator.integrate(gaussian, -3.0, 3.0); + IntegrationResult rThreeSigma = integrator.integrate(*gaussian, -3.0, 3.0); TS_ASSERT_EQUALS(rThreeSigma.errorCode, static_cast(GSL_SUCCESS)); TS_ASSERT_DELTA(rThreeSigma.result, 0.997300203936740, integrator.requiredRelativePrecision()); } @@ -179,7 +168,7 @@ class PeakFunctionIntegratorTest : public CxxTest::TestSuite IPeakFunction_sptr lorentzian = getLorentzian(0.0, 3.0, 8.0); PeakFunctionIntegrator integrator(1e-8); - IntegrationResult result = integrator.integrateInfinity(lorentzian); + IntegrationResult result = integrator.integrateInfinity(*lorentzian); TS_ASSERT_EQUALS(result.errorCode, static_cast(GSL_SUCCESS)); TS_ASSERT_DELTA(result.result, getLorentzianAnalyticalInfiniteIntegral(lorentzian), integrator.requiredRelativePrecision()); TS_ASSERT_LESS_THAN(result.intervals, 1000); diff --git a/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp b/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp index 498f73ef7e27..2f5ab76ffb23 100644 --- a/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp +++ b/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp @@ -571,7 +571,7 @@ PoldiPeakCollection_sptr PoldiFitPeaks2D::getIntegratedPeakCollection( profileFunction->setCentre(0.0); IntegrationResult integration = - peakIntegrator.integrateInfinity(profileFunction); + peakIntegrator.integrateInfinity(*profileFunction); if (!integration.success) { throw std::runtime_error("Problem during peak integration. Aborting."); From 717bb9cf53f937d6bd54c9c7a84518c728250c62 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Wed, 18 Feb 2015 11:07:41 +0000 Subject: [PATCH 257/414] refs #11056. Tracked down CrystalTest issues --- Code/Mantid/Framework/Crystal/test/PeaksOnSurfaceTest.h | 4 ++-- .../Framework/TestHelpers/src/WorkspaceCreationHelper.cpp | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Code/Mantid/Framework/Crystal/test/PeaksOnSurfaceTest.h b/Code/Mantid/Framework/Crystal/test/PeaksOnSurfaceTest.h index 7e2fa007ee98..239a663dfe7e 100644 --- a/Code/Mantid/Framework/Crystal/test/PeaksOnSurfaceTest.h +++ b/Code/Mantid/Framework/Crystal/test/PeaksOnSurfaceTest.h @@ -33,7 +33,7 @@ class PeaksOnSurfaceTest : public CxxTest::TestSuite Mantid::Kernel::V3D position; if(coordFrame == "Q (lab frame)") { - peak.setQLabFrame(peakPosition); + peak.setQLabFrame(peakPosition,1/*set the detector distance explicitly*/); } else { @@ -374,4 +374,4 @@ class PeaksOnSurfaceTestPerformance : public CxxTest::TestSuite } }; -#endif /* MANTID_CRYSTAL_PEAKSONSURFACETEST_H_ */ \ No newline at end of file +#endif /* MANTID_CRYSTAL_PEAKSONSURFACETEST_H_ */ diff --git a/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp b/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp index aba40ce1d8ac..11df5295a6c6 100644 --- a/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp +++ b/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp @@ -318,7 +318,7 @@ create2DWorkspaceWithFullInstrument(int nhist, int nbins, bool includeMonitors, boost::shared_ptr testInst(new Instrument(instrumentName)); testInst->setReferenceFrame( - boost::shared_ptr(new ReferenceFrame(Y, X, Left, ""))); + boost::shared_ptr(new ReferenceFrame(Y, Z, Left, ""))); space->setInstrument(testInst); const double pixelRadius(0.05); @@ -366,14 +366,14 @@ create2DWorkspaceWithFullInstrument(int nhist, int nbins, bool includeMonitors, // Define a source and sample position // Define a source component ObjComponent *source = - new ObjComponent("moderator", Object_sptr(), testInst.get()); + new ObjComponent("moderator", ComponentCreationHelper::createSphere(0.1, V3D(0,0,0), "1"), testInst.get()); source->setPos(V3D(-20, 0.0, 0.0)); testInst->add(source); testInst->markAsSource(source); // Define a sample as a simple sphere ObjComponent *sample = - new ObjComponent("samplePos", Object_sptr(), testInst.get()); + new ObjComponent("samplePos", ComponentCreationHelper::createSphere(0.1, V3D(0,0,0), "1"), testInst.get()); testInst->setPos(0.0, 0.0, 0.0); testInst->add(sample); testInst->markAsSamplePos(sample); From d26a4d599e74a6873b42c98e0b247c1ab00e8dea Mon Sep 17 00:00:00 2001 From: Roman Tolchenov Date: Wed, 18 Feb 2015 11:12:47 +0000 Subject: [PATCH 258/414] Re #11059. Fix a typo in example code. --- Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst b/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst index 8469b83b2e82..4aa18f206dd4 100644 --- a/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst +++ b/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst @@ -144,7 +144,7 @@ Output: **Example 2:** -.. testcode:: exStartLiveDataisto +.. testcode:: exStartLiveDataHisto from threading import Thread import time From e96d4de07fcc6e4e885b6fee4841b163895a23b4 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Wed, 18 Feb 2015 11:44:05 +0000 Subject: [PATCH 259/414] Re #9556 Commenting unused HKT function --- .../CurveFitting/src/DynamicKuboToyabe.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index b8f353c06a0f..ef12067afcde 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -41,10 +41,10 @@ double ZFKT (const double x, const double G){ } // Static Non-Zero field Kubo Toyabe relaxation function -double HKT (const double x, const double G, const double F) -{ - throw std::runtime_error("HKT not implemented yet"); -} +//double HKT (const double x, const double G, const double F) +//{ +// throw std::runtime_error("HKT not implemented yet"); +//} // Dynamic Kubo-Toyabe double getDKT (double t, double G, double v){ @@ -121,9 +121,10 @@ void DynamicKuboToyabe::function1D(double* out, const double* xValues, const siz } // Non-zero external field else{ - for (size_t i = 0; i < nData; i++) { - out[i] = A*HKT(xValues[i],G,F); - } + //for (size_t i = 0; i < nData; i++) { + // out[i] = A*HKT(xValues[i],G,F); + //} + throw std::runtime_error("HKT() not implemented yet"); } } @@ -139,7 +140,7 @@ void DynamicKuboToyabe::function1D(double* out, const double* xValues, const siz } else { // Non-zero field - throw std::runtime_error("Not implemented yet"); + throw std::runtime_error("HKT() not implemented yet"); } } // else hopping rate != 0 From 5ae7c880ea3d7da5b8cf3232fe74a7980414cf4f Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Wed, 18 Feb 2015 11:48:19 +0000 Subject: [PATCH 260/414] Re #9556 Fixing size_t to double conversion --- Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index ef12067afcde..cba5034c2405 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -69,7 +69,7 @@ double getDKT (double t, double G, double v){ // re-compute gStat if G has changed // Generate static Kubo-Toyabe - for (size_t k=0; k Date: Wed, 18 Feb 2015 12:16:16 +0000 Subject: [PATCH 261/414] re #11069 ScriptRepo now works with the new internetHelper --- .../Kernel/inc/MantidKernel/InternetHelper.h | 13 +- .../Framework/Kernel/src/InternetHelper.cpp | 70 ++++-- .../ScriptRepositoryImpl.h | 1 - .../src/ScriptRepositoryImpl.cpp | 228 ++++-------------- 4 files changed, 104 insertions(+), 208 deletions(-) diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h b/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h index 7fc7b1ed5cb0..f655d8bb1739 100644 --- a/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h +++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h @@ -6,8 +6,6 @@ #include "MantidKernel/ProxyInfo.h" #include -#include -#include namespace Poco { // forward declaration @@ -79,9 +77,11 @@ class MANTID_KERNEL_DLL InternetHelper { void setBody(const std::string& body); void setBody(const std::ostringstream& body); void setBody(Poco::Net::HTMLForm& form); - const std::string getBody(); - - + const std::string& getBody(); + + int getResponseStatus(); + const std::string& getResponseReason(); + void addHeader(const std::string& key, const std::string& value); void removeHeader (const std::string& key); const std::string& getHeader (const std::string& key); @@ -125,9 +125,10 @@ class MANTID_KERNEL_DLL InternetHelper { std::streamsize m_contentLength; std::string m_method; std::string m_contentType; - std::ostringstream m_body; + std::string m_body; StringToStringMap m_headers; Poco::Net::HTTPRequest *m_request; + Poco::Net::HTTPResponse *m_response; }; } // namespace Kernel diff --git a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp index 7e07db7f453d..0642b39d799a 100644 --- a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp +++ b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp @@ -34,6 +34,7 @@ // std #include +#include namespace Mantid { namespace Kernel { @@ -75,7 +76,7 @@ bool isRelocated(const int response) { InternetHelper::InternetHelper() : m_proxyInfo(), m_isProxySet(false), m_timeout(30), m_contentLength(0), m_method(HTTPRequest::HTTP_GET), m_contentType("application/json"), - m_body(), m_headers(), m_request(NULL) {} + m_body(), m_headers(), m_request(NULL),m_response(NULL) {} //---------------------------------------------------------------------------------------------- /** Constructor @@ -83,7 +84,7 @@ InternetHelper::InternetHelper() InternetHelper::InternetHelper(const Kernel::ProxyInfo &proxy) : m_proxyInfo(proxy), m_isProxySet(true), m_timeout(30), m_method(HTTPRequest::HTTP_GET), m_contentType("application/json"), - m_body(), m_headers(), m_request(NULL) {} + m_body(), m_headers(), m_request(NULL),m_response(NULL) {} //---------------------------------------------------------------------------------------------- /** Destructor @@ -91,6 +92,9 @@ InternetHelper::InternetHelper(const Kernel::ProxyInfo &proxy) InternetHelper::~InternetHelper() { if (m_request != NULL) { delete m_request; + } + if (m_response != NULL) { + delete m_response; } } @@ -107,9 +111,13 @@ void InternetHelper::createRequest(Poco::URI &uri) { if (m_request != NULL) { delete m_request; } + if (m_response != NULL) { + delete m_response; + } m_request = new HTTPRequest(m_method, uri.getPathAndQuery(), HTTPMessage::HTTP_1_1); + m_response = new HTTPResponse(); if (!m_contentType.empty()) { m_request->setContentType(m_contentType); } @@ -136,10 +144,10 @@ int InternetHelper::sendRequestAndProcess(HTTPClientSession &session, this->createRequest(uri); session.sendRequest(*m_request) << m_body; - HTTPResponse res; - std::istream &rs = session.receiveResponse(res); - int retStatus = res.getStatus(); - g_log.debug() << "Answer from web: " << retStatus << " " << res.getReason() + + std::istream &rs = session.receiveResponse(*m_response); + int retStatus = m_response->getStatus(); + g_log.debug() << "Answer from web: " << retStatus << " " << m_response->getReason() << std::endl; if (retStatus == HTTPResponse::HTTP_OK || @@ -148,9 +156,10 @@ int InternetHelper::sendRequestAndProcess(HTTPClientSession &session, Poco::StreamCopier::copyStream(rs, responseStream); return retStatus; } else if (isRelocated(retStatus)) { - return this->processRelocation(res, responseStream); + return this->processRelocation(*m_response, responseStream); } else { - return processErrorStates(res, rs, uri.toString()); + Poco::StreamCopier::copyStream(rs, responseStream); + return processErrorStates(*m_response, rs, uri.toString()); } } @@ -352,6 +361,7 @@ int InternetHelper::processErrorStates(const Poco::Net::HTTPResponse &res, // show the error info << res.getReason(); info << ss.str(); + g_log.debug() << ss.str(); } throw Exception::InternetError(info.str() + ss.str(), retStatus); } @@ -393,6 +403,12 @@ int InternetHelper::downloadFile(const std::string &urlFile, // if there have been no errors move it to the final location, and turn off // automatic deletion. + //clear the way if the target file path is already in use + Poco::File file(localFilePath); + if (file.exists()) { + file.remove(); + } + tempFile.moveTo(localFilePath); tempFile.keep(); @@ -417,7 +433,7 @@ void InternetHelper::setMethod(const std::string& method) { if (method == "POST") { m_method = method; } else { - m_method = "GET"; + m_method = "GET"; } } @@ -456,15 +472,13 @@ std::streamsize InternetHelper::getContentLength() { return m_contentLength; } * @param body A string of the body **/ void InternetHelper::setBody(const std::string& body) { - //clear the old body - m_body.str("") ; - if (body.empty()) { - setMethod("GET"); + m_body = body; + if (m_body.empty()) { + m_method="GET"; } else { - setMethod("POST"); - m_body << body; + m_method="POST"; } - setContentLength(body.size()); + setContentLength(m_body.size()); } /** Sets the body & content length for future requests, this will also @@ -473,7 +487,7 @@ void InternetHelper::setBody(const std::string& body) { * @param body A stringstream of the body **/ void InternetHelper::setBody(const std::ostringstream& body) { - setBody(body.str()); + setBody(body.str()); } /** Sets the body & content length for future requests, this will also @@ -490,22 +504,28 @@ void InternetHelper::setBody(Poco::Net::HTMLForm& form) { } form.prepareSubmit(*m_request); setContentType(m_request->getContentType()); - //clear the old body - m_body.str("") ; - form.write(m_body); - setContentLength(m_body.tellp()); + std::ostringstream ss; + form.write(ss); + m_body = ss.str(); + setContentLength(m_body.size()); } +/** Gets the body set for future requests +* @returns A string of the content type +**/ +const std::string& InternetHelper::getBody() {return m_body; } /** Gets the body set for future requests * @returns A string of the content type **/ -const std::string InternetHelper::getBody() {return m_body.str(); } +int InternetHelper::getResponseStatus() {return m_response->getStatus(); } -void setBody(const std::string& body); - const std::string getBody(); +/** Gets the body set for future requests +* @returns A string of the content type +**/ +const std::string& InternetHelper::getResponseReason() {return m_response->getReason(); } /** Adds a header * @param key The key to refer to the value @@ -545,7 +565,7 @@ std::map& InternetHelper::headers() { void InternetHelper::reset() { m_headers.clear(); m_timeout = 30; - m_body.str(""); + m_body = ""; m_method = HTTPRequest::HTTP_GET; m_contentType = "application/json"; m_request = NULL ; diff --git a/Code/Mantid/Framework/ScriptRepository/inc/MantidScriptRepository/ScriptRepositoryImpl.h b/Code/Mantid/Framework/ScriptRepository/inc/MantidScriptRepository/ScriptRepositoryImpl.h index dc9306628643..64c0750492af 100644 --- a/Code/Mantid/Framework/ScriptRepository/inc/MantidScriptRepository/ScriptRepositoryImpl.h +++ b/Code/Mantid/Framework/ScriptRepository/inc/MantidScriptRepository/ScriptRepositoryImpl.h @@ -167,7 +167,6 @@ class SCRIPT_DLL_EXPORT ScriptRepositoryImpl : public ScriptRepository { std::string ignoreregex; - bool getProxyConfig(std::string &, unsigned short &); std::string getParentFolder(const std::string &entry); }; diff --git a/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp b/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp index d7c05a2e675a..8f016f75e014 100644 --- a/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp +++ b/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp @@ -1,8 +1,10 @@ // from mantid #include "MantidScriptRepository/ScriptRepositoryImpl.h" #include "MantidAPI/ScriptRepositoryFactory.h" -#include "MantidKernel/Logger.h" #include "MantidKernel/ConfigService.h" +#include "MantidKernel/Exception.h" +#include "MantidKernel/InternetHelper.h" +#include "MantidKernel/Logger.h" #include "MantidKernel/NetworkProxy.h" #include "MantidKernel/ProxyInfo.h" #include @@ -18,11 +20,12 @@ using Mantid::Kernel::NetworkProxy; #include #include #include -#include -#include #include -#include #include +/*#include +#include +#include +*/ #include #include "Poco/Net/FilePartSource.h" @@ -41,7 +44,6 @@ using Mantid::Kernel::NetworkProxy; #include #endif #include -#include #include #include #include @@ -781,18 +783,9 @@ void ScriptRepositoryImpl::upload(const std::string &file_path, try { g_log.notice() << "ScriptRepository uploading " << file_path << " ..." << std::endl; - Poco::URI uri(remote_upload); - std::string path(uri.getPathAndQuery()); - HTTPClientSession session(uri.getHost(), uri.getPort()); - - // configure proxy - std::string proxy_config; - unsigned short proxy_port; - if (getProxyConfig(proxy_config, proxy_port)) - session.setProxy(proxy_config, proxy_port); - // proxy end - - HTTPRequest req(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_0); + + Kernel::InternetHelper inetHelper; + HTMLForm form(HTMLForm::ENCODING_MULTIPART); // add the fields author, email and comment @@ -816,32 +809,23 @@ void ScriptRepositoryImpl::upload(const std::string &file_path, FilePartSource *m_file = new FilePartSource(absolute_path); form.addPart("file", m_file); - // get the size of everything - std::stringstream sst; - form.write(sst); - // move back to the begining of the file - m_file->stream().clear(); - m_file->stream().seekg(0, std::ios::beg); - // set the size - req.setContentLength((int)sst.str().size()); - - form.prepareSubmit(req); - std::ostream &ostr = session.sendRequest(req); - // send the request. - ostr << sst.str(); - - HTTPResponse response; - std::istream &rs = session.receiveResponse(response); + inetHelper.setBody(form); + std::stringstream server_reply; + int status; + try { + status = inetHelper.sendRequest(remote_upload,server_reply); + } catch (Kernel::Exception::InternetError &ie) { + status = ie.errorCode(); + } + g_log.information() << "ScriptRepository upload status: " - << response.getStatus() << " " << response.getReason() + << status << std::endl; std::stringstream answer; { // remove the status message from the end of the reply, in order not to // get exception from the read_json parser - std::stringstream server_reply; std::string server_reply_str; - Poco::StreamCopier::copyStream(rs, server_reply); server_reply_str = server_reply.str(); size_t pos = server_reply_str.rfind("}"); if (pos != std::string::npos) @@ -1092,20 +1076,10 @@ std::string ScriptRepositoryImpl::doDeleteRemoteFile( using namespace Poco::Net; std::stringstream answer; try { - // create the poco httprequest object - Poco::URI uri(url); - std::string path(uri.getPathAndQuery()); - HTTPClientSession session(uri.getHost(), uri.getPort()); - HTTPRequest req(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_0); g_log.debug() << "Receive request to delete file " << file_path << " using " << url << std::endl; - // configure proxy - std::string proxy_config; - unsigned short proxy_port; - if (getProxyConfig(proxy_config, proxy_port)) - session.setProxy(proxy_config, proxy_port); - // proxy end + Kernel::InternetHelper inetHelper; // fill up the form required from the server to delete one file, with the // fields @@ -1117,22 +1091,23 @@ std::string ScriptRepositoryImpl::doDeleteRemoteFile( form.add("file_n", file_path); // send the request to the server - form.prepareSubmit(req); - std::ostream &ostr = session.sendRequest(req); - form.write(ostr); + inetHelper.setBody(form); + std::stringstream server_reply; + int status; + try { + status = inetHelper.sendRequest(url,server_reply); + } catch (Kernel::Exception::InternetError &ie) + { + status = ie.errorCode(); + } - // get the answer from the server - HTTPResponse response; - std::istream &rs = session.receiveResponse(response); - g_log.debug() << "ScriptRepository delete status: " << response.getStatus() - << " " << response.getReason() << std::endl; + g_log.debug() << "ScriptRepository delete status: " << status + << std::endl; { // get the answer from the server - std::stringstream server_reply; std::string server_reply_str; - Poco::StreamCopier::copyStream(rs, server_reply); server_reply_str = server_reply.str(); // remove the status message from the end of the reply, // in order not to get exception from the read_json parser @@ -1332,9 +1307,10 @@ void ScriptRepositoryImpl::doDownloadFile(const std::string &url_file, const std::string &local_file_path) { g_log.debug() << "DoDownloadFile : " << url_file << " to file: " << local_file_path << std::endl; + + // get the information from url_file - Poco::URI uri(url_file); - std::string path(uri.getPathAndQuery()); + std::string path(url_file); if (path.empty()) path = "/"; std::string given_path; @@ -1346,69 +1322,25 @@ void ScriptRepositoryImpl::doDownloadFile(const std::string &url_file, given_path = path; // Configure Poco HTTP Client Session try { - Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort()); - session.setTimeout(Poco::Timespan(3, 0)); // 3 secconds - - // configure proxy - std::string proxy_config; - unsigned short proxy_port; - if (getProxyConfig(proxy_config, proxy_port)) - session.setProxy(proxy_config, proxy_port); - // proxy end - - Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path, - Poco::Net::HTTPMessage::HTTP_1_1); - Poco::Net::HTTPResponse response; - - session.sendRequest(request); - - std::istream &rs = session.receiveResponse(response); - g_log.debug() << "Answer from mantid web: " << response.getStatus() << " " - << response.getReason() << std::endl; - if (response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) { - if (local_file_path.empty()) { - // ignore the answer, trow it away - Poco::NullOutputStream null; - Poco::StreamCopier::copyStream(rs, null); - return; - } else { - // copy the file - Poco::FileStream _out(local_file_path); - Poco::StreamCopier::copyStream(rs, _out); - _out.close(); - } - } else { - std::stringstream info; - std::stringstream ss; - Poco::StreamCopier::copyStream(rs, ss); - if (response.getStatus() == Poco::Net::HTTPResponse::HTTP_NOT_FOUND) - info << "Failed to download " << given_path - << " because it failed to find this file at the link " - << ".\n" - << "Hint. Check that link is correct and points to the correct " - "server " - << "which you can find at " - << "Script Repository Help Page"; - else { - // show the error - // fixme, process this error - info << response.getReason(); - info << ss.str(); - } - throw ScriptRepoException(info.str(), ss.str()); - } - } catch (Poco::Net::HostNotFoundException &ex) { - // this exception occurrs when the pc is not connected to the internet + Kernel::InternetHelper inetHelper; + inetHelper.setTimeout(3); // 3 seconds + + std::stringstream ss; + int status = inetHelper.downloadFile(url_file,local_file_path); + + g_log.debug() << "Answer from mantid web: " << status << std::endl; + } + catch (Kernel::Exception::InternetError &ie) { std::stringstream info; info << "Failed to download " << given_path - << " because there is no connection to the host " << ex.message() - << ".\nHint: Check your connection following this link: " << given_path << ""; - throw ScriptRepoException(info.str(), ex.displayText(), __FILE__, __LINE__); - - } catch (Poco::Exception &ex) { - throw pocoException("Connection and request failed", ex); + << " because it failed to find this file at the link " + << "" << url_file << ".\n" + << "Hint. Check that link is correct and points to the correct " + "server " + << "which you can find at " + << "Script Repository Help Page"; + throw ScriptRepoException(info.str(), ie.what()); } } @@ -1770,62 +1702,6 @@ std::string ScriptRepositoryImpl::convertPath(const std::string &path) { return path; } -bool ScriptRepositoryImpl::getProxyConfig(std::string &proxy_server, - unsigned short &proxy_port) { - // these variables are made static, so, to not query the system for the proxy - // configuration - // everytime this information is needed - - Mantid::Kernel::NetworkProxy proxyHelper; - ProxyInfo proxyInfo = proxyHelper.getHttpProxy(remote_url); - if (proxyInfo.emptyProxy()) { - g_log.information( - "ScriptRepository: No HTTP network proxy settings found. None used."); - } else { - g_log.information( - "ScriptRepository: HTTP System network proxy settings found."); - g_log.debug() << "ScriptRepository Host found: " << proxyInfo.host() - << " Port found: " << proxyInfo.port() << std::endl; - } - - if (!proxyInfo.emptyProxy()) { - try { - // test if the proxy is valid for connecting to remote repository - Poco::URI uri(remote_url); - Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort()); - // setup a request to read the remote url - Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, "/", - Poco::Net::HTTPMessage::HTTP_1_1); - // through the proxy - session.setProxy(proxyInfo.host(), - static_cast(proxyInfo.port())); - session.sendRequest( - request); // if it fails, it will throw exception here. - - // clear the answer. - Poco::Net::HTTPResponse response; - std::istream &rs = session.receiveResponse(response); - Poco::NullOutputStream null; - Poco::StreamCopier::copyStream(rs, null); - // report that the proxy was configured - g_log.information() << "ScriptRepository proxy found. Host: " - << proxyInfo.host() << " Port: " << proxyInfo.port() - << std::endl; - proxy_server = proxyInfo.host(); - proxy_port = static_cast(proxyInfo.port()); - } catch (Poco::Net::HostNotFoundException &ex) { - g_log.information() << "ScriptRepository found that proxy can not be " - "used for this connection.\n" << ex.displayText() - << std::endl; - } catch (...) { - g_log.warning() << "Unexpected error while looking for the proxy for " - "ScriptRepository." << std::endl; - } - } - - return !proxyInfo.emptyProxy(); - ; -} } // END API From f15cb2d0efb11b905937f7e3f0ad6c8f4df12965 Mon Sep 17 00:00:00 2001 From: Nick Draper Date: Wed, 18 Feb 2015 12:19:49 +0000 Subject: [PATCH 262/414] re #11114 remove always on top hint --- Code/Mantid/MantidPlot/src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/main.cpp b/Code/Mantid/MantidPlot/src/main.cpp index 8e8f9a066eac..646f3102b24e 100644 --- a/Code/Mantid/MantidPlot/src/main.cpp +++ b/Code/Mantid/MantidPlot/src/main.cpp @@ -187,7 +187,7 @@ int main( int argc, char ** argv ) // Splash QPixmap pixmap; if (!pixmap.load(":/MantidSplashScreen.png")) std::cerr << "Couldn't load splashscreen\n"; - QSplashScreen splash(pixmap, Qt::WindowStaysOnTopHint); + QSplashScreen splash(pixmap); const QString releaseDateTime(Mantid::Kernel::MantidVersion::releaseDate()); const QString versionInfo(Mantid::Kernel::MantidVersion::version()); splash.showMessage("Release: " + releaseDateTime + " (Version " + versionInfo + ")", Qt::AlignLeft | Qt::AlignBottom); From 06e5025c0c5e58c90c3ecad2194f5c7a0b8211d2 Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Wed, 18 Feb 2015 13:31:08 +0100 Subject: [PATCH 263/414] Refs #11104. Re-enabling unit tests in GaussianTest Re-enabled some of the disabled unit tests in GaussianTest.h. The other tests have some issues, this has to be handled in another ticket. --- Code/Mantid/Framework/CurveFitting/test/GaussianTest.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h b/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h index 760c5712f462..87069b7b3bb6 100644 --- a/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h @@ -160,7 +160,7 @@ class GaussianTest : public CxxTest::TestSuite for (size_t i=0; i < 41; i++) e[i] = sqrt( y[i] ); } - void xtest_with_Levenberg_Marquardt() + void test_with_Levenberg_Marquardt() { API::FunctionDomain1D_sptr domain(new API::FunctionDomain1DVector( 79292.4, 79603.6, 41)); API::FunctionValues mockData(*domain); @@ -426,7 +426,7 @@ class GaussianTest : public CxxTest::TestSuite } - void xtestAgainstMockDataSimplex2() + void testAgainstMockDataSimplex2() { // create mock data to test against std::string wsName = "GaussMockDataSimplex2"; From 173c23197e5c2d5caff7ca6cb891379b60f022c5 Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Wed, 18 Feb 2015 13:32:07 +0100 Subject: [PATCH 264/414] Refs #11104. Add intensity/setIntensity methods to IPeakFunction --- .../API/inc/MantidAPI/IPeakFunction.h | 6 +++++ .../Framework/API/src/IPeakFunction.cpp | 27 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/IPeakFunction.h b/Code/Mantid/Framework/API/inc/MantidAPI/IPeakFunction.h index 7405ca45a731..f36c1ad37261 100644 --- a/Code/Mantid/Framework/API/inc/MantidAPI/IPeakFunction.h +++ b/Code/Mantid/Framework/API/inc/MantidAPI/IPeakFunction.h @@ -49,6 +49,12 @@ class MANTID_API_DLL IPeakFunction : public IFunctionWithLocation { /// Sets the parameters such that FWHM = w virtual void setFwhm(const double w) = 0; + /// Returns the integral intensity of the peak + virtual double intensity() const; + + /// Sets the integral intensity of the peak + virtual void setIntensity(const double intensity); + /// General implementation of the method for all peaks. void function1D(double *out, const double *xValues, const size_t nData) const; /// General implementation of the method for all peaks. diff --git a/Code/Mantid/Framework/API/src/IPeakFunction.cpp b/Code/Mantid/Framework/API/src/IPeakFunction.cpp index 04e9b34dc2b2..edac0d20c107 100644 --- a/Code/Mantid/Framework/API/src/IPeakFunction.cpp +++ b/Code/Mantid/Framework/API/src/IPeakFunction.cpp @@ -3,6 +3,7 @@ //---------------------------------------------------------------------- #include "MantidAPI/IPeakFunction.h" #include "MantidAPI/Jacobian.h" +#include "MantidAPI/PeakFunctionIntegrator.h" #include "MantidKernel/Exception.h" #include "MantidKernel/ConfigService.h" @@ -130,5 +131,31 @@ void IPeakFunction::setPeakRadius(const int &r) { } } +double IPeakFunction::intensity() const { + double x0 = centre(); + double dx = fabs(s_peakRadius * fwhm()); + + PeakFunctionIntegrator integrator; + IntegrationResult result = integrator.integrate(*this, x0 - dx, x0 + dx); + + if(!result.success) { + return 0.0; + } + + return result.result; +} + +void IPeakFunction::setIntensity(const double newIntensity) +{ + double currentHeight = height(); + double currentIntensity = intensity(); + + if(currentIntensity == 0.0) { + setHeight(0.0); + } else { + setHeight(newIntensity / currentIntensity * currentHeight); + } +} + } // namespace API } // namespace Mantid From 1e56cbde5b7f8350dbc0f3359a413ce19fdb3d5f Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Wed, 18 Feb 2015 13:42:33 +0100 Subject: [PATCH 265/414] Refs #11104. Adding unit test for Gaussian. --- .../CurveFitting/test/GaussianTest.h | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h b/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h index 87069b7b3bb6..4c885c4edbe0 100644 --- a/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h @@ -583,6 +583,37 @@ class GaussianTest : public CxxTest::TestSuite ConfigService::Instance().setString("curvefitting.peakRadius",priorRadius); } + void testIntensity() + { + boost::shared_ptr fn( new Gaussian() ); + fn->initialize(); + fn->setHeight(2.0); + fn->setFwhm(0.125); + fn->setCentre(-200.0); + + // Area under a gaussian is height * sigma * sqrt(2 * pi) + TS_ASSERT_DELTA(fn->intensity(), 0.26611675485780654483, 1e-10); + } + + void testSetIntensity() + { + boost::shared_ptr fn( new Gaussian() ); + fn->initialize(); + fn->setHeight(2.0); + fn->setFwhm(0.125); + fn->setCentre(-200.0); + + TS_ASSERT_THROWS_NOTHING(fn->setIntensity(0.5)); + + TS_ASSERT_DELTA(fn->intensity(), 0.5, 1e-10); + + // FWHM does not change + TS_ASSERT_EQUALS(fn->fwhm(), 0.125); + + // Height changes + TS_ASSERT_DELTA(fn->height(), 3.75774911479860533509, 1e-10); + } + }; From a9dfb0fed59e4ec35ff877fca275b256b6e1f928 Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Wed, 18 Feb 2015 13:43:06 +0100 Subject: [PATCH 266/414] Refs #11104. Changing parameter name. --- Code/Mantid/Framework/API/inc/MantidAPI/IPeakFunction.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/IPeakFunction.h b/Code/Mantid/Framework/API/inc/MantidAPI/IPeakFunction.h index f36c1ad37261..80e2899f880f 100644 --- a/Code/Mantid/Framework/API/inc/MantidAPI/IPeakFunction.h +++ b/Code/Mantid/Framework/API/inc/MantidAPI/IPeakFunction.h @@ -53,7 +53,7 @@ class MANTID_API_DLL IPeakFunction : public IFunctionWithLocation { virtual double intensity() const; /// Sets the integral intensity of the peak - virtual void setIntensity(const double intensity); + virtual void setIntensity(const double newIntensity); /// General implementation of the method for all peaks. void function1D(double *out, const double *xValues, const size_t nData) const; From 6f4d2f1aabd475faa2b4602ddfd4204a81bb6cab Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Wed, 18 Feb 2015 12:55:12 +0000 Subject: [PATCH 267/414] refs #11056. Tracked down MDAlgorithmsTest issues --- .../Mantid/Framework/MDAlgorithms/test/CentroidPeaksMD2Test.h | 4 ++-- Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMDTest.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMD2Test.h b/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMD2Test.h index 31584d4caf27..3adbed5c426d 100644 --- a/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMD2Test.h +++ b/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMD2Test.h @@ -98,9 +98,9 @@ class CentroidPeaksMD2Test : public CxxTest::TestSuite Peak pIn(inst, 1, 1.0, startPos ); if (CoordinatesToUse == "Q (lab frame)") - pIn.setQLabFrame(startPos); + pIn.setQLabFrame(startPos, 1 /*sample to detector distance*/); else if (CoordinatesToUse == "Q (sample frame)") - pIn.setQSampleFrame(startPos); + pIn.setQSampleFrame(startPos, 1 /*sample to detector distance*/); else if (CoordinatesToUse == "HKL") pIn.setHKL(startPos); peakWS->addPeak( pIn ); diff --git a/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMDTest.h b/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMDTest.h index 4e7338b07bdd..445df41cf2d4 100644 --- a/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMDTest.h +++ b/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMDTest.h @@ -98,9 +98,9 @@ class CentroidPeaksMDTest : public CxxTest::TestSuite Peak pIn(inst, 1, 1.0, startPos ); if (CoordinatesToUse == "Q (lab frame)") - pIn.setQLabFrame(startPos); + pIn.setQLabFrame(startPos, 1 /*sample to detector distance*/); else if (CoordinatesToUse == "Q (sample frame)") - pIn.setQSampleFrame(startPos); + pIn.setQSampleFrame(startPos, 1 /*sample to detector distance*/); else if (CoordinatesToUse == "HKL") pIn.setHKL(startPos); peakWS->addPeak( pIn ); From 5d101c018d183fd3c975ff195c7d2efb511404cc Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Wed, 18 Feb 2015 14:14:56 +0100 Subject: [PATCH 268/414] Refs #11104. Adding another Gaussian test, formatting IPeakFunction --- .../Framework/API/src/IPeakFunction.cpp | 22 +++++++++---------- .../CurveFitting/test/GaussianTest.h | 11 ++++++++++ 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/Code/Mantid/Framework/API/src/IPeakFunction.cpp b/Code/Mantid/Framework/API/src/IPeakFunction.cpp index edac0d20c107..e7ba60ec1895 100644 --- a/Code/Mantid/Framework/API/src/IPeakFunction.cpp +++ b/Code/Mantid/Framework/API/src/IPeakFunction.cpp @@ -138,23 +138,23 @@ double IPeakFunction::intensity() const { PeakFunctionIntegrator integrator; IntegrationResult result = integrator.integrate(*this, x0 - dx, x0 + dx); - if(!result.success) { - return 0.0; + if (!result.success) { + return 0.0; } return result.result; } -void IPeakFunction::setIntensity(const double newIntensity) -{ - double currentHeight = height(); - double currentIntensity = intensity(); +void IPeakFunction::setIntensity(const double newIntensity) { + double currentHeight = height(); + double currentIntensity = intensity(); - if(currentIntensity == 0.0) { - setHeight(0.0); - } else { - setHeight(newIntensity / currentIntensity * currentHeight); - } + if (currentIntensity == 0.0) { + throw std::invalid_argument( + "Cannot set new intensity, not enough information available."); + } + + setHeight(newIntensity / currentIntensity * currentHeight); } } // namespace API diff --git a/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h b/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h index 4c885c4edbe0..e7bc607d7898 100644 --- a/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h @@ -614,6 +614,17 @@ class GaussianTest : public CxxTest::TestSuite TS_ASSERT_DELTA(fn->height(), 3.75774911479860533509, 1e-10); } + void testSetIntensityDefault() + { + boost::shared_ptr fn( new Gaussian() ); + fn->initialize(); + + TS_ASSERT_EQUALS(fn->intensity(), 0.0); + + TS_ASSERT_THROWS(fn->setIntensity(20.0), std::invalid_argument); + TS_ASSERT_EQUALS(fn->intensity(), 0.0); + } + }; From 392a0c9178fe3294a1d034b267149a777e006d64 Mon Sep 17 00:00:00 2001 From: Nick Draper Date: Wed, 18 Feb 2015 13:39:47 +0000 Subject: [PATCH 269/414] re #11069 Merge of master instroduced an error - solved --- Code/Mantid/Framework/Kernel/src/InternetHelper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp index a62084f74ec7..0642b39d799a 100644 --- a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp +++ b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp @@ -142,7 +142,7 @@ int InternetHelper::sendRequestAndProcess(HTTPClientSession &session, std::ostream &responseStream) { // create a request this->createRequest(uri); - session.sendRequest(*m_request) << m_body.str(); + session.sendRequest(*m_request) << m_body; std::istream &rs = session.receiveResponse(*m_response); From 7a4cefb04619f9ed8613ce709ac2bc96b804c91b Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Wed, 18 Feb 2015 15:01:14 +0100 Subject: [PATCH 270/414] Refs #11104. Adding intensity test for Lorentzian --- .../Framework/CurveFitting/test/LorentzianTest.h | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Code/Mantid/Framework/CurveFitting/test/LorentzianTest.h b/Code/Mantid/Framework/CurveFitting/test/LorentzianTest.h index 660939553f9b..f9781ce2b345 100644 --- a/Code/Mantid/Framework/CurveFitting/test/LorentzianTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/LorentzianTest.h @@ -103,6 +103,21 @@ class LorentzianTest : public CxxTest::TestSuite TS_ASSERT_EQUALS(y[0], 0.0); } + void testIntensity() + { + Mantid::CurveFitting::Lorentzian lor; + lor.initialize(); + lor.setHeight(2.0); + lor.setCentre(3.0); + lor.setFwhm(1.0); + + TS_ASSERT_DELTA(lor.intensity(), 1.873097930277787, 1e-10); + TS_ASSERT_THROWS_NOTHING(lor.setIntensity(2.0)); + + TS_ASSERT_DELTA(lor.intensity(), 2.0, 1e-10); + TS_ASSERT_EQUALS(lor.fwhm(), 1.0); + } + private: class TestableLorentzian : public Mantid::CurveFitting::Lorentzian From 5a2a0706568f08da23fc56e23c4c3994bcb02b6a Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Wed, 18 Feb 2015 16:36:38 +0100 Subject: [PATCH 271/414] Refs #11104. Python exports. --- .../mantid/api/src/Exports/IPeakFunction.cpp | 22 +++++--- .../python/mantid/api/IPeakFunctionTest.py | 53 +++++++++++++++++++ 2 files changed, 67 insertions(+), 8 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp index 1164cfe661d7..0d1a5c71e0a9 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp @@ -7,12 +7,18 @@ using Mantid::API::IPeakFunction; using Mantid::PythonInterface::IPeakFunctionAdapter; using namespace boost::python; -void export_IPeakFunction() -{ - class_, boost::shared_ptr, - boost::noncopyable>("IPeakFunction") - .def("functionLocal", (object (IPeakFunctionAdapter::*)(const object &)const)&IPeakFunction::functionLocal, - "Calculate the values of the function for the given x values. The output should be stored in the out array") - ; +void export_IPeakFunction() { + class_, + boost::shared_ptr, boost::noncopyable>( + "IPeakFunction") + .def("functionLocal", + (object (IPeakFunctionAdapter::*)(const object &)const) & + IPeakFunction::functionLocal, + "Calculate the values of the function for the given x values. The " + "output should be stored in the out array") + .def("intensity", &IPeakFunction::intensity, + "Returns the integral intensity of the peak function.") + .def("setIntensity", &IPeakFunction::setIntensity, + "Changes the integral intensity of the peak function by setting its " + "height."); } - diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py index 3832a39214ed..2ac78d6d5376 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py @@ -13,6 +13,41 @@ def init(self): def functionLocal(self, xvals): return 5*xvals +class RectangularFunction(IPeakFunction): + def init(self): + self.declareParameter("Height") + self.declareParameter("Fwhm") + self.declareParameter("Center") + + def centre(self): + return self.getParameterValue("Center") + + def setCentre(self, newCenter): + self.setParameter("Center", newCenter) + + def height(self): + return self.getParameterValue("Height") + + def setHeight(self, newHeight): + self.setParameter("Height", newHeight) + + def fwhm(self): + return self.getParameterValue("Fwhm") + + def setFwhm(self, newFwhm): + self.setParameter("Fwhm", newFwhm) + + def functionLocal(self, xvals): + center = self.getParameterValue("Center") + fwhm = self.getParameterValue("Fwhm") + height = self.getParameterValue("Height") + + values = np.zeros(xvals.shape) + nonZero = (xvals > (center - fwhm/2.0)) & (xvals < (center + fwhm / 2.0)) + values[nonZero] = height + + return values + class IPeakFunctionTest(unittest.TestCase): def test_instance_can_be_created_standalone(self): @@ -38,5 +73,23 @@ def test_functionLocal_can_be_called_directly(self): self.assertEquals(10., out[1]) self.assertEquals(15., out[2]) + def test_get_set_intensity(self): + func = RectangularFunction() + func.initialize() + func.setCentre(1.0) + func.setHeight(2.0) + func.setFwhm(3.0) + + # This is a rectangle function with height 2 and width 3, centered + # around 1.0. The intensity should be 6.0 (height * width) + self.assertAlmostEquals(func.intensity(), 6.0, delta=1e-10) + + # Setting the intensity only changes height, not width + func.setIntensity(12.0) + + self.assertEquals(func.fwhm(), 3.0) + self.assertAlmostEquals(func.height(), 4.0, delta=1e-10) + self.assertAlmostEquals(func.intensity(), 12.0, delta=1e-10) + if __name__ == '__main__': unittest.main() From 84f8193a86d0a92099e3fdb409b32b2675cd0961 Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Wed, 18 Feb 2015 16:40:14 +0100 Subject: [PATCH 272/414] Refs #11104. Adding comments. --- Code/Mantid/Framework/API/src/IPeakFunction.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Mantid/Framework/API/src/IPeakFunction.cpp b/Code/Mantid/Framework/API/src/IPeakFunction.cpp index e7ba60ec1895..f5995bf995bb 100644 --- a/Code/Mantid/Framework/API/src/IPeakFunction.cpp +++ b/Code/Mantid/Framework/API/src/IPeakFunction.cpp @@ -131,6 +131,8 @@ void IPeakFunction::setPeakRadius(const int &r) { } } +/// Returns the integral intensity of the peak function, using the peak radius +/// to determine integration borders. double IPeakFunction::intensity() const { double x0 = centre(); double dx = fabs(s_peakRadius * fwhm()); @@ -145,6 +147,7 @@ double IPeakFunction::intensity() const { return result.result; } +/// Sets the integral intensity of the peak by adjusting the height. void IPeakFunction::setIntensity(const double newIntensity) { double currentHeight = height(); double currentIntensity = intensity(); From 0c9bef16758351bd0f2491a5cb3d4dcb28aa6208 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Wed, 18 Feb 2015 15:56:19 +0000 Subject: [PATCH 273/414] Set and restore default facility in ISIS indirect tests Refs #11118 --- Code/Mantid/scripts/test/IndirectApplyCorrectionsTest.py | 5 +++++ Code/Mantid/scripts/test/IndirectCommonTests.py | 1 + 2 files changed, 6 insertions(+) diff --git a/Code/Mantid/scripts/test/IndirectApplyCorrectionsTest.py b/Code/Mantid/scripts/test/IndirectApplyCorrectionsTest.py index 6c99dc274fa5..3d1762cdc58c 100644 --- a/Code/Mantid/scripts/test/IndirectApplyCorrectionsTest.py +++ b/Code/Mantid/scripts/test/IndirectApplyCorrectionsTest.py @@ -30,6 +30,9 @@ def _decorator(self, *args, **kwargs): class ApplyCorrectionsTests(unittest.TestCase): def setUp(self): + self._config_defaults = config + config['default.facility'] = 'ISIS' + self._sample_workspace = self.make_sample_workspace() self._can_workspace = '' self._corrections_workspace = '' @@ -49,6 +52,8 @@ def tearDown(self): mtd.clear() self.clean_up_saved_workspaces() + config = self._config_defaults + @setup_can_test def test_with_can_workspace(self): output_workspaces = self.run_apply_corrections() diff --git a/Code/Mantid/scripts/test/IndirectCommonTests.py b/Code/Mantid/scripts/test/IndirectCommonTests.py index db4249d96b49..edc6c68b6fc8 100644 --- a/Code/Mantid/scripts/test/IndirectCommonTests.py +++ b/Code/Mantid/scripts/test/IndirectCommonTests.py @@ -16,6 +16,7 @@ class IndirectCommonTests(unittest.TestCase): def setUp(self): self._config_defaults = config + config['default.facility'] = 'ISIS' def tearDown(self): config = self._config_defaults From d7baf2780fe217477cd86a4a8f304e9422f43ef6 Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Wed, 18 Feb 2015 17:22:01 +0100 Subject: [PATCH 274/414] Refs #11104. Removing accidentally added file --- .../PoldiBatchFitIndividualPeaks.py | 181 ------------------ 1 file changed, 181 deletions(-) delete mode 100644 Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PoldiBatchFitIndividualPeaks.py diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PoldiBatchFitIndividualPeaks.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PoldiBatchFitIndividualPeaks.py deleted file mode 100644 index b77beeb9d17c..000000000000 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PoldiBatchFitIndividualPeaks.py +++ /dev/null @@ -1,181 +0,0 @@ -from mantid.api import * -from mantid.kernel import * -from mantid.simpleapi import * -import os -import math -import sys - -class PoldiSample: - def __init__(self, initString): - self._name, self._runList = self.parseInitString(initString) - - def name(self): - return self._name - - def runList(self): - return self._runList - - def runNames(self): - return [x[0] for x in self._runList] - - def parseInitString(self, initString): - parts = initString.split(':') - - if not len(parts) == 2: - raise RuntimeError("Unable to parse init string.") - - sampleName = parts[0] - runDict = self.parseRunDictString(parts[1]) - - return (sampleName, runDict) - - def parseRunDictString(self, runDictString): - runRanges = filter(bool, runDictString.strip().split(';')) - - newRunList = [] - for runRange in runRanges: - runPoints = self.parseRunRangeString(runRange) - newRunList += runPoints - - return newRunList - - def parseRunRangeString(self, runRangeString): - runRangeParameters = [int(x) for x in runRangeString.split(',')] - - if not len(runRangeParameters) == 3: - raise RuntimeError("Unable to parse run range string.") - - begin, end, step = runRangeParameters - - runList = [] - for i in range(begin, end + 1, step): - runList.append((i + step - 1, [str(x) for x in range(i, i + step)])) - - print runList - - return runList - -class PoldiProject: - def __init__(self, projectName, sampleListFile): - self._name = projectName - self._sampleList = self.parseSampleListFile(sampleListFile) - - def sampleList(self): - return self._sampleList - - def name(self): - return self._name - - def parseSampleListFile(self, sampleListFile): - fh = open(sampleListFile, 'r') - - sampleList = [] - for line in fh: - if len(line.strip()) > 0 and not line.strip()[0] == '#': - sampleList.append(PoldiSample(line)) - - return sampleList - -class PoldiBatchFitIndividualPeaks(PythonAlgorithm): - prefixes = {'raw': 'raw_', - 'data': 'data_'} - - suffixes = {'correlation': '_correlation', - 'raw_peaks': '_peaks_raw', - 'fit_peaks_1d': '_peaks_fit_1d', - 'fit_peaks_2d': '_peaks_fit_2d', - 'calculated_2d': '_spectrum_fitted_2d', - 'residuals': '_residuals'} - - def category(self): - return "Workflow\\Poldi" - - def name(self): - return "PoldiBatchFitIndividualPeaks" - - def summary(self): - return "Load a file with instructions for batch processing POLDI fits." - - def PyInit(self): - self.declareProperty("ProjectName", "", "Project name to use for labeling") - self.declareProperty(FileProperty(name="SampleListFile", defaultValue="", - action=FileAction.Load)) - self.declareProperty(FileProperty(name="OutputDirectory", defaultValue="", - action=FileAction.OptionalDirectory)) - self.declareProperty(FileProperty(name="CrystalStructures", - defaultValue="", - action=FileAction.OptionalLoad)) - self.declareProperty("PeakNumber", 10, "Number of peaks to fit.") - - def PyExec(self): - poldiProject = PoldiProject(self.getProperty("ProjectName"), - self.getProperty("SampleListFile").valueAsStr) - - sampleCount = len(poldiProject.sampleList()) - progress = Progress(self, start=0.0, end=1.0, nreports=sampleCount) - - for i, sample in enumerate(poldiProject.sampleList()): - self.processSample(sample) - progress.report("Processed sample " + str(i + 1) + " of " + str(sampleCount)) - - def processSample(self, poldiSample): - sampleList = poldiSample.runList() - - for dataPoint in sampleList: - self.processDataPoint(dataPoint) - - def processDataPoint(self, dataPointTuple): - self.loadDataPoint(dataPointTuple) - self.runPoldiAnalysis(dataPointTuple[0]) - - def loadDataPoint(self, dataPointTuple): - dataWorkspaceName = self.prefixes['data'] + str(dataPointTuple[0]) - - rawWorkspaceNames = [ - self.prefixes['raw'] + str(x) for x in dataPointTuple[1]] - - for numor,rawWsName in zip(dataPointTuple[1], rawWorkspaceNames): - LoadSINQ(Instrument="POLDI", Year=2014, - Numor=numor, OutputWorkspace=rawWsName) - LoadInstrument(rawWsName, InstrumentName="POLDI") - - if len(dataPointTuple[1]) > 1: - PoldiMerge(rawWorkspaceNames, OutputWorkspace=dataWorkspaceName) - - for ws in rawWorkspaceNames: - DeleteWorkspace(ws) - - else: - RenameWorkspace(rawWorkspaceNames[0], OutputWorkspace=dataWorkspaceName) - - return dataWorkspaceName - - def runPoldiAnalysis(self, dataPointName): - dataWorkspaceName = self.prefixes['data'] + str(dataPointName) - - correlationWsName = dataWorkspaceName + self.suffixes['correlation'] - PoldiAutoCorrelation(dataWorkspaceName, wlenmin=1.1, wlenmax=5.0, - OutputWorkspace=correlationWsName) - - peakSearchWsName = dataWorkspaceName + self.suffixes['raw_peaks'] - PoldiPeakSearch(correlationWsName, OutputWorkspace=peakSearchWsName) - - DeleteTableRows(peakSearchWsName, - self.getProperty("PeakNumber").valueAsStr + '-30') - - peakFit1DWsName = dataWorkspaceName + self.suffixes['fit_peaks_1d'] - PoldiFitPeaks1D(correlationWsName, PoldiPeakTable=peakSearchWsName, - OutputWorkspace=peakFit1DWsName) - - peakFit2DWsName = dataWorkspaceName + self.suffixes['fit_peaks_2d'] - spectrum2DCalc = dataWorkspaceName + self.suffixes['calculated_2d'] - PoldiFitPeaks2D(dataWorkspaceName, PoldiPeakWorkspace=peakFit1DWsName, - MaximumIterations=100, OutputWorkspace=spectrum2DCalc, - RefinedPoldiPeakWorkspace=peakFit2DWsName) - - residualsWsName = dataWorkspaceName + self.suffixes['residuals'] - PoldiAnalyseResiduals(dataWorkspaceName, spectrum2DCalc, - OutputWorkspace=residualsWsName, - MaxIterations=5) - -AlgorithmFactory.subscribe(PoldiBatchFitIndividualPeaks) \ No newline at end of file From 1016050880d3ec8147a3226a546a3081003982bf Mon Sep 17 00:00:00 2001 From: Andrei Savici Date: Wed, 18 Feb 2015 11:27:27 -0500 Subject: [PATCH 275/414] Update control python-sphinx-bootstrap-theme was added to 1.2.3, without updating the version number. Meanwhile, 1.2.4 was created, that does not includee that package --- .../deb/mantid-developer/mantid-developer-1.2.4/DEBIAN/control | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.4/DEBIAN/control b/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.4/DEBIAN/control index 7eb31c754324..b9feb3ebcfd4 100644 --- a/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.4/DEBIAN/control +++ b/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.4/DEBIAN/control @@ -3,7 +3,7 @@ Version: 1.2.4 Section: main Priority: optional Architecture: all -Depends: git, clang, cmake-qt-gui(>=2.8.12), qt4-qmake, qt4-dev-tools, libqt4-dbg, libpoco-dev(>=1.4.2), libboost-all-dev, libboost-dbg, libnexus0-dev, libgoogle-perftools-dev, libqwt5-qt4-dev, libqwtplot3d-qt4-dev, python-qt4-dev, libgsl0-dev, liboce-visualization-dev, libmuparser-dev, python-numpy, libssl-dev, libqscintilla2-dev, texlive,texlive-latex-extra, dvipng, libhdf4-dev, doxygen, python-sphinx, python-scipy, ipython-qtconsole (>=1.2.0), libhdf5-dev, libhdf4-dev, libpococrypto11-dbg, libpocodata11-dbg, libpocofoundation11-dbg, libpocomysql11-dbg, libpoconet11-dbg, libpoconetssl11-dbg, libpocoodbc11-dbg, libpocosqlite11-dbg, libpocoutil11-dbg, libpocoxml11-dbg, libpocozip11-dbg, python-qt4-dbg, qt4-default, ninja-build, libjsoncpp-dev, python-dateutil, graphviz +Depends: git, clang, cmake-qt-gui(>=2.8.12), qt4-qmake, qt4-dev-tools, libqt4-dbg, libpoco-dev(>=1.4.2), libboost-all-dev, libboost-dbg, libnexus0-dev, libgoogle-perftools-dev, libqwt5-qt4-dev, libqwtplot3d-qt4-dev, python-qt4-dev, libgsl0-dev, liboce-visualization-dev, libmuparser-dev, python-numpy, libssl-dev, libqscintilla2-dev, texlive,texlive-latex-extra, dvipng, libhdf4-dev, doxygen, python-sphinx, python-scipy, ipython-qtconsole (>=1.2.0), libhdf5-dev, libhdf4-dev, libpococrypto11-dbg, libpocodata11-dbg, libpocofoundation11-dbg, libpocomysql11-dbg, libpoconet11-dbg, libpoconetssl11-dbg, libpocoodbc11-dbg, libpocosqlite11-dbg, libpocoutil11-dbg, libpocoxml11-dbg, libpocozip11-dbg, python-qt4-dbg, qt4-default, ninja-build, libjsoncpp-dev, python-dateutil, python-sphinx-bootstrap-theme, graphviz Installed-Size: 0 Maintainer: Mantid Project Description: Installs all packages required for a Mantid developer From 50140bf89c0d79305a62d1af358f7a0f9520fc96 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Wed, 18 Feb 2015 16:38:41 +0000 Subject: [PATCH 276/414] refs #11056. Fix issue with python exports. --- .../mantid/api/src/Exports/IPeak.cpp | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp index 0d6e83ecca35..3b50c57c7c4f 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp @@ -10,11 +10,21 @@ Mantid::Geometry::PeakShape_sptr getPeakShape(IPeak &peak) { // Use clone to make a copy of the PeakShape. return Mantid::Geometry::PeakShape_sptr(peak.getPeakShape().clone()); } -void setQLabFrame(IPeak &peak, Mantid::Kernel::V3D qLabFrame, double distance) { - // Set the qlab frame +void setQLabFrame1(IPeak &peak, Mantid::Kernel::V3D qLabFrame) { + // Set the q lab frame + return peak.setQLabFrame(qLabFrame); +} +void setQLabFrame2(IPeak &peak, Mantid::Kernel::V3D qLabFrame, double distance) { + // Set the q lab frame return peak.setQLabFrame(qLabFrame, distance); } -void setQSampleFrame(IPeak &peak, Mantid::Kernel::V3D qSampleFrame, double distance) { + +void setQSampleFrame1(IPeak &peak, Mantid::Kernel::V3D qSampleFrame) { + // Set the qsample frame + return peak.setQSampleFrame(qSampleFrame); +} + +void setQSampleFrame2(IPeak &peak, Mantid::Kernel::V3D qSampleFrame, double distance) { // Set the qsample frame return peak.setQSampleFrame(qSampleFrame, distance); } @@ -47,10 +57,10 @@ void export_IPeak() "Using the instrument set in the peak, perform ray tracing to find the exact detector.") .def("getQSampleFrame", &IPeak::getQSampleFrame, "Return the Q change (of the lattice, k_i - k_f) for this peak." "The Q is in the Sample frame: the goniometer rotation WAS taken out. ") - .def("setQLabFrame", (void (IPeak::*)(Mantid::Kernel::V3D))&IPeak::setQLabFrame, "Set the peak using the peak's position in reciprocal space, in the lab frame.") - .def("setQLabFrame", setQLabFrame, "Set the peak using the peak's position in reciprocal space, in the lab frame. Detector distance explicitly supplied.") // two argument overload - .def("setQSampleFrame", (void (IPeak::*)(Mantid::Kernel::V3D))&IPeak::setQSampleFrame, "Set the peak using the peak's position in reciprocal space, in the sample frame.") - .def("setQSampleFrame", setQSampleFrame, "Set the peak using the peak's position in reciprocal space, in the sample frame.") + .def("setQLabFrame", setQLabFrame1, "Set the peak using the peak's position in reciprocal space, in the lab frame.") + .def("setQLabFrame", setQLabFrame2, "Set the peak using the peak's position in reciprocal space, in the lab frame. Detector distance explicitly supplied.") // two argument overload + .def("setQSampleFrame", setQSampleFrame1, "Set the peak using the peak's position in reciprocal space, in the sample frame.") + .def("setQSampleFrame", setQSampleFrame2, "Set the peak using the peak's position in reciprocal space, in the sample frame. Detector distance explicitly supplied.") .def("setWavelength", &IPeak::setWavelength, "Set the incident wavelength of the neutron. Calculates the energy from this assuming elastic scattering.") .def("getWavelength", &IPeak::getWavelength, "Return the incident wavelength") .def("getScattering", &IPeak::getScattering, "Calculate the scattering angle of the peak") From d89e750da68b69a75a99d07de7a5841df3ccd70b Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Wed, 18 Feb 2015 17:17:28 +0000 Subject: [PATCH 277/414] refs #11056. Fix GCC warnings. --- Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h | 4 ++-- .../PythonInterface/mantid/api/src/Exports/IPeak.cpp | 12 ++++++------ Code/Mantid/MantidQt/SliceViewer/test/MockObjects.h | 4 ++-- .../Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h b/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h index 0ceb44554efc..0ee7a8d085ff 100644 --- a/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h +++ b/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h @@ -51,9 +51,9 @@ class MANTID_API_DLL IPeak { virtual bool findDetector() = 0; virtual void setQSampleFrame(Mantid::Kernel::V3D QSampleFrame, - boost::optional detectorDistance = boost::optional()) = 0; + boost::optional detectorDistance) = 0; virtual void setQLabFrame(Mantid::Kernel::V3D QLabFrame, - boost::optional detectorDistance = boost::optional()) = 0; + boost::optional detectorDistance) = 0; virtual void setWavelength(double wavelength) = 0; virtual double getWavelength() const = 0; diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp index 3b50c57c7c4f..e12912bc5a0a 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp @@ -11,21 +11,21 @@ Mantid::Geometry::PeakShape_sptr getPeakShape(IPeak &peak) { return Mantid::Geometry::PeakShape_sptr(peak.getPeakShape().clone()); } void setQLabFrame1(IPeak &peak, Mantid::Kernel::V3D qLabFrame) { - // Set the q lab frame - return peak.setQLabFrame(qLabFrame); + // Set the q lab frame. No explicit detector distance. + return peak.setQLabFrame(qLabFrame, boost::optional()); } void setQLabFrame2(IPeak &peak, Mantid::Kernel::V3D qLabFrame, double distance) { - // Set the q lab frame + // Set the q lab frame. Detector distance specified. return peak.setQLabFrame(qLabFrame, distance); } void setQSampleFrame1(IPeak &peak, Mantid::Kernel::V3D qSampleFrame) { - // Set the qsample frame - return peak.setQSampleFrame(qSampleFrame); + // Set the qsample frame. No explicit detector distance. + return peak.setQSampleFrame(qSampleFrame, boost::optional()); } void setQSampleFrame2(IPeak &peak, Mantid::Kernel::V3D qSampleFrame, double distance) { - // Set the qsample frame + // Set the qsample frame. Detector distance specified. return peak.setQSampleFrame(qSampleFrame, distance); } diff --git a/Code/Mantid/MantidQt/SliceViewer/test/MockObjects.h b/Code/Mantid/MantidQt/SliceViewer/test/MockObjects.h index da6b3e1a4c57..42cb6aa2ddcf 100644 --- a/Code/Mantid/MantidQt/SliceViewer/test/MockObjects.h +++ b/Code/Mantid/MantidQt/SliceViewer/test/MockObjects.h @@ -200,9 +200,9 @@ class MockPeakTransformFactory : public PeakTransformFactory MOCK_METHOD0(findDetector, bool()); MOCK_METHOD2(setQSampleFrame, - void(Mantid::Kernel::V3D QSampleFrame, double detectorDistance)); + void(Mantid::Kernel::V3D QSampleFrame, boost::optional detectorDistance)); MOCK_METHOD2(setQLabFrame, - void(Mantid::Kernel::V3D QLabFrame, double detectorDistance)); + void(Mantid::Kernel::V3D QLabFrame, boost::optional detectorDistance)); MOCK_METHOD1(setWavelength, void(double wavelength)); MOCK_CONST_METHOD0(getWavelength, diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h index 025bf2135fd1..5e4fb59411a2 100644 --- a/Code/Mantid/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h +++ b/Code/Mantid/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h @@ -36,7 +36,7 @@ class MockPeaksWorkspace : public PeaksWorkspace MOCK_METHOD1(addPeak, void (const IPeak& ipeak)); MOCK_METHOD1(getPeak, Mantid::DataObjects::Peak & (int peakNum)); MOCK_CONST_METHOD1(getPeak, const Mantid::DataObjects::Peak & (int peakNum)); - MOCK_CONST_METHOD2(createPeak, Mantid::API::IPeak* (Mantid::Kernel::V3D QLabFrame, double detectorDistance)); + MOCK_CONST_METHOD2(createPeak, Mantid::API::IPeak* (Mantid::Kernel::V3D QLabFrame, boost::optional detectorDistance)); }; //===================================================================================== From 7d0c670476ec29709cd94ce3a7d61dbe5f0a8883 Mon Sep 17 00:00:00 2001 From: Nick Draper Date: Wed, 18 Feb 2015 17:18:18 +0000 Subject: [PATCH 278/414] re #11069 fix warning --- .../src/ScriptRepositoryImpl.cpp | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp b/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp index 8f016f75e014..d03969c8659d 100644 --- a/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp +++ b/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp @@ -64,23 +64,6 @@ namespace { Kernel::Logger g_log("ScriptRepositoryImpl"); } -static ScriptRepoException pocoException(const std::string &info, - Poco::Exception &ex) { - std::stringstream ss; - if (dynamic_cast(&ex)) - ss << info << ", because you do not have access to write to this path :" - << ex.message() << std::ends; - else if (dynamic_cast(&ex)) - ss << info << ". The definition of the remote url is not correct. Please " - "check the Mantid settings, the ScriptRepository entry. " - "Current: " << ex.message() << std::ends; - else { - ss << info << " . Unknown:" << ex.displayText() << std::ends; - } - - return ScriptRepoException(ss.str(), ex.displayText()); -} - const char *timeformat = "%Y-%b-%d %H:%M:%S"; const char *emptyURL = From 5608f05abe00ec22fcaafe221fdf9ca72af76de2 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Wed, 18 Feb 2015 17:47:33 +0000 Subject: [PATCH 279/414] Re #9556 Code cleaning --- .../MantidCurveFitting/DynamicKuboToyabe.h | 12 ++----- .../CurveFitting/src/DynamicKuboToyabe.cpp | 32 +++++-------------- 2 files changed, 11 insertions(+), 33 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h index 261905dc46ce..34f8cb9fbfbb 100644 --- a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h +++ b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h @@ -9,21 +9,15 @@ #include "MantidAPI/IFunctionWithLocation.h" #include -//#include "MantidAPI/ParamFunction.h" -//#include "MantidAPI/IPeakFunction.h" - -//#include "MantidAPI/IFunctionMW.h" -//#include "MantidAPI/IFunction1D.h" - namespace Mantid { namespace CurveFitting { /** - Provide Dynamic Kubo Toyabe function interface to IPeakFunction for muon scientists. + Provide Dynamic Kubo Toyabe function interface to IFunction1D for muon scientists. - @author Karl Palmen, ISIS, RAL - @date 21/03/2012 + @author Raquel Alvarez, ISIS, RAL + @date 18/02/2015 Copyright © 2007-2012 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index cba5034c2405..c69970ae783c 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -16,15 +16,6 @@ using namespace API; DECLARE_FUNCTION(DynamicKuboToyabe) -// ** MODIFY THIS ** -// Here specify/declare the parameters of your Fit Function -// -// declareParameter takes three arguments: -// -// 1st: The name of the parameter -// 2nd: The default (initial) value of the parameter -// 3rd: A description of the parameter (optional) -// void DynamicKuboToyabe::init() { declareParameter("Asym", 0.2, "Amplitude at time 0"); @@ -40,25 +31,18 @@ double ZFKT (const double x, const double G){ return (0.3333333333 + 0.6666666667*exp(-0.5*q)*(1-q)); } -// Static Non-Zero field Kubo Toyabe relaxation function -//double HKT (const double x, const double G, const double F) -//{ -// throw std::runtime_error("HKT not implemented yet"); -//} - // Dynamic Kubo-Toyabe double getDKT (double t, double G, double v){ const int tsmax = 656; // Length of the time axis, 32 us of valid data const double eps = 0.05; // Bin width for calculations - // const int stk = 25; // Not used for the moment static double oldG=-1., oldV=-1.; static std::vector gStat(tsmax), gDyn(tsmax); if ( (G != oldG) || (v != oldV) ){ - + // If G or v have changed with respect to the // previous call, we need to re-do the computations @@ -110,8 +94,8 @@ void DynamicKuboToyabe::function1D(double* out, const double* xValues, const siz const double& v = fabs(getParameter("Nu")); - // Zero hopping rate - if (v == 0.0) { + // Zero hopping rate + if (v == 0.0) { // Zero external field if ( F == 0.0 ){ @@ -126,10 +110,10 @@ void DynamicKuboToyabe::function1D(double* out, const double* xValues, const siz //} throw std::runtime_error("HKT() not implemented yet"); } - } + } // Non-zero hopping rate - else { + else { if ( F==0.0 ) { @@ -137,13 +121,13 @@ void DynamicKuboToyabe::function1D(double* out, const double* xValues, const siz out[i] = A*getDKT(xValues[i],G,v); } - } else { + } else { - // Non-zero field + // Non-zero field throw std::runtime_error("HKT() not implemented yet"); } - } // else hopping rate != 0 + } // else hopping rate != 0 } From 9c8a396348e9271cdb52d3d99f0668e3012aa546 Mon Sep 17 00:00:00 2001 From: Steven Hahn Date: Wed, 18 Feb 2015 13:00:02 -0500 Subject: [PATCH 280/414] Refs #11117. Generate header file with Poco version. --- Code/Mantid/Build/CMake/FindPoco.cmake | 12 +++++++ Code/Mantid/Framework/Kernel/CMakeLists.txt | 8 +++++ .../Kernel/inc/MantidKernel/PocoVersion.h.in | 33 +++++++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in diff --git a/Code/Mantid/Build/CMake/FindPoco.cmake b/Code/Mantid/Build/CMake/FindPoco.cmake index 63c811ccf494..445dc1ffda23 100644 --- a/Code/Mantid/Build/CMake/FindPoco.cmake +++ b/Code/Mantid/Build/CMake/FindPoco.cmake @@ -61,13 +61,25 @@ if( POCO_INCLUDE_DIR ) file ( STRINGS ${VERSION_FILE} POCO_VERSION REGEX ${VERS_REGEX} ) # pull out just the part after the 0x string( REGEX REPLACE ${VERS_REGEX} "\\1" POCO_VERSION ${POCO_VERSION} ) + # Pretty format string( SUBSTRING ${POCO_VERSION} 0 2 POCO_VERSION_MAJOR ) string( REGEX REPLACE "^0" "" POCO_VERSION_MAJOR ${POCO_VERSION_MAJOR} ) + if ("${POCO_VERSION_MAJOR}" STREQUAL "") + set( POCO_VERSION_MAJOR "0") + endif() + string( SUBSTRING ${POCO_VERSION} 2 2 POCO_VERSION_MINOR ) string( REGEX REPLACE "^0" "" POCO_VERSION_MINOR ${POCO_VERSION_MINOR} ) + if ("${POCO_VERSION_MINOR}" STREQUAL "") + set( POCO_VERSION_MINOR "0") + endif() + string( SUBSTRING ${POCO_VERSION} 4 2 POCO_VERSION_PATCH ) string( REGEX REPLACE "^0" "" POCO_VERSION_PATCH ${POCO_VERSION_PATCH} ) + if ("${POCO_VERSION_PATCH}" STREQUAL "") + set( POCO_VERSION_PATCH "0") + endif() set ( POCO_VERSION "${POCO_VERSION_MAJOR}.${POCO_VERSION_MINOR}.${POCO_VERSION_PATCH}" ) endif() diff --git a/Code/Mantid/Framework/Kernel/CMakeLists.txt b/Code/Mantid/Framework/Kernel/CMakeLists.txt index d8193e74dae8..887bba027157 100644 --- a/Code/Mantid/Framework/Kernel/CMakeLists.txt +++ b/Code/Mantid/Framework/Kernel/CMakeLists.txt @@ -196,6 +196,7 @@ set ( INC_FILES inc/MantidKernel/NullValidator.h inc/MantidKernel/ParaViewVersion.h inc/MantidKernel/PhysicalConstants.h + inc/MantidKernel/PocoVersion.h inc/MantidKernel/ProgressBase.h inc/MantidKernel/ProgressText.h inc/MantidKernel/Property.h @@ -416,6 +417,13 @@ if ( NOT NOT_GIT_REPO OR NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/src/MantidVersio ) endif () +########################################################################### +# This section deals with creating the PocoVersion implementation +########################################################################### +configure_file ( ${CMAKE_CURRENT_SOURCE_DIR}/inc/MantidKernel/PocoVersion.h.in + ${CMAKE_CURRENT_SOURCE_DIR}/inc/MantidKernel/PocoVersion.h +) + ########################################################################### # This section deals with creating the ParaViewVersion implementation ########################################################################### diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in b/Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in new file mode 100644 index 000000000000..808de4e6b23a --- /dev/null +++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in @@ -0,0 +1,33 @@ +#ifndef MANTID_KERNEL_POCOVERSION_H_ +#define MANTID_KERNEL_POCOVERSION_H_ + +/** Macros defining Poco version used to compile Mantid. + + Copyright © 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge + National Laboratory & European Spallation Source + + This file is part of Mantid. + + Mantid is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + Mantid is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + File change history is stored at: . + Code Documentation is available at: + */ +/// Major version of Poco used to build Mantid. +#define POCO_VERSION_MAJOR @POCO_VERSION_MAJOR@ +/// Minor version of Poco used to build Mantid. +#define POCO_VERSION_MINOR @POCO_VERSION_MINOR@ +/// Patch version of Poco used to build Mantid. +#define POCO_VERSION_PATCH @POCO_VERSION_PATCH@ +#endif /* MANTID_KERNEL_POCOVERSION_H_ */ From 340597e03584335653925e087602d94792cdf804 Mon Sep 17 00:00:00 2001 From: Steven Hahn Date: Wed, 18 Feb 2015 13:09:34 -0500 Subject: [PATCH 281/414] Refs #11117. clang-format changes to PocoVersion.h.in --- .../Framework/Kernel/inc/MantidKernel/PocoVersion.h.in | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in b/Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in index 808de4e6b23a..b82ef5ba092e 100644 --- a/Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in +++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in @@ -25,9 +25,9 @@ Code Documentation is available at: */ /// Major version of Poco used to build Mantid. -#define POCO_VERSION_MAJOR @POCO_VERSION_MAJOR@ +#define POCO_VERSION_MAJOR @POCO_VERSION_MAJOR @ /// Minor version of Poco used to build Mantid. -#define POCO_VERSION_MINOR @POCO_VERSION_MINOR@ +#define POCO_VERSION_MINOR @POCO_VERSION_MINOR @ /// Patch version of Poco used to build Mantid. -#define POCO_VERSION_PATCH @POCO_VERSION_PATCH@ +#define POCO_VERSION_PATCH @POCO_VERSION_PATCH @ #endif /* MANTID_KERNEL_POCOVERSION_H_ */ From ac5934cce72ce9052fe0aadff750b76dbf05d042 Mon Sep 17 00:00:00 2001 From: Steven Hahn Date: Wed, 18 Feb 2015 13:16:41 -0500 Subject: [PATCH 282/414] Refs #11117. fix lines broken by clang-format --- .../Framework/Kernel/inc/MantidKernel/PocoVersion.h.in | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in b/Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in index b82ef5ba092e..41dc2720a436 100644 --- a/Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in +++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in @@ -25,9 +25,9 @@ Code Documentation is available at: */ /// Major version of Poco used to build Mantid. -#define POCO_VERSION_MAJOR @POCO_VERSION_MAJOR @ +#define POCO_VERSION_MAJOR @POCO_VERSION_MAJOR@ /// Minor version of Poco used to build Mantid. -#define POCO_VERSION_MINOR @POCO_VERSION_MINOR @ +#define POCO_VERSION_MINOR @POCO_VERSION_MINOR@ /// Patch version of Poco used to build Mantid. -#define POCO_VERSION_PATCH @POCO_VERSION_PATCH @ +#define POCO_VERSION_PATCH @POCO_VERSION_PATCH@ #endif /* MANTID_KERNEL_POCOVERSION_H_ */ From 6a32a8324a1d49e858ff034f0b864cfcba4e5adc Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Wed, 18 Feb 2015 20:42:09 +0100 Subject: [PATCH 283/414] Refs #11104. Reverting clang-format on python export The clang-format command seemed to cause a compilation error on all systems. Going back to the old format fixes it. --- .../mantid/api/src/Exports/IPeakFunction.cpp | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp index 0d1a5c71e0a9..c8589a927a72 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp @@ -7,18 +7,16 @@ using Mantid::API::IPeakFunction; using Mantid::PythonInterface::IPeakFunctionAdapter; using namespace boost::python; -void export_IPeakFunction() { - class_, - boost::shared_ptr, boost::noncopyable>( - "IPeakFunction") - .def("functionLocal", - (object (IPeakFunctionAdapter::*)(const object &)const) & - IPeakFunction::functionLocal, - "Calculate the values of the function for the given x values. The " - "output should be stored in the out array") +void export_IPeakFunction() +{ + class_, boost::shared_ptr, + boost::noncopyable>("IPeakFunction") + .def("functionLocal", (object (IPeakFunctionAdapter::*)(const object &)const)&IPeakFunction::functionLocal, + "Calculate the values of the function for the given x values. The output should be stored in the out array") .def("intensity", &IPeakFunction::intensity, "Returns the integral intensity of the peak function.") .def("setIntensity", &IPeakFunction::setIntensity, "Changes the integral intensity of the peak function by setting its " - "height."); + "height.") + ; } From 51e7bc512adf2bdc294ebe8eaf159b25177e86fa Mon Sep 17 00:00:00 2001 From: Steven Hahn Date: Wed, 18 Feb 2015 15:01:30 -0500 Subject: [PATCH 284/414] Refs #11117. replace if statements with more complex regex. --- Code/Mantid/Build/CMake/FindPoco.cmake | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/Code/Mantid/Build/CMake/FindPoco.cmake b/Code/Mantid/Build/CMake/FindPoco.cmake index 445dc1ffda23..978e770fa8c8 100644 --- a/Code/Mantid/Build/CMake/FindPoco.cmake +++ b/Code/Mantid/Build/CMake/FindPoco.cmake @@ -64,23 +64,11 @@ if( POCO_INCLUDE_DIR ) # Pretty format string( SUBSTRING ${POCO_VERSION} 0 2 POCO_VERSION_MAJOR ) - string( REGEX REPLACE "^0" "" POCO_VERSION_MAJOR ${POCO_VERSION_MAJOR} ) - if ("${POCO_VERSION_MAJOR}" STREQUAL "") - set( POCO_VERSION_MAJOR "0") - endif() - + string( REGEX REPLACE "^0\(.\)" "\\1" POCO_VERSION_MAJOR ${POCO_VERSION_MAJOR} ) string( SUBSTRING ${POCO_VERSION} 2 2 POCO_VERSION_MINOR ) - string( REGEX REPLACE "^0" "" POCO_VERSION_MINOR ${POCO_VERSION_MINOR} ) - if ("${POCO_VERSION_MINOR}" STREQUAL "") - set( POCO_VERSION_MINOR "0") - endif() - + string( REGEX REPLACE "^0\(.\)" "\\1" POCO_VERSION_MINOR ${POCO_VERSION_MINOR} ) string( SUBSTRING ${POCO_VERSION} 4 2 POCO_VERSION_PATCH ) - string( REGEX REPLACE "^0" "" POCO_VERSION_PATCH ${POCO_VERSION_PATCH} ) - if ("${POCO_VERSION_PATCH}" STREQUAL "") - set( POCO_VERSION_PATCH "0") - endif() - + string( REGEX REPLACE "^0\(.\)" "\\1" POCO_VERSION_PATCH ${POCO_VERSION_PATCH} ) set ( POCO_VERSION "${POCO_VERSION_MAJOR}.${POCO_VERSION_MINOR}.${POCO_VERSION_PATCH}" ) endif() From 4181b1f3c1c8455bb5b2299f677d038b93fe74b7 Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Wed, 18 Feb 2015 21:15:14 +0100 Subject: [PATCH 285/414] Refs #11104. Replacing delta argument with places It seems that the unittest module on RHEL6 does not know the delta-parameter for assertAlmostEquals yet, so instead the number of places is used. --- .../test/python/mantid/api/IPeakFunctionTest.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py index 2ac78d6d5376..937f02a18f3d 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py @@ -82,14 +82,14 @@ def test_get_set_intensity(self): # This is a rectangle function with height 2 and width 3, centered # around 1.0. The intensity should be 6.0 (height * width) - self.assertAlmostEquals(func.intensity(), 6.0, delta=1e-10) + self.assertAlmostEquals(func.intensity(), 6.0, places=10) # Setting the intensity only changes height, not width func.setIntensity(12.0) self.assertEquals(func.fwhm(), 3.0) - self.assertAlmostEquals(func.height(), 4.0, delta=1e-10) - self.assertAlmostEquals(func.intensity(), 12.0, delta=1e-10) + self.assertAlmostEquals(func.height(), 4.0, places=10) + self.assertAlmostEquals(func.intensity(), 12.0, places=10) if __name__ == '__main__': unittest.main() From 4d2bd72846faf3d6d5b3b74768249c89b8e7d2c7 Mon Sep 17 00:00:00 2001 From: Steven Hahn Date: Wed, 18 Feb 2015 16:11:50 -0500 Subject: [PATCH 286/414] Refs #11120. For the second workspace, rename paramMap with paramMap2. --- .../test/LoadGSASInstrumentFileTest.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Code/Mantid/Framework/DataHandling/test/LoadGSASInstrumentFileTest.h b/Code/Mantid/Framework/DataHandling/test/LoadGSASInstrumentFileTest.h index 7545b11fa3a6..0ae94946fa50 100644 --- a/Code/Mantid/Framework/DataHandling/test/LoadGSASInstrumentFileTest.h +++ b/Code/Mantid/Framework/DataHandling/test/LoadGSASInstrumentFileTest.h @@ -274,35 +274,35 @@ class LoadGSASInstrumentFileTest : public CxxTest::TestSuite // Now check second workspace ws = boost::dynamic_pointer_cast(gws->getItem(1)); - paramMap = ws->instrumentParameters(); + Mantid::Geometry::ParameterMap& paramMap2 = ws->instrumentParameters(); instr = ws->getInstrument(); - // Check Alpha0 parameter - param = paramMap.get(&(*instr), "Alpha0", "fitting"); + // Check Alpha0 parameter + param = paramMap2.get(&(*instr), "Alpha0", "fitting"); fitParam = param->value(); TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 0.001); // Check Alpha1 parameter - param = paramMap.get(&(*instr), "Alpha1", "fitting"); + param = paramMap2.get(&(*instr), "Alpha1", "fitting"); fitParam = param->value(); TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 0.22); // Check Beta0 parameter - param = paramMap.get(&(*instr), "Beta0", "fitting"); + param = paramMap2.get(&(*instr), "Beta0", "fitting"); fitParam = param->value(); TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 32.7927); // Check Beta1 parameter - param = paramMap.get(&(*instr), "Kappa", "fitting"); + param = paramMap2.get(&(*instr), "Kappa", "fitting"); fitParam = param->value(); TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 52.4205); // Check SigmsSquared parameter // This is a formula, so values are not exact - param = paramMap.get(&(*instr), "SigmaSquared", "fitting"); + param = paramMap2.get(&(*instr), "SigmaSquared", "fitting"); fitParam = param->value(); TS_ASSERT_DELTA( fitParam.getValue(0.0), 0.04, 0.000001); TS_ASSERT_DELTA( fitParam.getValue(0.5), 21840.741796, 0.000001); // Check Gamma parameter // Although this is a formula, all coefficients should be zero // and so values should be exactly 0 as well - param = paramMap.get(&(*instr), "Gamma", "fitting"); + param = paramMap2.get(&(*instr), "Gamma", "fitting"); fitParam = param->value(); TS_ASSERT_EQUALS( fitParam.getValue( 0.0 ), 0.0); TS_ASSERT_EQUALS( fitParam.getValue( 0.0 ), 0.0); From d81decaf6fab8deea59ca22301c366095eafb07c Mon Sep 17 00:00:00 2001 From: Andrei Savici Date: Wed, 18 Feb 2015 17:19:53 -0500 Subject: [PATCH 287/414] Reduce pylint warnings. Refs #10945 --- .../plugins/algorithms/BASISReduction311.py | 186 ++--- .../CalibrateRectangularDetectors.py | 24 +- .../plugins/algorithms/CheckForSampleLogs.py | 3 +- .../plugins/algorithms/DSFinterp.py | 176 ++--- .../plugins/algorithms/DakotaChiSquared.py | 106 ++- .../plugins/algorithms/EnginXCalibrate.py | 52 +- .../plugins/algorithms/EnginXCalibrateFull.py | 128 ++-- .../plugins/algorithms/EnginXFitPeaks.py | 104 +-- .../plugins/algorithms/EnginXFocus.py | 118 +-- .../algorithms/ExaminePowderDiffProfile.py | 2 +- .../plugins/algorithms/ExportExperimentLog.py | 22 +- .../algorithms/ExportSampleLogsToCSVFile.py | 4 +- .../algorithms/FindReflectometryLines.py | 122 +-- .../plugins/algorithms/LoadFullprofFile.py | 56 +- .../plugins/algorithms/LoadSINQFile.py | 2 +- .../plugins/algorithms/LoadVesuvio.py | 10 +- .../plugins/algorithms/MaskBTP.py | 4 +- .../algorithms/MaskWorkspaceToCalFile.py | 92 +-- .../plugins/algorithms/MergeCalFiles.py | 208 ++--- .../PDDetermineCharacterizations.py | 42 +- .../plugins/algorithms/PearlMCAbsorption.py | 2 +- .../plugins/algorithms/PoldiMerge.py | 22 +- .../plugins/algorithms/RefLReduction.py | 2 +- .../plugins/algorithms/SaveVulcanGSS.py | 100 +-- .../algorithms/SelectPowderDiffPeaks.py | 2 +- .../plugins/algorithms/SortXAxis.py | 4 +- .../algorithms/WorkflowAlgorithms/CutMD.py | 182 ++--- .../WorkflowAlgorithms/HFIRSANSReduction.py | 18 +- .../WorkflowAlgorithms/MuscatData.py | 116 +-- .../WorkflowAlgorithms/MuscatFunc.py | 156 ++-- .../NormaliseByThickness.py | 2 +- .../OSIRISDiffractionReduction.py | 2 +- .../algorithms/WorkflowAlgorithms/QLines.py | 142 ++-- .../algorithms/WorkflowAlgorithms/Quest.py | 170 ++--- .../WorkflowAlgorithms/REFLReprocess.py | 12 +- .../ReactorSANSResolution.py | 2 +- .../algorithms/WorkflowAlgorithms/ResNorm.py | 108 +-- .../SANSAzimuthalAverage1D.py | 12 +- .../WorkflowAlgorithms/SANSReduction.py | 22 +- .../WorkflowAlgorithms/TransmissionUtils.py | 2 +- .../plugins/algorithms/sfCalculator.py | 26 +- .../plugins/functions/ChudleyElliot.py | 4 +- .../plugins/functions/DSFinterp1DFit.py | 230 +++--- .../functions/Examples/Example1DFunction.py | 4 +- .../functions/Examples/ExamplePeakFunction.py | 8 +- .../plugins/functions/FickDiffusion.py | 2 +- .../plugins/functions/Guinier.py | 4 +- .../plugins/functions/GuinierPorod.py | 20 +- .../plugins/functions/HallRoss.py | 4 +- .../plugins/functions/Lorentz.py | 2 +- .../plugins/functions/Porod.py | 2 +- .../plugins/functions/TeixeiraWater.py | 4 +- .../Examples/TubeCalibDemoMaps_All.py | 8 +- .../Examples/TubeCalibDemoMerlin.py | 130 ++-- .../Examples/TubeCalibDemoWish_5panels.py | 6 +- .../Examples/TubeCalibDemoWish_Simple.py | 6 +- Code/Mantid/scripts/Calibration/ideal_tube.py | 46 +- Code/Mantid/scripts/Calibration/tube_calib.py | 82 +- Code/Mantid/scripts/Calibration/tube_spec.py | 60 +- .../Mantid/scripts/Engineering/EnginXUtils.py | 16 +- Code/Mantid/scripts/FilterEvents.py | 12 +- .../scripts/FilterEvents/MplFigureCanvas.py | 8 +- .../scripts/FilterEvents/Ui_MainWindow.py | 4 +- .../scripts/FilterEvents/eventFilterGUI.py | 210 +++--- .../Inelastic/Direct/CommonFunctions.py | 6 +- .../Direct/DirectEnergyConversion.py | 714 +++++++++--------- .../Inelastic/Direct/NonIDF_Properties.py | 38 +- .../Inelastic/Direct/PropertiesDescriptors.py | 650 ++++++++-------- .../Inelastic/Direct/PropertyManager.py | 306 ++++---- .../Inelastic/Direct/ReductionHelpers.py | 260 +++---- .../Inelastic/Direct/ReductionWrapper.py | 190 ++--- .../scripts/Inelastic/Direct/RunDescriptor.py | 432 +++++------ .../scripts/Inelastic/Direct/__init__.py | 4 +- .../scripts/Inelastic/Direct/dgreduce.py | 8 +- .../scripts/Inelastic/Direct/diagnostics.py | 22 +- .../Mantid/scripts/Inelastic/IndirectBayes.py | 16 +- .../scripts/Inelastic/IndirectCommon.py | 156 ++-- .../scripts/Inelastic/IndirectDataAnalysis.py | 206 ++--- .../scripts/Inelastic/IndirectMuscat.py | 328 ++++---- .../inelastic_indirect_reduction_steps.py | 12 +- Code/Mantid/scripts/Inelastic/msg_reducer.py | 4 +- .../scripts/Interface/compile_refm_ui.py | 2 +- .../scripts/Interface/compile_sans_ui.py | 2 +- .../Interface/reduction_application.py | 2 +- .../diffraction_reduction_script.py | 2 +- .../reduction/inelastic/dgs_utils.py | 2 +- .../reduction_gui/reduction/sans/data_cat.py | 2 +- .../reduction/sans/eqsans_catalog.py | 2 +- .../reduction/sans/eqsans_data_script.py | 2 +- .../reduction/sans/eqsans_options_script.py | 4 +- .../reduction/sans/hfir_catalog.py | 2 +- .../reduction/sans/hfir_options_script.py | 14 +- .../reflectometer/base_ref_reduction.py | 32 +- .../widgets/reflectometer/refm_reduction.py | 12 +- .../widgets/sans/hfir_instrument.py | 12 +- .../widgets/sans/hfir_sample_data.py | 2 +- .../widgets/sans/sans_catalog.py | 12 +- .../reduction_gui/widgets/sans/stitcher.py | 2 +- .../ui/reflectometer/refl_choose_col.py | 2 +- .../Interface/ui/reflectometer/refl_gui.py | 30 +- .../ui/reflectometer/refl_gui_run.py | 2 +- .../ui/reflectometer/refl_options.py | 2 +- .../Interface/ui/reflectometer/refl_save.py | 4 +- .../LargeScaleStructures/EQSANS_geometry.py | 2 +- .../LargeScaleStructures/REF_L_geometry.py | 2 +- .../LargeScaleStructures/ReflectometerCors.py | 74 +- .../LargeScaleStructures/geometry_writer.py | 10 +- Code/Mantid/scripts/ORNL_SANS.py | 2 +- Code/Mantid/scripts/PyChop.py | 6 +- Code/Mantid/scripts/PyChop/PyChop.py | 72 +- Code/Mantid/scripts/PyChop/PyChopGUI.py | 6 +- Code/Mantid/scripts/PyChop/fluxGUI.py | 22 +- Code/Mantid/scripts/REFL_Reduction.py | 2 +- Code/Mantid/scripts/REFL_SF_Calculator.py | 2 +- Code/Mantid/scripts/REFM_Reduction.py | 2 +- .../isis_reflectometry/combineMulti.py | 54 +- .../convert_to_wavelength.py | 2 +- .../isis_reflectometry/procedures.py | 80 +- .../scripts/SANS/ISISCommandInterface.py | 12 +- Code/Mantid/scripts/SANS/SANSUtility.py | 42 +- Code/Mantid/scripts/SANS/SANSadd2.py | 362 ++++----- Code/Mantid/scripts/SANS/isis_reducer.py | 8 +- .../scripts/SANS/isis_reduction_steps.py | 48 +- .../scripts/SCD_Reduction/ReduceDictionary.py | 78 +- .../scripts/SCD_Reduction/ReduceSCD_OneRun.py | 112 +-- .../SCD_Reduction/ReduceSCD_Parallel.py | 186 ++--- Code/Mantid/scripts/TofConverter.py | 6 +- .../scripts/Vates/Inelastic_Workflow.py | 2 +- Code/Mantid/scripts/Vates/SXD_NaCl.py | 16 +- Code/Mantid/scripts/migrate1to2.py | 2 +- Code/Mantid/scripts/reduction/instrument.py | 4 +- .../reflectometer/data_manipulation.py | 2 +- .../instruments/reflectometer/wks_utility.py | 48 +- .../instruments/sans/sans_reduction_steps.py | 2 +- Code/Tools/Pylint/pylint.cfg | 8 +- 135 files changed, 4105 insertions(+), 4108 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py index 9d59807f548d..2e60dadde08d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py @@ -26,31 +26,31 @@ def PyInit(self): self._short_inst = "BSS" self._long_inst = "BASIS" self._extension = "_event.nxs" - + self.declareProperty("RunNumbers", "", "Sample run numbers") self.declareProperty("DoIndividual", False, "Do each run individually") - self.declareProperty("NoMonitorNorm", False, + self.declareProperty("NoMonitorNorm", False, "Stop monitor normalization") - self.declareProperty("NormRunNumbers", "", "Normalization run numbers") - arrVal = FloatArrayLengthValidator(2) - self.declareProperty(FloatArrayProperty("NormWavelengthRange", DEFAULT_RANGE, + self.declareProperty("NormRunNumbers", "", "Normalization run numbers") + arrVal = FloatArrayLengthValidator(2) + self.declareProperty(FloatArrayProperty("NormWavelengthRange", DEFAULT_RANGE, arrVal, direction=Direction.Input), - "Wavelength range for normalization. default:(6.24A, 6.30A)") - self.declareProperty(FloatArrayProperty("EnergyBins", DEFAULT_BINS, - direction=Direction.Input), - "Energy transfer binning scheme (in ueV)") - self.declareProperty(FloatArrayProperty("MomentumTransferBins", - DEFAULT_BINS, - direction=Direction.Input), - "Momentum transfer binning scheme") + "Wavelength range for normalization. default:(6.24A, 6.30A)") + self.declareProperty(FloatArrayProperty("EnergyBins", DEFAULT_BINS, + direction=Direction.Input), + "Energy transfer binning scheme (in ueV)") + self.declareProperty(FloatArrayProperty("MomentumTransferBins", + DEFAULT_BINS, + direction=Direction.Input), + "Momentum transfer binning scheme") self.declareProperty(FileProperty(name="MaskFile", defaultValue="", - action=FileAction.OptionalLoad, extensions=['.xml']), - "Directory location for standard masking and grouping files.") + action=FileAction.OptionalLoad, extensions=['.xml']), + "Directory location for standard masking and grouping files.") grouping_type = ["None", "Low-Resolution", "By-Tube"] - self.declareProperty("GroupDetectors", "None", - StringListValidator(grouping_type), + self.declareProperty("GroupDetectors", "None", + StringListValidator(grouping_type), "Switch for grouping detectors") - + def PyExec(self): config['default.facility'] = "SNS" config['default.instrument'] = self._long_inst @@ -71,65 +71,65 @@ def PyExec(self): config.appendDataSearchDir(DEFAULT_MASK_GROUP_DIR) self._maskFile = DEFAULT_MASK_FILE - api.LoadMask(Instrument='BASIS', OutputWorkspace='BASIS_MASK', + api.LoadMask(Instrument='BASIS', OutputWorkspace='BASIS_MASK', InputFile=self._maskFile) - + # Work around length issue _dMask = api.ExtractMask('BASIS_MASK') self._dMask = _dMask[1] api.DeleteWorkspace(_dMask[0]) - - # Do normalization if run numbers are present - norm_runs = self.getProperty("NormRunNumbers").value - self._doNorm = bool(norm_runs) - self.log().information("Do Norm: " + str(self._doNorm)) - if self._doNorm: - if ";" in norm_runs: - raise SyntaxError("Normalization does not support run groups") - # Setup the integration (rebin) parameters - normRange = self.getProperty("NormWavelengthRange").value - self._normRange = [normRange[0], normRange[1]-normRange[0], normRange[1]] - - # Process normalization runs - self._norm_run_list = self._getRuns(norm_runs) - for norm_set in self._norm_run_list: + + # Do normalization if run numbers are present + norm_runs = self.getProperty("NormRunNumbers").value + self._doNorm = bool(norm_runs) + self.log().information("Do Norm: " + str(self._doNorm)) + if self._doNorm: + if ";" in norm_runs: + raise SyntaxError("Normalization does not support run groups") + # Setup the integration (rebin) parameters + normRange = self.getProperty("NormWavelengthRange").value + self._normRange = [normRange[0], normRange[1]-normRange[0], normRange[1]] + + # Process normalization runs + self._norm_run_list = self._getRuns(norm_runs) + for norm_set in self._norm_run_list: extra_extension = "_norm" self._normWs = self._makeRunName(norm_set[0]) self._normWs += extra_extension - self._normMonWs = self._normWs + "_monitors" + self._normMonWs = self._normWs + "_monitors" self._sumRuns(norm_set, self._normWs, self._normMonWs, extra_extension) - self._calibData(self._normWs, self._normMonWs) - - api.Rebin(InputWorkspace=self._normWs, OutputWorkspace=self._normWs, - Params=self._normRange) - api.FindDetectorsOutsideLimits(InputWorkspace=self._normWs, - OutputWorkspace="BASIS_NORM_MASK") + self._calibData(self._normWs, self._normMonWs) + + api.Rebin(InputWorkspace=self._normWs, OutputWorkspace=self._normWs, + Params=self._normRange) + api.FindDetectorsOutsideLimits(InputWorkspace=self._normWs, + OutputWorkspace="BASIS_NORM_MASK") self._run_list = self._getRuns(self.getProperty("RunNumbers").value) for run_set in self._run_list: self._samWs = self._makeRunName(run_set[0]) self._samMonWs = self._samWs + "_monitors" self._samWsRun = str(run_set[0]) - - self._sumRuns(run_set, self._samWs, self._samMonWs) + + self._sumRuns(run_set, self._samWs, self._samMonWs) # After files are all added, run the reduction - self._calibData(self._samWs, self._samMonWs) - - if self._doNorm: - api.MaskDetectors(Workspace=self._samWs, - MaskedWorkspace='BASIS_NORM_MASK') - api.Divide(LHSWorkspace=self._samWs, RHSWorkspace=self._normWs, - OutputWorkspace=self._samWs) - - api.ConvertUnits(InputWorkspace=self._samWs, - OutputWorkspace=self._samWs, + self._calibData(self._samWs, self._samMonWs) + + if self._doNorm: + api.MaskDetectors(Workspace=self._samWs, + MaskedWorkspace='BASIS_NORM_MASK') + api.Divide(LHSWorkspace=self._samWs, RHSWorkspace=self._normWs, + OutputWorkspace=self._samWs) + + api.ConvertUnits(InputWorkspace=self._samWs, + OutputWorkspace=self._samWs, Target='DeltaE', EMode='Indirect') - api.CorrectKiKf(InputWorkspace=self._samWs, - OutputWorkspace=self._samWs, + api.CorrectKiKf(InputWorkspace=self._samWs, + OutputWorkspace=self._samWs, EMode='Indirect') - - api.Rebin(InputWorkspace=self._samWs, - OutputWorkspace=self._samWs, + + api.Rebin(InputWorkspace=self._samWs, + OutputWorkspace=self._samWs, Params=self._etBins) if self._groupDetOpt != "None": if self._groupDetOpt == "Low-Resolution": @@ -141,29 +141,29 @@ def PyExec(self): if self._overrideMask: config.appendDataSearchDir(DEFAULT_MASK_GROUP_DIR) - api.GroupDetectors(InputWorkspace=self._samWs, + api.GroupDetectors(InputWorkspace=self._samWs, OutputWorkspace=self._samWs, MapFile=grp_file, Behaviour="Sum") - + self._samSqwWs = self._samWs+'_sqw' - api.SofQW3(InputWorkspace=self._samWs, + api.SofQW3(InputWorkspace=self._samWs, OutputWorkspace=self._samSqwWs, - QAxisBinning=self._qBins, EMode='Indirect', + QAxisBinning=self._qBins, EMode='Indirect', EFixed=DEFAULT_ENERGY) - - dave_grp_filename = self._makeRunName(self._samWsRun, + + dave_grp_filename = self._makeRunName(self._samWsRun, False) + ".dat" - api.SaveDaveGrp(Filename=dave_grp_filename, + api.SaveDaveGrp(Filename=dave_grp_filename, InputWorkspace=self._samSqwWs, ToMicroEV=True) - processed_filename = self._makeRunName(self._samWsRun, + processed_filename = self._makeRunName(self._samWsRun, False) + "_sqw.nxs" - api.SaveNexus(Filename=processed_filename, - InputWorkspace=self._samSqwWs) + api.SaveNexus(Filename=processed_filename, + InputWorkspace=self._samSqwWs) def _getRuns(self, rlist): """ - Create sets of run numbers for analysis. A semicolon indicates a + Create sets of run numbers for analysis. A semicolon indicates a separate group of runs to be processed together. """ run_list = [] @@ -172,7 +172,7 @@ def _getRuns(self, rlist): iap = IntArrayProperty("", rlval) if self._doIndiv: run_list.extend([[x] for x in iap.value]) - else: + else: run_list.append(iap.value) return run_list @@ -184,12 +184,12 @@ def _makeRunName(self, run, useShort=True): return self._short_inst + "_" + str(run) else: return self._long_inst + "_" + str(run) - + def _makeRunFile(self, run): """ Make name like BSS24234 """ - return self._short_inst + str(run) + return self._short_inst + str(run) def _sumRuns(self, run_set, sam_ws, mon_ws, extra_ext=None): for run in run_set: @@ -198,57 +198,57 @@ def _sumRuns(self, run_set, sam_ws, mon_ws, extra_ext=None): ws_name += extra_ext mon_ws_name = ws_name + "_monitors" run_file = self._makeRunFile(run) - + api.Load(Filename=run_file, OutputWorkspace=ws_name) - + if not self._noMonNorm: - api.LoadNexusMonitors(Filename=run_file, + api.LoadNexusMonitors(Filename=run_file, OutputWorkspace=mon_ws_name) if sam_ws != ws_name: api.Plus(LHSWorkspace=sam_ws, RHSWorkspace=ws_name, OutputWorkspace=sam_ws) api.DeleteWorkspace(ws_name) if mon_ws != mon_ws_name and not self._noMonNorm: - api.Plus(LHSWorkspace=mon_ws, + api.Plus(LHSWorkspace=mon_ws, RHSWorkspace=mon_ws_name, OutputWorkspace=mon_ws) api.DeleteWorkspace(mon_ws_name) def _calibData(self, sam_ws, mon_ws): - api.LoadInstrument(Workspace=sam_ws, + api.LoadInstrument(Workspace=sam_ws, Filename=os.path.join(DEFAULT_CONFIG_DIR, 'BASIS_Definition_311.xml')) - api.MaskDetectors(Workspace=sam_ws, + api.MaskDetectors(Workspace=sam_ws, DetectorList=self._dMask) #MaskedWorkspace='BASIS_MASK') - api.ModeratorTzeroLinear(InputWorkspace=sam_ws, + api.ModeratorTzeroLinear(InputWorkspace=sam_ws, OutputWorkspace=sam_ws) - api.LoadParameterFile(Workspace=sam_ws, + api.LoadParameterFile(Workspace=sam_ws, Filename=os.path.join(DEFAULT_CONFIG_DIR, 'BASIS_silicon_311_Parameters.xml')) - api.ConvertUnits(InputWorkspace=sam_ws, + api.ConvertUnits(InputWorkspace=sam_ws, OutputWorkspace=sam_ws, Target='Wavelength', EMode='Indirect') - + if not self._noMonNorm: - api.ModeratorTzeroLinear(InputWorkspace=mon_ws, + api.ModeratorTzeroLinear(InputWorkspace=mon_ws, OutputWorkspace=mon_ws) - api.Rebin(InputWorkspace=mon_ws, + api.Rebin(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Params='10') - api.ConvertUnits(InputWorkspace=mon_ws, - OutputWorkspace=mon_ws, + api.ConvertUnits(InputWorkspace=mon_ws, + OutputWorkspace=mon_ws, Target='Wavelength') api.OneMinusExponentialCor(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, - C='0.20749999999999999', + C='0.20749999999999999', C1='0.001276') - api.Scale(InputWorkspace=mon_ws, + api.Scale(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Factor='9.9999999999999995e-07') - api.RebinToWorkspace(WorkspaceToRebin=sam_ws, + api.RebinToWorkspace(WorkspaceToRebin=sam_ws, WorkspaceToMatch=mon_ws, OutputWorkspace=sam_ws) - api.Divide(LHSWorkspace=sam_ws, - RHSWorkspace=mon_ws, + api.Divide(LHSWorkspace=sam_ws, + RHSWorkspace=mon_ws, OutputWorkspace=sam_ws) - + # Register algorithm with Mantid. AlgorithmFactory.subscribe(BASISReduction311) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py index 0a9f068f51a9..d6aa0ea4000f 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py @@ -25,10 +25,10 @@ def PyInit(self): instruments = [] for instr in sns.instruments(): - for tech in instr.techniques(): - if "Neutron Diffraction" == str(tech): - instruments.append(instr.shortName()) - break + for tech in instr.techniques(): + if "Neutron Diffraction" == str(tech): + instruments.append(instr.shortName()) + break self.declareProperty("Instrument", "PG3", StringListValidator(instruments)) validator = IntArrayBoundedValidator() @@ -67,7 +67,7 @@ def PyInit(self): self.declareProperty(ITableWorkspaceProperty("FitwindowTableWorkspace", "", Direction.Input, PropertyMode.Optional), "Name of input table workspace containing the fit window information for each spectrum. ") self.declareProperty("MinimumPeakHeight", 2., "Minimum value allowed for peak height") - self.declareProperty("MinimumPeakHeightObs", 0., + self.declareProperty("MinimumPeakHeightObs", 0., "Minimum value of a peak's maximum observed Y value for this peak to be used to calculate offset.") self.declareProperty(MatrixWorkspaceProperty("DetectorResolutionWorkspace", "", Direction.Input, PropertyMode.Optional), @@ -232,8 +232,8 @@ def _cccalibrate(self, wksp, calib): y_s = wksp.readY(s) midBin = wksp.blocksize()/2 if y_s[midBin] > ymax: - refpixel = s - ymax = y_s[midBin] + refpixel = s + ymax = y_s[midBin] self.log().information("Reference spectra=%s" % refpixel) # Remove old calibration files cmd = "rm "+calib @@ -253,7 +253,7 @@ def _cccalibrate(self, wksp, calib): XMin=-self._ccnumber, XMax=self._ccnumber, MaxOffset=self._maxoffset, MaskWorkspace=str(wksp)+"mask") if AnalysisDataService.doesExist(str(wksp)+"cc"): - AnalysisDataService.remove(str(wksp)+"cc") + AnalysisDataService.remove(str(wksp)+"cc") if self._peakpos2 > 0.0: wksp = Rebin(InputWorkspace=wksp, OutputWorkspace=wksp.name(), Params=str(self._peakmin2)+","+str(abs(self._binning[1]))+","+str(self._peakmax2)) @@ -263,8 +263,8 @@ def _cccalibrate(self, wksp, calib): y_s = wksp.readY(s) midBin = wksp.blocksize()/2 if y_s[midBin] > ymax: - refpixel = s - ymax = y_s[midBin] + refpixel = s + ymax = y_s[midBin] msg = "Reference spectra = %s, lastpixel_3 = %s" % (refpixel, self._lastpixel3) self.log().information(msg) self._lastpixel2 = wksp.getNumberHistograms()*self._lastpixel2/self._lastpixel3-1 @@ -294,8 +294,8 @@ def _cccalibrate(self, wksp, calib): y_s = wksp.readY(s) midBin = wksp.blocksize()/2 if y_s[midBin] > ymax: - refpixel = s - ymax = y_s[midBin] + refpixel = s + ymax = y_s[midBin] self.log().information("Reference spectra=%s" % refpixel) CrossCorrelate(InputWorkspace=wksp, OutputWorkspace=str(wksp)+"cc3", ReferenceSpectra=refpixel, diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py index ff4ff2a92155..bda7c2b9952c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py @@ -1,7 +1,6 @@ from mantid.api import PythonAlgorithm, AlgorithmFactory, WorkspaceProperty import mantid.simpleapi from mantid.kernel import Direction, logger -from string import * class CheckForSampleLogs(PythonAlgorithm): """ Check if certain sample logs exists on a workspace @@ -38,7 +37,7 @@ def PyExec(self): for value in logNames.split(','): value=value.strip() if len(value)>0: - if not w.run().hasProperty(value): + if not w.run().hasProperty(value): resultString+='Property '+value+' not found\n' #return the result diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py index e7720a121e5a..9b1e79a6ea00 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py @@ -6,108 +6,108 @@ class DSFinterp(PythonAlgorithm): - def category(self): - return "Transforms\\Smoothing;Utility;PythonAlgorithms" + def category(self): + return "Transforms\\Smoothing;Utility;PythonAlgorithms" - def name(self): - return 'DSFinterp' + def name(self): + return 'DSFinterp' - def summary(self): - return 'Given a set of parameter values {Ti} and corresponding structure factors S(Q,E,Ti), this algorithm interpolates S(Q,E,T) for any value of parameter T within the range spanned by the {Ti} set.' + def summary(self): + return 'Given a set of parameter values {Ti} and corresponding structure factors S(Q,E,Ti), this algorithm interpolates S(Q,E,T) for any value of parameter T within the range spanned by the {Ti} set.' - def PyInit(self): - arrvalidator = StringArrayMandatoryValidator() - lrg='Input' - self.declareProperty(StringArrayProperty('Workspaces', values=[], validator=arrvalidator, direction=Direction.Input), doc='list of input workspaces') - self.declareProperty('LoadErrors', True, direction=Direction.Input, doc='Do we load error data contained in the workspaces?') - self.declareProperty(FloatArrayProperty('ParameterValues', values=[], validator=FloatArrayMandatoryValidator(),direction=Direction.Input), doc='list of input parameter values') - self.setPropertyGroup('Workspaces', lrg) - self.setPropertyGroup('LoadErrors', lrg) - self.setPropertyGroup('ParameterValues', lrg) + def PyInit(self): + arrvalidator = StringArrayMandatoryValidator() + lrg='Input' + self.declareProperty(StringArrayProperty('Workspaces', values=[], validator=arrvalidator, direction=Direction.Input), doc='list of input workspaces') + self.declareProperty('LoadErrors', True, direction=Direction.Input, doc='Do we load error data contained in the workspaces?') + self.declareProperty(FloatArrayProperty('ParameterValues', values=[], validator=FloatArrayMandatoryValidator(),direction=Direction.Input), doc='list of input parameter values') + self.setPropertyGroup('Workspaces', lrg) + self.setPropertyGroup('LoadErrors', lrg) + self.setPropertyGroup('ParameterValues', lrg) - self.declareProperty('LocalRegression', True, direction=Direction.Input, doc='Perform running local-regression?') - condition = EnabledWhenProperty("LocalRegression", PropertyCriterion.IsDefault) - self.declareProperty('RegressionWindow', 6, direction=Direction.Input, doc='window size for the running local-regression') - self.setPropertySettings("RegressionWindow", condition) - regtypes = [ 'linear', 'quadratic'] - self.declareProperty('RegressionType', 'quadratic', StringListValidator(regtypes), direction=Direction.Input, doc='type of local-regression; linear and quadratic are available') - self.setPropertySettings("RegressionType", condition) - lrg = 'Running Local Regression Options' - self.setPropertyGroup('LocalRegression', lrg) - self.setPropertyGroup('RegressionWindow', lrg) - self.setPropertyGroup('RegressionType', lrg) + self.declareProperty('LocalRegression', True, direction=Direction.Input, doc='Perform running local-regression?') + condition = EnabledWhenProperty("LocalRegression", PropertyCriterion.IsDefault) + self.declareProperty('RegressionWindow', 6, direction=Direction.Input, doc='window size for the running local-regression') + self.setPropertySettings("RegressionWindow", condition) + regtypes = [ 'linear', 'quadratic'] + self.declareProperty('RegressionType', 'quadratic', StringListValidator(regtypes), direction=Direction.Input, doc='type of local-regression; linear and quadratic are available') + self.setPropertySettings("RegressionType", condition) + lrg = 'Running Local Regression Options' + self.setPropertyGroup('LocalRegression', lrg) + self.setPropertyGroup('RegressionWindow', lrg) + self.setPropertyGroup('RegressionType', lrg) - lrg='Output' - self.declareProperty(FloatArrayProperty('TargetParameters', values=[], ), doc="Parameters to interpolate the structure factor") - self.declareProperty(StringArrayProperty('OutputWorkspaces', values=[], validator=arrvalidator), doc='list of output workspaces to save the interpolated structure factors') - self.setPropertyGroup('TargetParameters', lrg) - self.setPropertyGroup('OutputWorkspaces', lrg) - self.channelgroup = None + lrg='Output' + self.declareProperty(FloatArrayProperty('TargetParameters', values=[], ), doc="Parameters to interpolate the structure factor") + self.declareProperty(StringArrayProperty('OutputWorkspaces', values=[], validator=arrvalidator), doc='list of output workspaces to save the interpolated structure factors') + self.setPropertyGroup('TargetParameters', lrg) + self.setPropertyGroup('OutputWorkspaces', lrg) + self.channelgroup = None - def areWorkspacesCompatible(self, a, b): - sizeA = a.blocksize() * a.getNumberHistograms() - sizeB = b.blocksize() * b.getNumberHistograms() - return sizeA == sizeB + def areWorkspacesCompatible(self, a, b): + sizeA = a.blocksize() * a.getNumberHistograms() + sizeB = b.blocksize() * b.getNumberHistograms() + return sizeA == sizeB - def PyExec(self): + def PyExec(self): # Check congruence of workspaces - workspaces = self.getProperty('Workspaces').value - fvalues = self.getProperty('ParameterValues').value - if len(workspaces) != len(fvalues): - mesg = 'Number of Workspaces and ParameterValues should be the same' + workspaces = self.getProperty('Workspaces').value + fvalues = self.getProperty('ParameterValues').value + if len(workspaces) != len(fvalues): + mesg = 'Number of Workspaces and ParameterValues should be the same' #logger.error(mesg) - raise IndexError(mesg) - for workspace in workspaces[1:]: - if not self.areWorkspacesCompatible(mtd[workspaces[0]],mtd[workspace]): - mesg = 'Workspace {0} incompatible with {1}'.format(workspace, workspaces[0]) - logger.error(mesg) - raise ValueError(mesg) + raise IndexError(mesg) + for workspace in workspaces[1:]: + if not self.areWorkspacesCompatible(mtd[workspaces[0]],mtd[workspace]): + mesg = 'Workspace {0} incompatible with {1}'.format(workspace, workspaces[0]) + logger.error(mesg) + raise ValueError(mesg) # Load the workspaces into a group of dynamic structure factors - from dsfinterp.dsf import Dsf - from dsfinterp.dsfgroup import DsfGroup - from dsfinterp.channelgroup import ChannelGroup - dsfgroup = DsfGroup() - for idsf in range(len(workspaces)): - dsf = Dsf() - dsf.Load( mtd[workspaces[idsf]] ) - if not self.getProperty('LoadErrors').value: - dsf.errors = None # do not incorporate error data - dsf.SetFvalue( fvalues[idsf] ) - dsfgroup.InsertDsf(dsf) + from dsfinterp.dsf import Dsf + from dsfinterp.dsfgroup import DsfGroup + from dsfinterp.channelgroup import ChannelGroup + dsfgroup = DsfGroup() + for idsf in range(len(workspaces)): + dsf = Dsf() + dsf.Load( mtd[workspaces[idsf]] ) + if not self.getProperty('LoadErrors').value: + dsf.errors = None # do not incorporate error data + dsf.SetFvalue( fvalues[idsf] ) + dsfgroup.InsertDsf(dsf) # Create the intepolator if not instantiated before - if not self.channelgroup: - self.channelgroup = ChannelGroup() - self.channelgroup.InitFromDsfGroup(dsfgroup) - localregression = self.getProperty('LocalRegression').value - if localregression: - regressiontype = self.getProperty('RegressionType').value - windowlength = self.getProperty('RegressionWindow').value - self.channelgroup.InitializeInterpolator(running_regr_type=regressiontype, windowlength=windowlength) - else: - self.channelgroup.InitializeInterpolator(windowlength=0) + if not self.channelgroup: + self.channelgroup = ChannelGroup() + self.channelgroup.InitFromDsfGroup(dsfgroup) + localregression = self.getProperty('LocalRegression').value + if localregression: + regressiontype = self.getProperty('RegressionType').value + windowlength = self.getProperty('RegressionWindow').value + self.channelgroup.InitializeInterpolator(running_regr_type=regressiontype, windowlength=windowlength) + else: + self.channelgroup.InitializeInterpolator(windowlength=0) # Invoke the interpolator and generate the output workspaces - targetfvalues = self.getProperty('TargetParameters').value - for targetfvalue in targetfvalues: - if targetfvalue < min(fvalues) or targetfvalue > max(fvalues): - mesg = 'Target parameters should lie in [{0}, {1}]'.format(min(fvalues),max(fvalues)) - logger.error(mesg) - raise ValueError(mesg) - outworkspaces = self.getProperty('OutputWorkspaces').value - if len(targetfvalues) != len(outworkspaces): - mesg = 'Number of OutputWorkspaces and TargetParameters should be the same' - logger.error(mesg) - raise IndexError(mesg) - for i in range(len(targetfvalues)): - outworkspace = outworkspaces[i] - dsf = self.channelgroup( targetfvalues[i] ) - outws = CloneWorkspace( mtd[workspaces[0]], OutputWorkspace=outworkspaces[i]) - dsf.Save(outws) # overwrite dataY and dataE + targetfvalues = self.getProperty('TargetParameters').value + for targetfvalue in targetfvalues: + if targetfvalue < min(fvalues) or targetfvalue > max(fvalues): + mesg = 'Target parameters should lie in [{0}, {1}]'.format(min(fvalues),max(fvalues)) + logger.error(mesg) + raise ValueError(mesg) + outworkspaces = self.getProperty('OutputWorkspaces').value + if len(targetfvalues) != len(outworkspaces): + mesg = 'Number of OutputWorkspaces and TargetParameters should be the same' + logger.error(mesg) + raise IndexError(mesg) + for i in range(len(targetfvalues)): + outworkspace = outworkspaces[i] + dsf = self.channelgroup( targetfvalues[i] ) + outws = CloneWorkspace( mtd[workspaces[0]], OutputWorkspace=outworkspaces[i]) + dsf.Save(outws) # overwrite dataY and dataE ############################################################################################# try: - import dsfinterp - AlgorithmFactory.subscribe(DSFinterp) + import dsfinterp + AlgorithmFactory.subscribe(DSFinterp) except: - logger.debug('Failed to subscribe algorithm DSFinterp; Python package dsfinterp may be missing (https://pypi.python.org/pypi/dsfinterp)') - pass + logger.debug('Failed to subscribe algorithm DSFinterp; Python package dsfinterp may be missing (https://pypi.python.org/pypi/dsfinterp)') + pass diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py index 7a671ccb7066..1bebb1496bd8 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py @@ -1,9 +1,8 @@ from mantid.api import PythonAlgorithm, AlgorithmFactory,MatrixWorkspaceProperty,PropertyMode from mantid.kernel import Direction,IntBoundedValidator,FloatBoundedValidator -import mantid.simpleapi +import mantid.simpleapi import mantid import numpy -from string import * class DakotaChiSquared(PythonAlgorithm): """ Get chi squared by comparing two mantid nexus files @@ -12,7 +11,7 @@ def category(self): """ Return category """ return "PythonAlgorithms;Utility\\Workspaces" - + def name(self): """ Return name """ @@ -24,67 +23,66 @@ def summmary(self): def PyInit(self): """ Declare properties """ - f1=mantid.api.FileProperty("DataFile","",mantid.api.FileAction.Load,".nxs") - self.declareProperty(f1,"Input Nexus file containing data.") - f2=mantid.api.FileProperty("CalculatedFile","",mantid.api.FileAction.Load,".nxs") + f1=mantid.api.FileProperty("DataFile","",mantid.api.FileAction.Load,".nxs") + self.declareProperty(f1,"Input Nexus file containing data.") + f2=mantid.api.FileProperty("CalculatedFile","",mantid.api.FileAction.Load,".nxs") self.declareProperty(f2,"Input Nexus file containing calculated data.") - fout=mantid.api.FileProperty("OutputFile","",mantid.api.FileAction.Save,".xml") + fout=mantid.api.FileProperty("OutputFile","",mantid.api.FileAction.Save,".xml") self.declareProperty(fout,"Output filename containing chi^2.") - self.declareProperty("ChiSquared",0.0,Direction.Output) - self.declareProperty(MatrixWorkspaceProperty("ResidualsWorkspace", "",Direction.Output,PropertyMode.Optional), "The name of the workspace that will contain residuals.") - + self.declareProperty("ChiSquared",0.0,Direction.Output) + self.declareProperty(MatrixWorkspaceProperty("ResidualsWorkspace", "",Direction.Output,PropertyMode.Optional), "The name of the workspace that will contain residuals.") return - + def PyExec(self): """ Main execution body """ - #get parameters - f1 = self.getProperty("DataFile").value - f2 = self.getProperty("CalculatedFile").value - fout = self.getProperty("OutputFile").value - - #load files + #get parameters + f1 = self.getProperty("DataFile").value + f2 = self.getProperty("CalculatedFile").value + fout = self.getProperty("OutputFile").value + + #load files __w1=mantid.simpleapi.Load(f1) - __w2=mantid.simpleapi.Load(f2) + __w2=mantid.simpleapi.Load(f2) + + #validate inputs + if (type(__w1)!= mantid.api._api.MatrixWorkspace): + mantid.kernel.logger.error('Wrong workspace type for data file') + raise ValueError( 'Wrong workspace type for data file') + if (type(__w2)!= mantid.api._api.MatrixWorkspace): + mantid.kernel.logger.error('Wrong workspace type for calculated file') + raise ValueError( 'Wrong workspace type for calculated file') + if((__w1.blocksize()!=__w2.blocksize()) or (__w1.getNumberHistograms()!=__w2.getNumberHistograms())): + mantid.kernel.logger.error('The file sizes are different') + raise ValueError( 'The file sizes are different') - #validate inputs - if (type(__w1)!= mantid.api._api.MatrixWorkspace): - mantid.kernel.logger.error('Wrong workspace type for data file') - raise ValueError( 'Wrong workspace type for data file') - if (type(__w2)!= mantid.api._api.MatrixWorkspace): - mantid.kernel.logger.error('Wrong workspace type for calculated file') - raise ValueError( 'Wrong workspace type for calculated file') - if((__w1.blocksize()!=__w2.blocksize()) or (__w1.getNumberHistograms()!=__w2.getNumberHistograms())): - mantid.kernel.logger.error('The file sizes are different') - raise ValueError( 'The file sizes are different') - - #calculate chi^2 - soeName = self.getPropertyValue("ResidualsWorkspace") - if (len(soeName)>0): - mantid.simpleapi.SignalOverError(__w1-__w2,OutputWorkspace=soeName) - self.setProperty("ResidualsWorkspace",soeName) - __soe=mantid.mtd[soeName] - else: - __soe=mantid.simpleapi.SignalOverError(__w1-__w2) - __soe2=__soe*__soe - __soe2=mantid.simpleapi.ReplaceSpecialValues(__soe2,0,0,0,0) - - data=__soe2.extractY() - chisquared=numpy.sum(data) + #calculate chi^2 + soeName = self.getPropertyValue("ResidualsWorkspace") + if (len(soeName)>0): + mantid.simpleapi.SignalOverError(__w1-__w2,OutputWorkspace=soeName) + self.setProperty("ResidualsWorkspace",soeName) + __soe=mantid.mtd[soeName] + else: + __soe=mantid.simpleapi.SignalOverError(__w1-__w2) + __soe2=__soe*__soe + __soe2=mantid.simpleapi.ReplaceSpecialValues(__soe2,0,0,0,0) - #write out the Dakota chi squared file - f = open(fout,'w') - f.write(str(chisquared)+' obj_fn\n') - f.close() + data=__soe2.extractY() + chisquared=numpy.sum(data) + + #write out the Dakota chi squared file + f = open(fout,'w') + f.write(str(chisquared)+' obj_fn\n') + f.close() self.setProperty("ChiSquared",chisquared) - - #cleanup - mantid.simpleapi.DeleteWorkspace(__w1.getName()) - mantid.simpleapi.DeleteWorkspace(__w2.getName()) - mantid.simpleapi.DeleteWorkspace(__soe2.getName()) - if (len(soeName)==0): - mantid.simpleapi.DeleteWorkspace(__soe.getName()) - + + #cleanup + mantid.simpleapi.DeleteWorkspace(__w1.getName()) + mantid.simpleapi.DeleteWorkspace(__w2.getName()) + mantid.simpleapi.DeleteWorkspace(__soe2.getName()) + if (len(soeName)==0): + mantid.simpleapi.DeleteWorkspace(__soe.getName()) + AlgorithmFactory.subscribe(DakotaChiSquared) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py index b7dcc6e08a22..4988e37de329 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py @@ -7,57 +7,57 @@ class EnginXCalibrate(PythonAlgorithm): def category(self): - return "Diffraction\Engineering;PythonAlgorithms" + return "Diffraction\Engineering;PythonAlgorithms" def name(self): - return "EnginXCalibrate" + return "EnginXCalibrate" def summary(self): - return "Calibrates a detector bank by performing a single peak fitting." + return "Calibrates a detector bank by performing a single peak fitting." def PyInit(self): - self.declareProperty(FileProperty("Filename", "", FileAction.Load), + self.declareProperty(FileProperty("Filename", "", FileAction.Load), "Calibration run to use") - self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""), + self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""), "A list of dSpacing values where peaks are expected.") - self.declareProperty("Bank", 1, "Which bank to calibrate") + self.declareProperty("Bank", 1, "Which bank to calibrate") - self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional), "Calibrated detector positions. If not specified, default ones are used.") - self.declareProperty("Difc", 0.0, direction = Direction.Output, + self.declareProperty("Difc", 0.0, direction = Direction.Output, doc = "Calibrated Difc value for the bank") - self.declareProperty("Zero", 0.0, direction = Direction.Output, + self.declareProperty("Zero", 0.0, direction = Direction.Output, doc = "Calibrated Zero value for the bank") def PyExec(self): - ws = self._focusRun() + ws = self._focusRun() - fitPeaksAlg = self.createChildAlgorithm('EnginXFitPeaks') - fitPeaksAlg.setProperty('InputWorkspace', ws) - fitPeaksAlg.setProperty('WorkspaceIndex', 0) # There should be only one index anyway - fitPeaksAlg.setProperty('ExpectedPeaks', self.getProperty('ExpectedPeaks').value) - fitPeaksAlg.execute() + fitPeaksAlg = self.createChildAlgorithm('EnginXFitPeaks') + fitPeaksAlg.setProperty('InputWorkspace', ws) + fitPeaksAlg.setProperty('WorkspaceIndex', 0) # There should be only one index anyway + fitPeaksAlg.setProperty('ExpectedPeaks', self.getProperty('ExpectedPeaks').value) + fitPeaksAlg.execute() - self.setProperty('Difc', fitPeaksAlg.getProperty('Difc').value) - self.setProperty('Zero', fitPeaksAlg.getProperty('Zero').value) + self.setProperty('Difc', fitPeaksAlg.getProperty('Difc').value) + self.setProperty('Zero', fitPeaksAlg.getProperty('Zero').value) def _focusRun(self): - alg = self.createChildAlgorithm('EnginXFocus') - alg.setProperty('Filename', self.getProperty('Filename').value) - alg.setProperty('Bank', self.getProperty('Bank').value) + alg = self.createChildAlgorithm('EnginXFocus') + alg.setProperty('Filename', self.getProperty('Filename').value) + alg.setProperty('Bank', self.getProperty('Bank').value) - detPos = self.getProperty('DetectorPositions').value - if detPos: - alg.setProperty('DetectorPositions', detPos) + detPos = self.getProperty('DetectorPositions').value + if detPos: + alg.setProperty('DetectorPositions', detPos) - alg.execute() + alg.execute() - return alg.getProperty('OutputWorkspace').value + return alg.getProperty('OutputWorkspace').value -AlgorithmFactory.subscribe(EnginXCalibrate) \ No newline at end of file +AlgorithmFactory.subscribe(EnginXCalibrate) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py index 9d586a12440d..458b633ea3c7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py @@ -4,130 +4,130 @@ class EnginXCalibrateFull(PythonAlgorithm): def category(self): - return "Diffraction\Engineering;PythonAlgorithms" + return "Diffraction\Engineering;PythonAlgorithms" def name(self): - return "EnginXCalibrateFull" + return "EnginXCalibrateFull" def summary(self): - return "Calibrates every pixel position by performing single peak fitting." + return "Calibrates every pixel position by performing single peak fitting." def PyInit(self): - self.declareProperty(FileProperty("Filename", "", FileAction.Load), + self.declareProperty(FileProperty("Filename", "", FileAction.Load), "Calibration run to use") - self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Output), "A table with the detector IDs and calibrated detector positions in V3P format.") - self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""), + self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""), "A list of dSpacing values where peaks are expected.") - self.declareProperty("Bank", 1, "Which bank to calibrate") + self.declareProperty("Bank", 1, "Which bank to calibrate") def PyExec(self): - import EnginXUtils + import EnginXUtils - ws = self._loadCalibrationRun() + ws = self._loadCalibrationRun() - ws = self._prepareWsForFitting(ws) + ws = self._prepareWsForFitting(ws) - positionTable = self._createPositionsTable() + positionTable = self._createPositionsTable() - indices = EnginXUtils.getWsIndicesForBank(self.getProperty('Bank').value, ws) + indices = EnginXUtils.getWsIndicesForBank(self.getProperty('Bank').value, ws) - prog = Progress(self, 0, 1, len(indices)) + prog = Progress(self, 0, 1, len(indices)) - for i in indices: + for i in indices: - _, difc = self._fitPeaks(ws, i) + _, difc = self._fitPeaks(ws, i) - det = ws.getDetector(i) + det = ws.getDetector(i) - newPos = self._getCalibratedDetPos(difc, det, ws) + newPos = self._getCalibratedDetPos(difc, det, ws) - positionTable.addRow([det.getID(), newPos]) + positionTable.addRow([det.getID(), newPos]) - prog.report() + prog.report() - self.setProperty("DetectorPositions", positionTable) + self.setProperty("DetectorPositions", positionTable) def _loadCalibrationRun(self): - """ Loads specified calibration run + """ Loads specified calibration run """ - alg = self.createChildAlgorithm('Load') - alg.setProperty('Filename', self.getProperty('Filename').value) - alg.execute() - return alg.getProperty('OutputWorkspace').value + alg = self.createChildAlgorithm('Load') + alg.setProperty('Filename', self.getProperty('Filename').value) + alg.execute() + return alg.getProperty('OutputWorkspace').value def _prepareWsForFitting(self, ws): - """ Rebins the workspace and converts it to distribution + """ Rebins the workspace and converts it to distribution """ - rebinAlg = self.createChildAlgorithm('Rebin') - rebinAlg.setProperty('InputWorkspace', ws) - rebinAlg.setProperty('Params', '-0.0005') # The value is borrowed from OG routines - rebinAlg.execute() - result = rebinAlg.getProperty('OutputWorkspace').value + rebinAlg = self.createChildAlgorithm('Rebin') + rebinAlg.setProperty('InputWorkspace', ws) + rebinAlg.setProperty('Params', '-0.0005') # The value is borrowed from OG routines + rebinAlg.execute() + result = rebinAlg.getProperty('OutputWorkspace').value if result.isDistribution()==False: - convertAlg = self.createChildAlgorithm('ConvertToDistribution') - convertAlg.setProperty('Workspace', result) - convertAlg.execute() + convertAlg = self.createChildAlgorithm('ConvertToDistribution') + convertAlg.setProperty('Workspace', result) + convertAlg.execute() - return result + return result def _createPositionsTable(self): - """ Creates an empty table for storing detector positions + """ Creates an empty table for storing detector positions """ - alg = self.createChildAlgorithm('CreateEmptyTableWorkspace') - alg.execute() - table = alg.getProperty('OutputWorkspace').value + alg = self.createChildAlgorithm('CreateEmptyTableWorkspace') + alg.execute() + table = alg.getProperty('OutputWorkspace').value - table.addColumn('int', 'Detector ID') - table.addColumn('V3D', 'Detector Position') + table.addColumn('int', 'Detector ID') + table.addColumn('V3D', 'Detector Position') - return table + return table def _fitPeaks(self, ws, wsIndex): - """ Fits expected peaks to the spectrum, and returns calibrated zero and difc values. + """ Fits expected peaks to the spectrum, and returns calibrated zero and difc values. """ - alg = self.createChildAlgorithm('EnginXFitPeaks') - alg.setProperty('InputWorkspace', ws) - alg.setProperty('WorkspaceIndex', wsIndex) # There should be only one index anyway - alg.setProperty('ExpectedPeaks', self.getProperty('ExpectedPeaks').value) - alg.execute() + alg = self.createChildAlgorithm('EnginXFitPeaks') + alg.setProperty('InputWorkspace', ws) + alg.setProperty('WorkspaceIndex', wsIndex) # There should be only one index anyway + alg.setProperty('ExpectedPeaks', self.getProperty('ExpectedPeaks').value) + alg.execute() - difc = alg.getProperty('Difc').value - zero = alg.getProperty('Zero').value + difc = alg.getProperty('Difc').value + zero = alg.getProperty('Zero').value - return (zero, difc) + return (zero, difc) def _getCalibratedDetPos(self, newDifc, det, ws): - """ Returns a detector position which corresponds to the newDifc value. + """ Returns a detector position which corresponds to the newDifc value. The two_theta and phi of the detector are preserved, L2 is changed. """ - detL2 = det.getDistance(ws.getInstrument().getSample()) - detTwoTheta = ws.detectorTwoTheta(det) - detPhi = det.getPhi() + detL2 = det.getDistance(ws.getInstrument().getSample()) + detTwoTheta = ws.detectorTwoTheta(det) + detPhi = det.getPhi() - newL2 = (newDifc / (252.816 * 2 * math.sin(detTwoTheta / 2.0))) - 50 + newL2 = (newDifc / (252.816 * 2 * math.sin(detTwoTheta / 2.0))) - 50 - newPos = self._V3DFromSpherical(newL2, detTwoTheta, detPhi) + newPos = self._V3DFromSpherical(newL2, detTwoTheta, detPhi) - return newPos + return newPos def _V3DFromSpherical(self, R, polar, azimuth): - """ Returns a cartesian 3D vector for the given spherical coordinates. + """ Returns a cartesian 3D vector for the given spherical coordinates. Borrowed from V3D::spherical (C++). """ - z = R*math.cos(polar) - ct=R*math.sin(polar) - x=ct*math.cos(azimuth) - y=ct*math.sin(azimuth) + z = R*math.cos(polar) + ct=R*math.sin(polar) + x=ct*math.cos(azimuth) + y=ct*math.sin(azimuth) - return V3D(x,y,z) + return V3D(x,y,z) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py index 5642497df446..f51adff839a0 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py @@ -6,30 +6,30 @@ class EnginXFitPeaks(PythonAlgorithm): def category(self): - return "Diffraction\Engineering;PythonAlgorithms" + return "Diffraction\Engineering;PythonAlgorithms" def name(self): - return "EnginXFitPeaks" + return "EnginXFitPeaks" def summary(self): - return "The algorithm fits an expected diffraction pattern to a workpace spectrum by performing single peak fits." + return "The algorithm fits an expected diffraction pattern to a workpace spectrum by performing single peak fits." def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), "Workspace to fit peaks in. ToF is expected X unit.") - self.declareProperty("WorkspaceIndex", 0, + self.declareProperty("WorkspaceIndex", 0, "Index of the spectra to fit peaks in") - self.declareProperty(FloatArrayProperty("ExpectedPeaks", (self._getDefaultPeaks())), + self.declareProperty(FloatArrayProperty("ExpectedPeaks", (self._getDefaultPeaks())), "A list of dSpacing values to be translated into TOF to find expected peaks.") - - self.declareProperty(FileProperty(name="ExpectedPeaksFromFile",defaultValue="",action=FileAction.OptionalLoad,extensions = [".csv"]),"Load from file a list of dSpacing values to be translated into TOF to find expected peaks.") - self.declareProperty("Difc", 0.0, direction = Direction.Output, + self.declareProperty(FileProperty(name="ExpectedPeaksFromFile",defaultValue="",action=FileAction.OptionalLoad,extensions = [".csv"]),"Load from file a list of dSpacing values to be translated into TOF to find expected peaks.") + + self.declareProperty("Difc", 0.0, direction = Direction.Output, doc = "Fitted Difc value") - self.declareProperty("Zero", 0.0, direction = Direction.Output, + self.declareProperty("Zero", 0.0, direction = Direction.Output, doc = "Fitted Zero value") def PyExec(self): @@ -39,7 +39,7 @@ def PyExec(self): # so we can match them with fitted centres later. expectedPeaksTof = sorted(expectedPeaksTof) expectedPeaksD = self._readInExpectedPeaks() - + # Find approximate peak positions, asumming Gaussian shapes findPeaksAlg = self.createChildAlgorithm('FindPeaks') findPeaksAlg.setProperty('InputWorkspace', self.getProperty("InputWorkspace").value) @@ -118,83 +118,83 @@ def _readInExpectedPeaks(self): if exPeakArray == []: print "File could not be read. Defaults being used." expectedPeaksD = sorted(self.getProperty('ExpectedPeaks').value) - else: + else: print "using file" expectedPeaksD = sorted(exPeakArray) else: expectedPeaksD = sorted(self.getProperty('ExpectedPeaks').value) - return expectedPeaksD + return expectedPeaksD def _getDefaultPeaks(self): """ Gets default peaks for EnginX algorithm. Values from CeO2 """ - defaultPeak = [3.1243, 2.7057, 1.9132, 1.6316, 1.5621, 1.3529, 1.2415, 1.2100, 1.1046, 1.0414, 0.9566, 0.9147, 0.9019, 0.8556, 0.8252, 0.8158, 0.7811] + defaultPeak = [3.1243, 2.7057, 1.9132, 1.6316, 1.5621, 1.3529, 1.2415, 1.2100, 1.1046, 1.0414, 0.9566, 0.9147, 0.9019, 0.8556, 0.8252, 0.8158, 0.7811] return defaultPeak def _fitDSpacingToTOF(self, fittedPeaksTable): - """ Fits a linear background to the dSpacing <-> TOF relationship and returns fitted difc + """ Fits a linear background to the dSpacing <-> TOF relationship and returns fitted difc and zero values. """ - convertTableAlg = self.createChildAlgorithm('ConvertTableToMatrixWorkspace') - convertTableAlg.setProperty('InputWorkspace', fittedPeaksTable) - convertTableAlg.setProperty('ColumnX', 'dSpacing') - convertTableAlg.setProperty('ColumnY', 'X0') - convertTableAlg.execute() - dSpacingVsTof = convertTableAlg.getProperty('OutputWorkspace').value + convertTableAlg = self.createChildAlgorithm('ConvertTableToMatrixWorkspace') + convertTableAlg.setProperty('InputWorkspace', fittedPeaksTable) + convertTableAlg.setProperty('ColumnX', 'dSpacing') + convertTableAlg.setProperty('ColumnY', 'X0') + convertTableAlg.execute() + dSpacingVsTof = convertTableAlg.getProperty('OutputWorkspace').value # Fit the curve to get linear coefficients of TOF <-> dSpacing relationship for the detector - fitAlg = self.createChildAlgorithm('Fit') - fitAlg.setProperty('Function', 'name=LinearBackground') - fitAlg.setProperty('InputWorkspace', dSpacingVsTof) - fitAlg.setProperty('WorkspaceIndex', 0) - fitAlg.setProperty('CreateOutput', True) - fitAlg.execute() - paramTable = fitAlg.getProperty('OutputParameters').value + fitAlg = self.createChildAlgorithm('Fit') + fitAlg.setProperty('Function', 'name=LinearBackground') + fitAlg.setProperty('InputWorkspace', dSpacingVsTof) + fitAlg.setProperty('WorkspaceIndex', 0) + fitAlg.setProperty('CreateOutput', True) + fitAlg.execute() + paramTable = fitAlg.getProperty('OutputParameters').value - zero = paramTable.cell('Value', 0) # A0 - difc = paramTable.cell('Value', 1) # A1 + zero = paramTable.cell('Value', 0) # A0 + difc = paramTable.cell('Value', 1) # A1 - return (difc, zero) + return (difc, zero) def _expectedPeaksInTOF(self): - """ Converts expected peak dSpacing values to TOF values for the detector + """ Converts expected peak dSpacing values to TOF values for the detector """ - ws = self.getProperty("InputWorkspace").value - wsIndex = self.getProperty("WorkspaceIndex").value + ws = self.getProperty("InputWorkspace").value + wsIndex = self.getProperty("WorkspaceIndex").value # Detector for specified spectrum - det = ws.getDetector(wsIndex) + det = ws.getDetector(wsIndex) # Current detector parameters - detL2 = det.getDistance(ws.getInstrument().getSample()) - detTwoTheta = ws.detectorTwoTheta(det) + detL2 = det.getDistance(ws.getInstrument().getSample()) + detTwoTheta = ws.detectorTwoTheta(det) # Function for converting dSpacing -> TOF for the detector - dSpacingToTof = lambda d: 252.816 * 2 * (50 + detL2) * math.sin(detTwoTheta / 2.0) * d - expectedPeaks = self._readInExpectedPeaks() + dSpacingToTof = lambda d: 252.816 * 2 * (50 + detL2) * math.sin(detTwoTheta / 2.0) * d + expectedPeaks = self._readInExpectedPeaks() # Expected peak positions in TOF for the detector - expectedPeaksTof = map(dSpacingToTof, expectedPeaks) + expectedPeaksTof = map(dSpacingToTof, expectedPeaks) - return expectedPeaksTof + return expectedPeaksTof def _createFittedPeaksTable(self): - """ Creates a table where to put peak fitting results to + """ Creates a table where to put peak fitting results to """ - alg = self.createChildAlgorithm('CreateEmptyTableWorkspace') - alg.execute() - table = alg.getProperty('OutputWorkspace').value + alg = self.createChildAlgorithm('CreateEmptyTableWorkspace') + alg.execute() + table = alg.getProperty('OutputWorkspace').value - table.addColumn('double', 'dSpacing') + table.addColumn('double', 'dSpacing') - for name in ['A0', 'A1', 'X0', 'A', 'B', 'S', 'I']: - table.addColumn('double', name) - table.addColumn('double', name + '_Err') + for name in ['A0', 'A1', 'X0', 'A', 'B', 'S', 'I']: + table.addColumn('double', name) + table.addColumn('double', name + '_Err') - table.addColumn('double', 'Chi') + table.addColumn('double', 'Chi') - return table + return table def _addParametersToMap(self, paramMap, paramTable): """ Reads parameters from the Fit Parameter table, and add their values and errors to the map @@ -209,4 +209,4 @@ def _addParametersToMap(self, paramMap, paramTable): paramMap[name + '_Err'] = row['Error'] -AlgorithmFactory.subscribe(EnginXFitPeaks) \ No newline at end of file +AlgorithmFactory.subscribe(EnginXFitPeaks) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py index 7086f19c4b11..6ee09d8b6e38 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py @@ -3,123 +3,123 @@ class EnginXFocus(PythonAlgorithm): def category(self): - return "Diffraction\Engineering;PythonAlgorithms" + return "Diffraction\Engineering;PythonAlgorithms" def name(self): - return "EnginXFocus" + return "EnginXFocus" def summary(self): - return "Focuses a run." + return "Focuses a run." def PyInit(self): - self.declareProperty(FileProperty("Filename", "", FileAction.Load), + self.declareProperty(FileProperty("Filename", "", FileAction.Load), "Run to focus") - self.declareProperty(WorkspaceProperty("OutputWorkspace", "", Direction.Output), + self.declareProperty(WorkspaceProperty("OutputWorkspace", "", Direction.Output), "A workspace with focussed data") - self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional), "Calibrated detector positions. If not specified, default ones are used.") - self.declareProperty("Bank", 1, "Which bank to focus") + self.declareProperty("Bank", 1, "Which bank to focus") def PyExec(self): # Load the run file - ws = self._loadRun() + ws = self._loadRun() # Leave the data for the bank we are interested in only - ws = self._cropData(ws) + ws = self._cropData(ws) # Apply calibration - self._applyCalibration(ws) + self._applyCalibration(ws) # Convert to dSpacing - ws = self._convertToDSpacing(ws) + ws = self._convertToDSpacing(ws) # Sum the values - ws = self._sumSpectra(ws) + ws = self._sumSpectra(ws) # Convert back to time of flight - ws = self._convertToTOF(ws) + ws = self._convertToTOF(ws) # OpenGenie displays distributions instead of pure counts (this is done implicitly when # converting units), so I guess that's what users will expect - self._convertToDistr(ws) + self._convertToDistr(ws) - self.setProperty("OutputWorkspace", ws) + self.setProperty("OutputWorkspace", ws) def _loadRun(self): - """ Loads the specified run + """ Loads the specified run """ - alg = self.createChildAlgorithm('Load') - alg.setProperty('Filename', self.getProperty("Filename").value) - alg.execute() - return alg.getProperty('OutputWorkspace').value + alg = self.createChildAlgorithm('Load') + alg.setProperty('Filename', self.getProperty("Filename").value) + alg.execute() + return alg.getProperty('OutputWorkspace').value def _applyCalibration(self, ws): - """ Refines the detector positions using the result of calibration (if one is specified) + """ Refines the detector positions using the result of calibration (if one is specified) """ - detPos = self.getProperty("DetectorPositions").value + detPos = self.getProperty("DetectorPositions").value - if detPos: - alg = self.createChildAlgorithm('ApplyCalibration') - alg.setProperty('Workspace', ws) - alg.setProperty('PositionTable', detPos) - alg.execute() + if detPos: + alg = self.createChildAlgorithm('ApplyCalibration') + alg.setProperty('Workspace', ws) + alg.setProperty('PositionTable', detPos) + alg.execute() def _convertToDSpacing(self, ws): - """ Converts workspace to dSpacing + """ Converts workspace to dSpacing """ - alg = self.createChildAlgorithm('ConvertUnits') - alg.setProperty('InputWorkspace', ws) - alg.setProperty('Target', 'dSpacing') - alg.setProperty('AlignBins', True) - alg.execute() - return alg.getProperty('OutputWorkspace').value + alg = self.createChildAlgorithm('ConvertUnits') + alg.setProperty('InputWorkspace', ws) + alg.setProperty('Target', 'dSpacing') + alg.setProperty('AlignBins', True) + alg.execute() + return alg.getProperty('OutputWorkspace').value def _convertToTOF(self, ws): - """ Converts workspace to TOF + """ Converts workspace to TOF """ - alg = self.createChildAlgorithm('ConvertUnits') - alg.setProperty('InputWorkspace', ws) - alg.setProperty('Target', 'TOF') - alg.execute() - return alg.getProperty('OutputWorkspace').value + alg = self.createChildAlgorithm('ConvertUnits') + alg.setProperty('InputWorkspace', ws) + alg.setProperty('Target', 'TOF') + alg.execute() + return alg.getProperty('OutputWorkspace').value def _convertToDistr(self, ws): - """ Convert workspace to distribution + """ Convert workspace to distribution """ - alg = self.createChildAlgorithm('ConvertToDistribution') - alg.setProperty('Workspace', ws) - alg.execute() + alg = self.createChildAlgorithm('ConvertToDistribution') + alg.setProperty('Workspace', ws) + alg.execute() def _cropData(self, ws): - """ Crops the workspace so that only data for the specified bank is left. + """ Crops the workspace so that only data for the specified bank is left. NB: This assumes spectra for a bank are consequent. """ - import EnginXUtils + import EnginXUtils - indices = EnginXUtils.getWsIndicesForBank(self.getProperty('Bank').value, ws) + indices = EnginXUtils.getWsIndicesForBank(self.getProperty('Bank').value, ws) # Leave only spectra between min and max - alg = self.createChildAlgorithm('CropWorkspace') - alg.setProperty('InputWorkspace', ws) - alg.setProperty('StartWorkspaceIndex', min(indices)) - alg.setProperty('EndWorkspaceIndex', max(indices)) - alg.execute() + alg = self.createChildAlgorithm('CropWorkspace') + alg.setProperty('InputWorkspace', ws) + alg.setProperty('StartWorkspaceIndex', min(indices)) + alg.setProperty('EndWorkspaceIndex', max(indices)) + alg.execute() - return alg.getProperty('OutputWorkspace').value + return alg.getProperty('OutputWorkspace').value def _sumSpectra(self, ws): - """ Calls the SumSpectra algorithm + """ Calls the SumSpectra algorithm """ - alg = self.createChildAlgorithm('SumSpectra') - alg.setProperty('InputWorkspace', ws) - alg.execute() - return alg.getProperty('OutputWorkspace').value + alg = self.createChildAlgorithm('SumSpectra') + alg.setProperty('InputWorkspace', ws) + alg.execute() + return alg.getProperty('OutputWorkspace').value -AlgorithmFactory.subscribe(EnginXFocus) \ No newline at end of file +AlgorithmFactory.subscribe(EnginXFocus) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py index 774411536175..a4971cb0a1f4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py @@ -142,7 +142,7 @@ def mainExec(self): # Load .irf file and .hkl file optionally if self.loadinfofile is True: - if dir(self).count('latticesize') == 0 or self.latticesize is None: + if dir(self).count('latticesize') == 0 or self.latticesize is None: raise NotImplementedError("Lattice size is not defined. Unable to use option 'LoadInfo'") api.CreateLeBailFitInput( diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py index 4b7d54498f63..d02cbed8a41e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py @@ -42,7 +42,7 @@ def PyInit(self): "With this option, the posfix of the output file is .csv automatically. " self.declareProperty("FileFormat", "tab", mantid.kernel.StringListValidator(fileformates), des) - self.declareProperty("OrderByTitle", "", "Log file will be ordered by the value of this title from low to high.") + self.declareProperty("OrderByTitle", "", "Log file will be ordered by the value of this title from low to high.") self.declareProperty("RemoveDuplicateRecord", False, "Coupled with OrderByTitle, duplicated record will be removed.") overrideprop = StringArrayProperty("OverrideLogValue", values=[], direction=Direction.Input) @@ -160,7 +160,7 @@ def _processInputs(self): self._orderRecord = False self._titleToOrder = None if self._filemode != "new": - ordertitle = self.getProperty("OrderByTitle").value + ordertitle = self.getProperty("OrderByTitle").value if ordertitle in self._headerTitles: self._orderRecord = True self._removeDupRecord = self.getProperty("RemoveDuplicateRecord").value @@ -237,7 +237,7 @@ def _examineLogFile(self): if len(titles) != len(self._headerTitles): if len(self._headerTitles) == 0: self._headerTitles = titles[:] - else: + else: same = False for ititle in xrange(len(titles)): title1 = titles[ititle] @@ -290,10 +290,10 @@ def _appendExpLog(self, logvaluedict): skip = True else: skip = False - + headertitle = None for il in xrange(len(self._sampleLogNames)): - if skip is False: + if skip is False: headertitle = self._headerTitles[il] if headertitle is not None and headertitle in self._ovrdTitleValueDict.keys(): # overriden @@ -321,7 +321,7 @@ def _appendExpLog(self, logvaluedict): return def _orderRecordFile(self): - """ Check and order (if necessary) record file + """ Check and order (if necessary) record file by value of specified log by title """ self.log().debug("Order Record File!") @@ -347,12 +347,12 @@ def _orderRecordFile(self): titlelines.append(line) else: # value line - try: + try: keyvalue = line.split(self._valuesep)[ilog].strip() except IndexError: self.log().error("Order record failed.") return - if linedict.has_key(keyvalue) is False: + if linedict.has_key(keyvalue) is False: linedict[keyvalue] = [] linedict[keyvalue].append(line) totnumlines += 1 @@ -363,7 +363,7 @@ def _orderRecordFile(self): if linedict.keys() != sorted(linedict.keys()): # Re-write file wbuf = "" - + # title line for line in titlelines: wbuf += line @@ -385,8 +385,8 @@ def _orderRecordFile(self): numlines += 1 else: - # Consider all! - for line in linedict[ivalue]: + # Consider all! + for line in linedict[ivalue]: wbuf += line # Add extra \n in case reordered if numlines != totnumlines-1 and wbuf[-1] != '\n': diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py index 1c2aab1eeb97..fbc231e69cea 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py @@ -439,7 +439,7 @@ def getLocalTimeShiftInSecond(utctime, localtimezone, logger = None): if logger: logger.information("Input UTC time = %s" % (str(utctime))) - + # Return early if local time zone is UTC if localtimezone == "UTC": return 0 @@ -452,7 +452,7 @@ def getLocalTimeShiftInSecond(utctime, localtimezone, logger = None): if logger: logger.information("About to convert time string: %s" % t1str) try: - if t1str.count("T") == 1: + if t1str.count("T") == 1: utc = datetime.strptime(t1str, '%Y-%m-%dT%H:%M:%S') else: utc = datetime.strptime(t1str, '%Y-%m-%d %H:%M:%S') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py index 5e61abb53444..d014770dc56f 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py @@ -10,93 +10,93 @@ class FindReflectometryLines(PythonAlgorithm): # Determine if a given signal identifies a peak or not. def __is_peak(self, before, current, after): # A peak is defined to be any signal that is preceeded by a lower signal value and followed by a lower signal value. - if before < current and current > after: - return True - return False + if before < current and current > after: + return True + return False # Find a list of spectra numbers corresponding to peaks in the data. def __find_peak_spectrum_numbers(self, y_data, ws): - peak_index_list = [] - for index, current in enumerate(y_data.flat): - if (index > 0) and (index < (y_data.size - 1)): - before = y_data[index-1] - after = y_data[index+1] - if self.__is_peak(before, current, after): - spec_number = ws.getSpectrum(index).getSpectrumNo() - peak_index_list.append(spec_number) - return peak_index_list + peak_index_list = [] + for index, current in enumerate(y_data.flat): + if (index > 0) and (index < (y_data.size - 1)): + before = y_data[index-1] + after = y_data[index+1] + if self.__is_peak(before, current, after): + spec_number = ws.getSpectrum(index).getSpectrumNo() + peak_index_list.append(spec_number) + return peak_index_list # Zero-out any data considered to be background. def __remove_background(self, y_data): - y_average = np.sum(y_data) / y_data.size - y_max = np.max(y_data) + y_average = np.sum(y_data) / y_data.size + y_max = np.max(y_data) #The thresholding criteria is hard-coded to be above the average as follows. - threshold = (y_max - y_average)/10 + y_average - y_data[y_data < threshold] = 0 - return y_data + threshold = (y_max - y_average)/10 + y_average + y_data[y_data < threshold] = 0 + return y_data def category(self): - return "PythonAlgorithms;Reflectometry" + return "PythonAlgorithms;Reflectometry" def name(self): - return "FindReflectometryLines" + return "FindReflectometryLines" def summary(self): - return "Finds spectrum numbers corresponding to reflected and transmission lines in a line detector Reflectometry dataset." + return "Finds spectrum numbers corresponding to reflected and transmission lines in a line detector Reflectometry dataset." def PyInit(self): - workspace_validator = CompositeValidator() - workspace_validator.add(WorkspaceUnitValidator("Wavelength")) - workspace_validator.add(SpectraAxisValidator()) + workspace_validator = CompositeValidator() + workspace_validator.add(WorkspaceUnitValidator("Wavelength")) + workspace_validator.add(SpectraAxisValidator()) - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, workspace_validator), "Input Reflectometry Workspace") - self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), "Output Spectrum Numbers") - self.declareProperty(name="StartWavelength", defaultValue=0.0, validator=FloatBoundedValidator(lower=0.0), doc="Start wavelength to use for x-axis cropping") - self.declareProperty(name="KeepIntermediateWorkspaces", defaultValue=False, doc="Keeps cropped and integrated workspaces in memory after usage.") + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, workspace_validator), "Input Reflectometry Workspace") + self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), "Output Spectrum Numbers") + self.declareProperty(name="StartWavelength", defaultValue=0.0, validator=FloatBoundedValidator(lower=0.0), doc="Start wavelength to use for x-axis cropping") + self.declareProperty(name="KeepIntermediateWorkspaces", defaultValue=False, doc="Keeps cropped and integrated workspaces in memory after usage.") def PyExec(self): - from mantid.simpleapi import CropWorkspace, Integration, DeleteWorkspace + from mantid.simpleapi import CropWorkspace, Integration, DeleteWorkspace - in_ws = self.getPropertyValue("InputWorkspace") - min_wavelength = self.getPropertyValue("StartWavelength") - keep_workspaces = self.getPropertyValue("KeepIntermediateWorkspaces") + in_ws = self.getPropertyValue("InputWorkspace") + min_wavelength = self.getPropertyValue("StartWavelength") + keep_workspaces = self.getPropertyValue("KeepIntermediateWorkspaces") # Crop off lower wavelengths where the signal is also lower. - cropped_ws = CropWorkspace(InputWorkspace=in_ws,XMin=float(min_wavelength)) + cropped_ws = CropWorkspace(InputWorkspace=in_ws,XMin=float(min_wavelength)) # Integrate over the higher wavelengths after cropping. - summed_ws = Integration(InputWorkspace=cropped_ws) + summed_ws = Integration(InputWorkspace=cropped_ws) # Loop through each histogram, and fetch out each intensity value from the single bin to generate a list of all values. - n_histograms = summed_ws.getNumberHistograms() - y_data = np.empty([n_histograms]) - for i in range(0, n_histograms): - intensity = summed_ws.readY(i)[0] - y_data[i] = intensity + n_histograms = summed_ws.getNumberHistograms() + y_data = np.empty([n_histograms]) + for i in range(0, n_histograms): + intensity = summed_ws.readY(i)[0] + y_data[i] = intensity #Remove the background - y_data = self.__remove_background(y_data) + y_data = self.__remove_background(y_data) #Find the peaks - peak_index_list = self.__find_peak_spectrum_numbers(y_data, summed_ws) + peak_index_list = self.__find_peak_spectrum_numbers(y_data, summed_ws) #Reverse the order so that it goes from high spec number to low spec number - peak_index_list.reverse() - n_peaks_found = len(peak_index_list) - - output_ws = WorkspaceFactory.createTable("TableWorkspace") - output_ws.addColumn("int", "Reflected Spectrum Number") - - if n_peaks_found > 2: - raise PeakFindingException("Found more than two peaks.") - elif n_peaks_found == 0: - raise PeakFindingException("No peaks found") - elif n_peaks_found == 1: - output_ws.addRow(peak_index_list) - elif n_peaks_found == 2: - output_ws.addColumn("int", "Transmission Spectrum Number") - output_ws.addRow(peak_index_list) - - if int(keep_workspaces) == 0: - DeleteWorkspace(Workspace=cropped_ws) - DeleteWorkspace(Workspace=summed_ws) - - self.setProperty("OutputWorkspace", output_ws) + peak_index_list.reverse() + n_peaks_found = len(peak_index_list) + + output_ws = WorkspaceFactory.createTable("TableWorkspace") + output_ws.addColumn("int", "Reflected Spectrum Number") + + if n_peaks_found > 2: + raise PeakFindingException("Found more than two peaks.") + elif n_peaks_found == 0: + raise PeakFindingException("No peaks found") + elif n_peaks_found == 1: + output_ws.addRow(peak_index_list) + elif n_peaks_found == 2: + output_ws.addColumn("int", "Transmission Spectrum Number") + output_ws.addRow(peak_index_list) + + if int(keep_workspaces) == 0: + DeleteWorkspace(Workspace=cropped_ws) + DeleteWorkspace(Workspace=summed_ws) + + self.setProperty("OutputWorkspace", output_ws) AlgorithmFactory.subscribe(FindReflectometryLines()) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py index 333e17ff3cba..9ffb0b45fbb1 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py @@ -25,20 +25,20 @@ def summary(self): def PyInit(self): """ Declare properties - """ + """ self.declareProperty(FileProperty("Filename","", FileAction.Load, ['.hkl', '.prf', '.dat']), "Name of [http://www.ill.eu/sites/fullprof/ Fullprof] .hkl or .prf file.") #self.declareProperty("Bank", 1, "Bank ID for output if there are more than one bank in .irf file.") - self.declareProperty(ITableWorkspaceProperty("PeakParameterWorkspace", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("PeakParameterWorkspace", "", Direction.Output), "Name of table workspace containing peak parameters from .hkl file.") - - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), + + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), "Name of data workspace containing the diffraction pattern in .prf file. ") return - + def PyExec(self): """ Main Execution Body """ @@ -46,12 +46,12 @@ def PyExec(self): fpfilename = self.getPropertyValue("Filename") # 2. Import - if fpfilename.lower().endswith(".hkl") is True: + if fpfilename.lower().endswith(".hkl") is True: # (.hkl) file self._tableWS = self._loadFPHKLFile(fpfilename) self._dataWS = self._makeEmptyDataWorkspace() elif fpfilename.lower().endswith(".prf") is True: - # (.prf) file + # (.prf) file self._tableWS, self._dataWS= self._loadFullprofPrfFile(fpfilename) elif fpfilename.lower().endswith(".dat") is True: # (.dat) file: Fullprof data file @@ -131,13 +131,13 @@ def _importFullprofHKLFile(self, hklfilename): dkey = (h, k, l) if hkldict.has_key(dkey): - if _OUTPUTLEVEL == "INFORMATION": + if _OUTPUTLEVEL == "INFORMATION": self.warning("Warning! Duplicate HKL %d, %d, %d" (h, k, l)) continue if fwhm < 1.0E-5: # Peak width is too small/annihilated peak - if _OUTPUTLEVEL == "INFORMATION": + if _OUTPUTLEVEL == "INFORMATION": self.log.information("Peak (%d, %d, %d) has an unreasonable small FWHM. Peak does not exist. " % (h, k, l)) continue @@ -156,20 +156,20 @@ def _importFullprofHKLFile(self, hklfilename): return hkldict def _createReflectionWorkspace(self, hkldict): - """ Create TableWorkspace containing reflections and etc. + """ Create TableWorkspace containing reflections and etc. """ # 1. Set up columns tablews = WorkspaceFactory.createTable() - - tablews.addColumn("int", "H"); - tablews.addColumn("int", "K"); - tablews.addColumn("int", "L"); - tablews.addColumn("double", "Alpha"); - tablews.addColumn("double", "Beta"); - tablews.addColumn("double", "Sigma2"); - tablews.addColumn("double", "Gamma"); - tablews.addColumn("double", "FWHM"); - tablews.addColumn("double", "PeakHeight"); + + tablews.addColumn("int", "H") + tablews.addColumn("int", "K") + tablews.addColumn("int", "L") + tablews.addColumn("double", "Alpha") + tablews.addColumn("double", "Beta") + tablews.addColumn("double", "Sigma2") + tablews.addColumn("double", "Gamma") + tablews.addColumn("double", "FWHM") + tablews.addColumn("double", "PeakHeight") # 2. Add rows for hkl in sorted(hkldict.keys()): @@ -250,7 +250,7 @@ def _parseFullprofPrfFile(self, filename): # spacegroup = terms[1].strip() # infodict["SpaceGroup"] = spacegroup - # Find data line header + # Find data line header firstline = -1 for i in xrange(1, len(lines)): if lines[i].count("Yobs-Ycal") > 0: @@ -266,14 +266,14 @@ def _parseFullprofPrfFile(self, filename): headerterms = dataheader.split() dataperline = 5 # TOF., ... h k l ... - reflectionperline = len(headerterms)-5+3 + reflectionperline = len(headerterms)-5+3 # Parse data count = 0 - for i in xrange(firstline, len(lines)): - line = lines[i].strip() - if len(line) == 0: # empty line + for i in xrange(firstline, len(lines)): + line = lines[i].strip() + if len(line) == 0: # empty line continue if line.count(")") == 0 and line.count("(") == 0: @@ -312,10 +312,10 @@ def _parseFullprofPrfFile(self, filename): ycal = float(terms[2]) ydif = float(terms[3]) ybak = float(terms[4]) - + dataset.append([x, yobs, ycal, ydif, ybak]) count += 1 - + raise NotImplementedError("Need a sample line of this use case.") hklstr = line.split(")")[1].split(")")[0].strip() infodict[hklstr] = tofh @@ -357,7 +357,7 @@ def _loadFullprofDataFile(self, datafilename): # header title += line + ", " else: - # line information + # line information terms = line.split() if terms[0] != 'BANK': raise NotImplementedError("First word must be 'BANK', but not %s" % (terms[0])) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py index 734f5e6d7489..1e9b7476a306 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py @@ -59,7 +59,7 @@ def PyExec(self): if inst == "POLDI": if ws.getNumberHistograms() == 800: - ws.maskDetectors(SpectraList=range(0,800)[::2]) + ws.maskDetectors(SpectraList=range(0,800)[::2]) config.appendDataSearchDir(config['groupingFiles.directory']) grp_file = "POLDI_Grouping_800to400.xml" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py index 0d23197cc062..500396a95f42 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py @@ -34,7 +34,7 @@ class LoadVesuvio(PythonAlgorithm): def summary(self): - return "Loads raw data produced by the Vesuvio instrument at ISIS." + return "Loads raw data produced by the Vesuvio instrument at ISIS." def PyInit(self): self.declareProperty(RUN_PROP, "", StringMandatoryValidator(), @@ -417,9 +417,9 @@ def _sum_foil_periods(self): foil_out_periods, foil_thin_periods, foil_thick_periods = self._get_foil_periods() if self._nperiods == 6 and self._spectra_type == FORWARD: - mon_out_periods = (5,6) - mon_thin_periods = (3,4) - mon_thick_periods = foil_thick_periods + mon_out_periods = (5,6) + mon_thin_periods = (3,4) + mon_thick_periods = foil_thick_periods else: # None indicates same as standard foil mon_out_periods, mon_thin_periods, mon_thick_periods = (None,None,None) @@ -824,7 +824,7 @@ def get_index(self, spectrum_no, foil_state_no): (spectrum_no >= 167 and spectrum_no <= 174) or \ (spectrum_no >= 183 and spectrum_no <= 190): # foil_in = 1,3,5, foil out = 2,4,6 - foil_periods = self._odd_even + foil_periods = self._odd_even else: # foil_in = 2,4,6 foil out = 1,3,5 foil_periods = self._even_odd diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py index 3e2326027143..5aa82a595b8c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py @@ -176,9 +176,9 @@ def _getEightPackHandle(self,banknum): elif self.instname=="WISH": if (self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]): try: - return self.instrument.getComponentByName("panel"+"%02d" % banknum)[0] + return self.instrument.getComponentByName("panel"+"%02d" % banknum)[0] except: - return None + return None else: raise ValueError("Out of range index for "+str(self.instname)+" instrument bank numbers") else: diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py index 10848174236a..95f9fccfd65c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py @@ -4,80 +4,80 @@ from mantid.simpleapi import * class QueryFlag: - def isMasked(self, detector, yValue): - return detector.isMasked() + def isMasked(self, detector, yValue): + return detector.isMasked() class QueryValue: - def isMasked(self, detector, yValue): - return yValue == 1 + def isMasked(self, detector, yValue): + return yValue == 1 class MaskWorkspaceToCalFile(PythonAlgorithm): def category(self): - return "DataHandling\\Text;Diffraction;PythonAlgorithms" + return "DataHandling\\Text;Diffraction;PythonAlgorithms" def name(self): - return "MaskWorkspaceToCalFile" + return "MaskWorkspaceToCalFile" def summary(self): - return "Saves the masking information in a workspace to a Cal File." + return "Saves the masking information in a workspace to a Cal File." def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), "The workspace containing the Masking to extract.") - self.declareProperty(FileProperty(name="OutputFile",defaultValue="",action=FileAction.Save,extensions=['cal']), "The file for the results.") + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), "The workspace containing the Masking to extract.") + self.declareProperty(FileProperty(name="OutputFile",defaultValue="",action=FileAction.Save,extensions=['cal']), "The file for the results.") - self.declareProperty("Invert", False, "If True, masking is inverted in the input workspace. Default: False") + self.declareProperty("Invert", False, "If True, masking is inverted in the input workspace. Default: False") def PyExec(self): #extract settings - inputWorkspace = mtd[self.getPropertyValue("InputWorkspace")] - outputFileName = self.getProperty("OutputFile").value - invert = self.getProperty("Invert").value - mask_query = QueryFlag() - if inputWorkspace.id() == "MaskWorkspace": - mask_query = QueryValue() + inputWorkspace = mtd[self.getPropertyValue("InputWorkspace")] + outputFileName = self.getProperty("OutputFile").value + invert = self.getProperty("Invert").value + mask_query = QueryFlag() + if inputWorkspace.id() == "MaskWorkspace": + mask_query = QueryValue() #check for consistency - if len(inputWorkspace.readX(0)) < 1: - raise RuntimeError('The input workspace is empty.') + if len(inputWorkspace.readX(0)) < 1: + raise RuntimeError('The input workspace is empty.') #define flags for masking and not-masking - masking_flag = 0 - not_masking_flag = 1 + masking_flag = 0 + not_masking_flag = 1 - if invert: - masking_flag, not_masking_flag = not_masking_flag, masking_flag + if invert: + masking_flag, not_masking_flag = not_masking_flag, masking_flag - calFile = open(outputFileName,"w") + calFile = open(outputFileName,"w") #write a header - instrumentName = inputWorkspace.getInstrument().getName() - calFile.write('# '+instrumentName+' detector file\n') - calFile.write('# Format: number UDET offset select group\n') + instrumentName = inputWorkspace.getInstrument().getName() + calFile.write('# '+instrumentName+' detector file\n') + calFile.write('# Format: number UDET offset select group\n') #save the grouping - for i in range(inputWorkspace.getNumberHistograms()): - try: - det = inputWorkspace.getDetector(i) - y_value = inputWorkspace.readY(i)[0] - if (mask_query.isMasked(det, y_value)): #check if masked - group = masking_flag - else: - group = not_masking_flag - detIDs = [] - try: - detIDs = det.getDetectorIDs() - except: - detIDs = [det.getID()] - for id in detIDs: - calFile.write(self.FormatLine(i,id,0.0,group,group)) - except: + for i in range(inputWorkspace.getNumberHistograms()): + try: + det = inputWorkspace.getDetector(i) + y_value = inputWorkspace.readY(i)[0] + if (mask_query.isMasked(det, y_value)): #check if masked + group = masking_flag + else: + group = not_masking_flag + detIDs = [] + try: + detIDs = det.getDetectorIDs() + except: + detIDs = [det.getID()] + for id in detIDs: + calFile.write(self.FormatLine(i,id,0.0,group,group)) + except: #no detector for this spectra - pass - calFile.close() + pass + calFile.close() def FormatLine(self,number,UDET,offset,select,group): - line = "{0:9d}{1:16d}{2:16.7f}{3:9d}{4:9d}\n".format(number,UDET,offset,select,group) - return line + line = "{0:9d}{1:16d}{2:16.7f}{3:9d}{4:9d}\n".format(number,UDET,offset,select,group) + return line ############################################################################################# diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py index ea164973bf8c..244933f644bc 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py @@ -3,133 +3,133 @@ class MergeCalFiles(PythonAlgorithm): - def category(self): - return "DataHandling\\Text;Diffraction;PythonAlgorithms" + def category(self): + return "DataHandling\\Text;Diffraction;PythonAlgorithms" - def name(self): - return "MergeCalFiles" + def name(self): + return "MergeCalFiles" - def summary(self): - return "Combines the data from two Cal Files." + def summary(self): + return "Combines the data from two Cal Files." - def PyInit(self): - self.declareProperty(FileProperty("UpdateFile","", FileAction.Load, ['cal']), doc="The cal file containing the updates to merge into another file.") - self.declareProperty(FileProperty("MasterFile","", FileAction.Load, ['cal']), doc="The master file to be altered, the file must be sorted by UDET") - self.declareProperty(FileProperty("OutputFile","", FileAction.Save, ['cal']), doc="The file to contain the results") + def PyInit(self): + self.declareProperty(FileProperty("UpdateFile","", FileAction.Load, ['cal']), doc="The cal file containing the updates to merge into another file.") + self.declareProperty(FileProperty("MasterFile","", FileAction.Load, ['cal']), doc="The master file to be altered, the file must be sorted by UDET") + self.declareProperty(FileProperty("OutputFile","", FileAction.Save, ['cal']), doc="The file to contain the results") - self.declareProperty("MergeOffsets", False, doc="If True, the offsets from file1 will be merged to the master file. Default: False") - self.declareProperty("MergeSelections", False, doc="If True, the selections from file1 will be merged to the master file. Default: False") - self.declareProperty("MergeGroups", False, doc="If True, the Groups from file1 will be merged to the master file. Default: False") + self.declareProperty("MergeOffsets", False, doc="If True, the offsets from file1 will be merged to the master file. Default: False") + self.declareProperty("MergeSelections", False, doc="If True, the selections from file1 will be merged to the master file. Default: False") + self.declareProperty("MergeGroups", False, doc="If True, the Groups from file1 will be merged to the master file. Default: False") - def PyExec(self): + def PyExec(self): #extract settings - mergeOffsets = self.getProperty("MergeOffsets").value - mergeSelections = self.getProperty("MergeSelections").value - mergeGroups = self.getProperty("MergeGroups").value - updateFileName = self.getPropertyValue("UpdateFile") - masterFileName = self.getPropertyValue("MasterFile") - outputFileName = self.getPropertyValue("OutputFile") - - - if (masterFileName == outputFileName) : - raise RuntimeError('The output file must be different to the master file.') - - self.DisplayMessage(mergeOffsets,mergeSelections,mergeGroups,updateFileName,masterFileName) - - updateFile = open(updateFileName,"r") - updateDict=dict() - lastNumber = 0 - linesUpdated = 0 - linesUntouched = 0 - linesAdded = 0 - linesInvalid=0 - for line in updateFile: - if not self.IsComment(line): + mergeOffsets = self.getProperty("MergeOffsets").value + mergeSelections = self.getProperty("MergeSelections").value + mergeGroups = self.getProperty("MergeGroups").value + updateFileName = self.getPropertyValue("UpdateFile") + masterFileName = self.getPropertyValue("MasterFile") + outputFileName = self.getPropertyValue("OutputFile") + + + if (masterFileName == outputFileName) : + raise RuntimeError('The output file must be different to the master file.') + + self.DisplayMessage(mergeOffsets,mergeSelections,mergeGroups,updateFileName,masterFileName) + + updateFile = open(updateFileName,"r") + updateDict=dict() + lastNumber = 0 + linesUpdated = 0 + linesUntouched = 0 + linesAdded = 0 + linesInvalid=0 + for line in updateFile: + if not self.IsComment(line): #process line - try: - (number,UDET,offset,select,group) = self.ProcessLine(line) - except ValueError: - pass + try: + (number,UDET,offset,select,group) = self.ProcessLine(line) + except ValueError: + pass #remeber all of the values - updateDict[UDET] = (offset,select,group) + updateDict[UDET] = (offset,select,group) - updateFile.close() - self.log().information(str(len(updateDict)) + " updates found in " + updateFileName) + updateFile.close() + self.log().information(str(len(updateDict)) + " updates found in " + updateFileName) - masterFile = open(masterFileName,"r") - outputFile = open(outputFileName,"w") + masterFile = open(masterFileName,"r") + outputFile = open(outputFileName,"w") - for line in masterFile: - if self.IsComment(line): + for line in masterFile: + if self.IsComment(line): #copy the comment over - outputFile.write(line) - else: + outputFile.write(line) + else: #process line - try: - (number,UDET,masterOffset,masterSelect,masterGroup) = self.ProcessLine(line) - lastNumber = number + try: + (number,UDET,masterOffset,masterSelect,masterGroup) = self.ProcessLine(line) + lastNumber = number #If line to be updated - if UDET in updateDict: - (offset,select,group)=updateDict.pop(UDET) - linesUpdated += 1 - if mergeOffsets: - masterOffset = offset - if mergeSelections: - masterSelect = select - if mergeGroups: - masterGroup = group - else: - linesUntouched += 1 - outputFile.write(self.FormatLine(number,UDET,masterOffset,masterSelect,masterGroup)) - except ValueError: + if UDET in updateDict: + (offset,select,group)=updateDict.pop(UDET) + linesUpdated += 1 + if mergeOffsets: + masterOffset = offset + if mergeSelections: + masterSelect = select + if mergeGroups: + masterGroup = group + else: + linesUntouched += 1 + outputFile.write(self.FormatLine(number,UDET,masterOffset,masterSelect,masterGroup)) + except ValueError: #invalid line - ignore it - linesInvalid += 1 + linesInvalid += 1 #add any lines at the end - for UDET in updateDict.keys(): - (offset,select,group)=updateDict.pop(UDET) - lastNumber += 1 - outputFile.write(self.FormatLine(lastNumber,UDET,offset,select,group)) - linesAdded += 1 + for UDET in updateDict.keys(): + (offset,select,group)=updateDict.pop(UDET) + lastNumber += 1 + outputFile.write(self.FormatLine(lastNumber,UDET,offset,select,group)) + linesAdded += 1 - self.log().information("{0} lines Updated, {1} lines added, {2} lines untouched".format(linesUpdated,linesAdded,linesUntouched)) + self.log().information("{0} lines Updated, {1} lines added, {2} lines untouched".format(linesUpdated,linesAdded,linesUntouched)) #close the files - masterFile.close() - outputFile.close() + masterFile.close() + outputFile.close() - def DisplayMessage(self,mergeOffsets,mergeSelections,mergeGroups,fileName1,fileName2): + def DisplayMessage(self,mergeOffsets,mergeSelections,mergeGroups,fileName1,fileName2): #Log the settings string - outputString = "Merging " - if (mergeOffsets): - outputString+= "offsets, " - if (mergeSelections): - outputString+= "selections, " - if (mergeGroups): - outputString+= "groups, " + outputString = "Merging " + if (mergeOffsets): + outputString+= "offsets, " + if (mergeSelections): + outputString+= "selections, " + if (mergeGroups): + outputString+= "groups, " #strip the final comma - outputString = outputString [0:len(outputString)-2] - outputString += " from file " + fileName1 + " into " + fileName2 - self.log().information(outputString) - - def IsComment(self,line): - return line.startswith("#") - - def ProcessLine(self,line): - try: - elements = line.split() - number =int(elements[0]) - UDET =int(elements[1]) - offset =float(elements[2]) - select =int(elements[3]) - group =int(elements[4]) - except: - raise ValueError("invalid line: " + line) - return (number,UDET,offset,select,group) - - def FormatLine(self,number,UDET,offset,select,group): - line = "{0:9d}{1:16d}{2:16.7f}{3:9d}{4:9d}\n".format(number,UDET,offset,select,group) - return line + outputString = outputString [0:len(outputString)-2] + outputString += " from file " + fileName1 + " into " + fileName2 + self.log().information(outputString) + + def IsComment(self,line): + return line.startswith("#") + + def ProcessLine(self,line): + try: + elements = line.split() + number =int(elements[0]) + UDET =int(elements[1]) + offset =float(elements[2]) + select =int(elements[3]) + group =int(elements[4]) + except: + raise ValueError("invalid line: " + line) + return (number,UDET,offset,select,group) + + def FormatLine(self,number,UDET,offset,select,group): + line = "{0:9d}{1:16d}{2:16.7f}{3:9d}{4:9d}\n".format(number,UDET,offset,select,group) + return line ############################################################################################# AlgorithmFactory.subscribe(MergeCalFiles()) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py index 9bb2ba9ed9a7..a4b49a463d6d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py @@ -37,7 +37,7 @@ def name(self): def summary(self): return "Determines the characterizations of a workspace." - + def PyInit(self): # input parameters self.declareProperty(WorkspaceProperty("InputWorkspace", "", @@ -49,23 +49,23 @@ def PyInit(self): "Table of characterization information") self.declareProperty("ReductionProperties", - "__pd_reduction_properties", + "__pd_reduction_properties", validator=StringMandatoryValidator(), doc="Property manager name for the reduction") defaultMsg = " run to use. 0 to use value in table, -1 to not use." - self.declareProperty("BackRun", 0, + self.declareProperty("BackRun", 0, doc="The background" + defaultMsg) - self.declareProperty("NormRun", 0, + self.declareProperty("NormRun", 0, doc="The background" + defaultMsg) - self.declareProperty("NormBackRun", 0, + self.declareProperty("NormBackRun", 0, doc="The background" + defaultMsg) - self.declareProperty(StringArrayProperty("FrequencyLogNames", ["SpeedRequest1", "Speed1", "frequency"], + self.declareProperty(StringArrayProperty("FrequencyLogNames", ["SpeedRequest1", "Speed1", "frequency"], direction=Direction.Input), "Possible log names for frequency.") - self.declareProperty(StringArrayProperty("WaveLengthLogNames", ["LambdaRequest", "lambda"], + self.declareProperty(StringArrayProperty("WaveLengthLogNames", ["LambdaRequest", "lambda"], direction=Direction.Input), "Candidate log names for wave length.") @@ -119,7 +119,7 @@ def PyExec(self): self.log().information("Determined frequency: " + str(frequency) \ + " Hz, center wavelength:" \ + str(wavelength) + " Angstrom") - + # get a row of the table info = self.getLine(char, frequency, wavelength) @@ -140,7 +140,7 @@ def PyExec(self): def processInformation(self, prop_man, info_dict): for key in COL_NAMES: val = info_dict[key] - # Convert comma-delimited list to array, else return the original + # Convert comma-delimited list to array, else return the original # value. if type("") == type(val): if (len(val)==0) and (key in DEF_INFO.keys()): @@ -177,7 +177,7 @@ def getLine(self, char, frequency, wavelength): # go through every row looking for a match result = dict(DEF_INFO) - icount = 0 + icount = 0 for i in xrange(char.rowCount()): row = char.row(i) if not self.closeEnough(frequency, row['frequency']): @@ -206,7 +206,7 @@ def getFrequency(self, logs, wkspName): self.log().information(msg) else: frequency = frequency.getStatistics().mean - if frequency == 0.: + if frequency == 0.: self.log().information("'%s' mean value is zero" % name) else: self.log().information("Found frequency in %s log" \ @@ -219,13 +219,13 @@ def getFrequency(self, logs, wkspName): def getWavelength(self, logs, wkspName): """ Get wave length Wavelength can be given by 2 sample logs, either LambdaRequest or lambda. - And its unit can be either Angstrom or A. + And its unit can be either Angstrom or A. """ wavelengthnames = self.getProperty("WaveLengthLogNames").value - for name in wavelengthnames: - # skip if not exists - if name not in logs.keys(): + for name in wavelengthnames: + # skip if not exists + if name not in logs.keys(): continue # get value @@ -233,7 +233,7 @@ def getWavelength(self, logs, wkspName): # unit if name == "LambdaRequest": - if wavelength.units != "Angstrom": + if wavelength.units != "Angstrom": msg = "Only know how to deal with LambdaRequest in Angstrom, not %s" % (wavelength.units) self.log().warning(msg) break @@ -246,17 +246,17 @@ def getWavelength(self, logs, wkspName): else: if wavelength.units != "Angstrom" and wavelength.units != "A": - msg = "Only know how to deal with %s in Angstrom (A) but not %s" % (name, + msg = "Only know how to deal with %s in Angstrom (A) but not %s" % (name, wavelength.units) self.log().warning(msg) break # return - wavelength = wavelength.getStatistics().mean - if wavelength == 0.: - self.log().warning("'%s' mean value is zero" % name) + wavelength = wavelength.getStatistics().mean + if wavelength == 0.: + self.log().warning("'%s' mean value is zero" % name) break - else: + else: return wavelength # ENDFOR diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py index 5120101e9c90..43a1655ceb0a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py @@ -36,7 +36,7 @@ def PyExec(self): coeffs = self._calculateAbsorption(ascii_wkspace, float(thickness)) coeffs.setYUnitLabel("Attenuation Factor (I/I0)") - coeffs.setYUnit(""); + coeffs.setYUnit("") coeffs.setDistribution(True) self.setProperty("OutputWorkspace", coeffs) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py index 612bd8ee0d8c..e26796bc3c08 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py @@ -93,7 +93,7 @@ def makePlausibleChopperSpeed(self, chopperSpeed): # This is related to ticket #10090, where a new field in new data is used # when that ticket is finished, new data files will not need this # cleanup method anymore. - return np.floor((chopperSpeed + 250.0) / 500.0) * 500.0; + return np.floor((chopperSpeed + 250.0) / 500.0) * 500.0 def instrumentsMatch(self, leftWorkspace, rightWorkspace): leftInstrument = leftWorkspace.getInstrument() @@ -112,7 +112,7 @@ def instrumentParametersMatch(self, leftInstrument, rightInstrument): if abs(leftValue - rightValue) > 1e-12: raise RuntimeError("Instrument parameter '%s'/'%s' does not match" % parameterTuple) - return True; + return True def getParameterValue(self, instrument, parameterTuple): return instrument.getComponentByName(parameterTuple[0]).getNumberParameter(parameterTuple[1])[0] @@ -137,17 +137,17 @@ def handleError(self, error): raise RuntimeError("Workspaces can not be merged. %s. Aborting." % (str(error))) def getWorkspacesRecursive(self, workspace): - returnList = [] - if isinstance(workspace, WorkspaceGroup): - for i in range(workspace.getNumberOfEntries()): - returnList += self.getWorkspacesRecursive(workspace.getItem(i)) + returnList = [] + if isinstance(workspace, WorkspaceGroup): + for i in range(workspace.getNumberOfEntries()): + returnList += self.getWorkspacesRecursive(workspace.getItem(i)) - elif isinstance(workspace, MatrixWorkspace): - returnList.append(workspace) + elif isinstance(workspace, MatrixWorkspace): + returnList.append(workspace) - else: - raise RuntimeError("Can only merge MatrixWorkspaces, this is " + type(workspace)) + else: + raise RuntimeError("Can only merge MatrixWorkspaces, this is " + type(workspace)) - return returnList + return returnList AlgorithmFactory.subscribe(PoldiMerge) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py index 9c173170f685..4e1722361f91 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py @@ -138,7 +138,7 @@ def PyExec(self): qMin = self.getProperty("QMin").value qStep = self.getProperty("QStep").value if (qStep > 0): #force logarithmic binning - qStep = -qStep; + qStep = -qStep # angle offset angleOffsetDeg = self.getProperty("AngleOffset").value diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SaveVulcanGSS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SaveVulcanGSS.py index 4ef3adb13c09..8b8404cbd1cf 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SaveVulcanGSS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SaveVulcanGSS.py @@ -24,14 +24,14 @@ def summary(self): def PyInit(self): """ Declare properties - """ - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), + """ + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), "Focussed diffraction workspace to be exported to GSAS file. ") self.declareProperty(FileProperty("BinFilename","", FileAction.Load, ['.dat']), "Name of a data file containing the bin boundaries in Log(TOF). ") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), "Name of rebinned matrix workspace. ") self.declareProperty(FileProperty("GSSFilename","", FileAction.Save, ['.gda']), @@ -42,7 +42,7 @@ def PyInit(self): self.declareProperty("GSSParmFileName", "", "GSAS parameter file name for this GSAS data file.") return - + def PyExec(self): """ Main Execution Body """ @@ -69,7 +69,7 @@ def PyExec(self): # Generate GSAS file outputws = self._saveGSAS(gsaws, outgssfilename) - + # Convert header and bank information ipts = self.getPropertyValue("IPTS") parmfname = self.getPropertyValue("GSSParmFileName") @@ -115,14 +115,14 @@ def _loadRefLogBinFile(self, logbinfilename): return vecPow10X - + def _rebinVdrive(self, inputws, vec_refT, outputwsname): """ Rebin to match VULCAN's VDRIVE-generated GSAS file Arguments: - inputws : focussed workspace - vec_refT: list of TOF bins """ - # Create a complicated bin parameter + # Create a complicated bin parameter params = [] for ibin in xrange(len(vec_refT)-1): x0 = vec_refT[ibin] @@ -133,7 +133,7 @@ def _rebinVdrive(self, inputws, vec_refT, outputwsname): # last bin x0 = vec_refT[-1] - xf = 2*dx + x0 + xf = 2*dx + x0 params.extend([x0, 2*dx, xf]) # Rebin @@ -155,7 +155,7 @@ def _rebinVdrive(self, inputws, vec_refT, outputwsname): # ENDFOR (i) # ENDFOR (iws) api.DeleteWorkspace(Workspace=tempws) - gsaws = api.CreateWorkspace(DataX=newvecx, DataY=newvecy, DataE=newvece, NSpec=numhist, + gsaws = api.CreateWorkspace(DataX=newvecx, DataY=newvecy, DataE=newvece, NSpec=numhist, UnitX="TOF", ParentWorkspace=inputws, OutputWorkspace=outputwsname) return gsaws @@ -167,8 +167,8 @@ def _saveGSAS(self, gsaws, gdafilename): # Convert from PointData to Histogram gsaws = api.ConvertToHistogram(InputWorkspace=gsaws, OutputWorkspace=str(gsaws)) - # Save - api.SaveGSS(InputWorkspace=gsaws, Filename=gdafilename, SplitFiles=False, Append=False, + # Save + api.SaveGSS(InputWorkspace=gsaws, Filename=gdafilename, SplitFiles=False, Append=False, Format="SLOG", MultiplyByBinWidth=False, ExtendedHeader=False, UseSpectrumNumberAsBankID=True) return gsaws @@ -181,18 +181,18 @@ def _rewriteGSSFile(self, gssfilename, newheader): gfile = open(gssfilename, "r") lines = gfile.readlines() gfile.close() - + # New file filebuffer = "" filebuffer += newheader - + inbank = False banklines = [] for line in lines: cline = line.strip() if len(cline) == 0: continue - + if line.startswith("BANK"): # Indicate a new bank if len(banklines) == 0: @@ -200,7 +200,7 @@ def _rewriteGSSFile(self, gssfilename, newheader): inbank = True banklines.append(line.strip("\n")) else: - # bank line for non-first bank. + # bank line for non-first bank. tmpbuffer = self._rewriteOneBankData(banklines) filebuffer += tmpbuffer banklines = [line] @@ -208,33 +208,33 @@ def _rewriteGSSFile(self, gssfilename, newheader): elif (inbank is True and cline.startswith("#") is False): # Write data line banklines.append(line.strip("\n")) - + # ENDFOR - - if len(banklines) > 0: - tmpbuffer = self._rewriteOneBankData(banklines) + + if len(banklines) > 0: + tmpbuffer = self._rewriteOneBankData(banklines) filebuffer += tmpbuffer else: raise NotImplementedError("Impossible to have this") - + # Overwrite the original file ofile = open(gssfilename, "w") ofile.write(filebuffer) ofile.close() - + return - + def _genVulcanGSSHeader(self, ws, gssfilename, ipts, parmfname): """ """ from datetime import datetime import os.path - + # Get necessary information title = ws.getTitle() - - run = ws.getRun() + + run = ws.getRun() # Get information on start/stop processtime = True @@ -249,45 +249,45 @@ def _genVulcanGSSHeader(self, ws, gssfilename, ipts, parmfname): # property run_start and duration exist runstart_sec = runstart.split(".")[0] runstart_ns = runstart.split(".")[1] - + utctime = datetime.strptime(runstart_sec, '%Y-%m-%dT%H:%M:%S') time0=datetime.strptime("1990-01-01T0:0:0",'%Y-%m-%dT%H:%M:%S') - + delta = utctime-time0 - try: + try: total_nanosecond_start = int(delta.total_seconds()*int(1.0E9)) + int(runstart_ns) - except: - total_seconds = delta.days*24*3600 + delta.seconds + except: + total_seconds = delta.days*24*3600 + delta.seconds total_nanosecond_start = total_seconds * int(1.0E9) + int(runstart_ns) total_nanosecond_stop = total_nanosecond_start + int(duration*1.0E9) else: # not both property is found total_nanosecond_start = 0 total_nanosecond_stop = 0 - + self.log().debug("Start = %d, Stop = %d" % (total_nanosecond_start, total_nanosecond_stop)) - + # Construct new header newheader = "" - + if len(title) > 80: title = title[0:80] newheader += "%-80s\n" % (title) - + newheader += "%-80s\n" % ( "Instrument parameter file: %s" %(parmfname) ) - + newheader += "%-80s\n" % ( "#IPTS: %s" % (str(ipts)) ) - + newheader += "%-80s\n" % ( "#binned by: Mantid" ) - + newheader += "%-80s\n" % ( "#GSAS file name: %s" % (os.path.basename(gssfilename)) ) - + newheader += "%-80s\n" % ( "#GSAS IPARM file: %s" % (parmfname) ) - + newheader += "%-80s\n" % ( "#Pulsestart: %d" % (total_nanosecond_start) ) - + newheader += "%-80s\n" % ( "#Pulsestop: %d" % (total_nanosecond_stop) ) - + return newheader @@ -295,33 +295,33 @@ def _rewriteOneBankData(self, banklines): """ first line is for bank information """ wbuf = "" - + # Rewrite bank lines bankline = banklines[0].strip() terms = bankline.split() tofmin = float(banklines[1].split()[0]) tofmax = float(banklines[-1].split()[0]) - + terms[5] = "%.1f" % (tofmin) terms[6] = "%.1f" % (tofmax) - + newbankline = "" - + # title for t in terms: newbankline += "%s " % (t) wbuf = "%-80s\n" % (newbankline) - + # data for i in xrange(1, len(banklines)): - cline = banklines[i] - + cline = banklines[i] + terms = cline.split() try: tof = float(terms[0]) y = float(terms[1]) e = float(terms[2]) - + x_s = "%.1f" % (tof) y_s = "%.1f" % (y) e_s = "%.2f" % (e) @@ -333,7 +333,7 @@ def _rewriteOneBankData(self, banklines): wbuf += "%-80s\n" % (temp) # ENDFOR - + return wbuf diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py index 7ed8baf4d4f2..ac30f56eeb42 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py @@ -1,5 +1,5 @@ from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory, FileProperty, FileAction -from mantid.kernel import Direction, StringListValidator +from mantid.kernel import Direction, StringListValidator import warnings _OUTPUTLEVEL = "NOOUTPUT" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py index 39c81a9f31a3..8786acbeea29 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py @@ -36,8 +36,8 @@ def PyExec(self): x_ordered = x[indexes] if input_ws.isHistogramData(): - max_index = np.argmax(indexes) - indexes = np.delete(indexes, max_index) + max_index = np.argmax(indexes) + indexes = np.delete(indexes, max_index) y_ordered = y[indexes] e_ordered = e[indexes] diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py index fba0c883eb6e..b5fdca55a691 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py @@ -10,14 +10,14 @@ class Projection(object): u = "u" v = "v" w = "w" - + class ProjectionUnit(object): r = "r" a = "a" - - + + class CutMD(DataProcessorAlgorithm): - + def category(self): return 'MDAlgorithms' @@ -27,30 +27,30 @@ def summary(self): def PyInit(self): self.declareProperty(IMDEventWorkspaceProperty('InputWorkspace', '', direction=Direction.Input), doc='MDWorkspace to slice') - + self.declareProperty(ITableWorkspaceProperty('Projection', '', direction=Direction.Input, optional = PropertyMode.Optional), doc='Projection') - + self.declareProperty(FloatArrayProperty(name='P1Bin', values=[]), doc='Projection 1 binning') - + self.declareProperty(FloatArrayProperty(name='P2Bin', values=[]), doc='Projection 2 binning') - + self.declareProperty(FloatArrayProperty(name='P3Bin', values=[]), doc='Projection 3 binning') - + self.declareProperty(FloatArrayProperty(name='P4Bin', values=[]), doc='Projection 4 binning') self.declareProperty(IMDWorkspaceProperty('OutputWorkspace', '', direction=Direction.Output), doc='Output cut workspace') - + self.declareProperty(name="NoPix", defaultValue=False, doc="If False creates a full MDEventWorkspaces as output. True to create an MDHistoWorkspace as output. This is DND only in Horace terminology.") - + self.declareProperty(name="CheckAxes", defaultValue=True, doc="Check that the axis look to be correct, and abort if not.") - - + + def __calculate_steps(self, extents, horace_binning ): # Because the step calculations may involve moving the extents, we re-publish the extents. out_extents = extents @@ -61,13 +61,13 @@ def __calculate_steps(self, extents, horace_binning ): max_extent_index = (i*2) + 1 min_extent_index = (i*2) dim_range = extents[ max_extent_index ] - extents[ min_extent_index ] - + if n_arguments == 0: raise ValueError("binning parameter cannot be empty") elif n_arguments == 1: step_size = horace_binning[i][0] if step_size > dim_range: - step_size = dim_range + step_size = dim_range n_bins = int( dim_range / step_size) # Correct the max extent to fit n * step_size out_extents[max_extent_index] = extents[min_extent_index] + ( n_bins * step_size ) @@ -81,7 +81,7 @@ def __calculate_steps(self, extents, horace_binning ): step_size = horace_binning[i][1] dim_range = dim_max - dim_min if step_size > dim_range: - step_size = dim_range + step_size = dim_range n_bins = int( dim_range / step_size) # Correct the max extent to fit n * step_size out_extents[ max_extent_index ] = dim_min + ( n_bins * step_size ) @@ -90,40 +90,40 @@ def __calculate_steps(self, extents, horace_binning ): raise ValueError("Number of bins calculated to be < 1") out_n_bins.append( n_bins ) return out_extents, out_n_bins - + def __extents_in_current_projection(self, to_cut, dimension_index): - + dim = to_cut.getDimension(dimension_index) dim_min = dim.getMinimum() dim_max = dim.getMaximum() return (dim_min, dim_max) - + def __calculate_extents(self, v, u, w, limits): M=np.array([u,v,w]) Minv=np.linalg.inv(M) - + # unpack limits Hrange, Krange, Lrange = limits - + # Create a numpy 2D array. Makes finding minimums and maximums for each transformed coordinates over every corner easier. new_coords = np.empty([8, 3]) counter = 0 for h in Hrange: - for k in Krange: - for l in Lrange: - original_corner=np.array([h,k,l]) - new_coords[counter]=np.dot(original_corner, Minv) - counter += 1 - + for k in Krange: + for l in Lrange: + original_corner=np.array([h,k,l]) + new_coords[counter]=np.dot(original_corner, Minv) + counter += 1 + # Get the min max extents extents = list() for i in range(0,3): # Vertical slice down each corner for each dimension, then determine the max, min and use as extents extents.append(np.amin(new_coords[:,i])) extents.append(np.amax(new_coords[:,i])) - + return extents - + def __uvw_from_projection_table(self, projection_table): if not isinstance(projection_table, ITableWorkspace): I = np.identity(3) @@ -136,26 +136,26 @@ def __uvw_from_projection_table(self, projection_table): else: w = np.array(projection_table.column(Projection.w)) return (u, v, w) - + def __units_from_projection_table(self, projection_table): if not isinstance(projection_table, ITableWorkspace) or not "type" in projection_table.getColumnNames(): units = (ProjectionUnit.r, ProjectionUnit.r, ProjectionUnit.r) else: units = tuple(projection_table.column("type")) return units - - + + def __make_labels(self, projection): class Mapping: - + def __init__(self, replace): self.__replace = replace - + def replace(self, entry): if np.absolute(entry) == 1: if entry > 0: - return self.__replace + return self.__replace else: return "-" + self.__replace elif entry == 0: @@ -163,40 +163,40 @@ def replace(self, entry): else: return "%.2f%s" % ( entry, self.__replace ) return entry - - crystallographic_names = ['zeta', 'eta', 'xi' ] + + crystallographic_names = ['zeta', 'eta', 'xi' ] labels = list() for i in range(len(projection)): cmapping = Mapping(crystallographic_names[i]) labels.append( [cmapping.replace(x) for x in projection[i] ] ) - + return labels - + def __verify_projection_input(self, projection_table): if isinstance(projection_table, ITableWorkspace): column_names = set(projection_table.getColumnNames()) if not column_names == set([Projection.u, Projection.v, 'type']): - if not column_names == set([Projection.u, Projection.v, 'offsets', 'type']): - if not column_names == set([Projection.u, Projection.v, Projection.w, 'offsets', 'type']): - raise ValueError("Projection table schema is wrong! Column names received: " + str(column_names) ) + if not column_names == set([Projection.u, Projection.v, 'offsets', 'type']): + if not column_names == set([Projection.u, Projection.v, Projection.w, 'offsets', 'type']): + raise ValueError("Projection table schema is wrong! Column names received: " + str(column_names) ) if projection_table.rowCount() != 3: raise ValueError("Projection table expects 3 rows") - + def __scale_projection(self, (u, v, w), origin_units, target_units, to_cut): - + if set(origin_units) == set(target_units): return (u,v,w) # Nothing to do. - + ol = to_cut.getExperimentInfo(0).sample().getOrientedLattice() - + projection_scaled = [u, v, w] - + to_from_pairs = zip(origin_units, target_units) for i in range(len(to_from_pairs)) : - + proj = projection_scaled[i] d_star = 2 * np.pi * ol.dstar( float(proj[0]), float(proj[1]), float(proj[2]) ) - + from_unit, to_unit = to_from_pairs[i] if from_unit == to_unit: continue @@ -205,44 +205,44 @@ def __scale_projection(self, (u, v, w), origin_units, target_units, to_cut): else: # From rlu to inverse Anstroms projection_scaled[i] /= d_star return projection_scaled - - + + def PyExec(self): - + logger.warning('You are running algorithm %s that is the beta stage of development' % (self.name())) - + to_cut = self.getProperty("InputWorkspace").value - + ndims = to_cut.getNumDims() - + nopix = self.getProperty("NoPix").value - + projection_table = self.getProperty("Projection").value self.__verify_projection_input(projection_table) - + p1_bins = self.getProperty("P1Bin").value p2_bins = self.getProperty("P2Bin").value p3_bins = self.getProperty("P3Bin").value p4_bins_property = self.getProperty("P4Bin") - p4_bins = p4_bins_property.value - - x_extents = self.__extents_in_current_projection(to_cut, 0); - y_extents = self.__extents_in_current_projection(to_cut, 1); - z_extents = self.__extents_in_current_projection(to_cut, 2); - + p4_bins = p4_bins_property.value + + x_extents = self.__extents_in_current_projection(to_cut, 0) + y_extents = self.__extents_in_current_projection(to_cut, 1) + z_extents = self.__extents_in_current_projection(to_cut, 2) + projection = self.__uvw_from_projection_table(projection_table) target_units = self.__units_from_projection_table(projection_table) origin_units = (ProjectionUnit.r, ProjectionUnit.r, ProjectionUnit.r) # TODO. This is a hack! - + u,v,w = self.__scale_projection(projection, origin_units, target_units, to_cut) - + extents = self.__calculate_extents(v, u, w, ( x_extents, y_extents, z_extents ) ) extents, bins = self.__calculate_steps( extents, ( p1_bins, p2_bins, p3_bins ) ) - + if not p4_bins_property.isDefault: if (ndims == 4): n_args = len(p4_bins) - min, max = self.__extents_in_current_projection(to_cut, 3); + min, max = self.__extents_in_current_projection(to_cut, 3) d_range = max - min if n_args == 1: step_size = p4_bins[0] @@ -259,21 +259,21 @@ def PyExec(self): if step_size > dim_range: step_size = dim_range nbins = int( dim_range / step_size) - + extents.append(min) extents.append(max) bins.append(int(nbins)) - + e_units = to_cut.getDimension(3).getUnits() - + temp = list(target_units) temp.append(target_units) target_units = tuple(temp) else: raise ValueError("Cannot specify P4Bins unless the workspace is of sufficient dimensions") - + projection_labels = self.__make_labels(projection) - + cut_alg_name = "BinMD" if nopix else "SliceMD" ''' Actually perform the binning operation @@ -285,46 +285,46 @@ def PyExec(self): cut_alg.setProperty("NormalizeBasisVectors", False) cut_alg.setProperty("AxisAligned", False) # Now for the basis vectors. - + n_padding = __builtin__.max(0, ndims-3) - + for i in range(0, ndims): - - + + if i <= 2: - + label = projection_labels[i] unit = target_units[i] vec = list(projection[i]) + ( [0] * n_padding ) - + # These are always orthogonal to the rest. else: orthogonal_dimension = to_cut.getDimension(i) - label = orthogonal_dimension.getName() + label = orthogonal_dimension.getName() unit = orthogonal_dimension.getUnits() vec = [0] * ndims vec[i] = 1 - - value = "%s, %s, %s" % ( label, unit, ",".join(map(str, vec))) - cut_alg.setPropertyValue("BasisVector{0}".format(i) , value) - - + + value = "%s, %s, %s" % ( label, unit, ",".join(map(str, vec))) + cut_alg.setPropertyValue("BasisVector{0}".format(i) , value) + + cut_alg.setProperty("OutputExtents", extents) cut_alg.setProperty("OutputBins", bins) - + cut_alg.execute() - + slice = cut_alg.getProperty("OutputWorkspace").value - - + + # Attach the w-matrix (projection matrix) if slice.getNumExperimentInfo() > 0: u, v, w = projection w_matrix = np.array([u, v, w]).flatten().tolist() info = slice.getExperimentInfo(0) info.run().addProperty("W_MATRIX", w_matrix, True) - + self.setProperty("OutputWorkspace", slice) - - + + AlgorithmFactory.subscribe(CutMD) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py index 0bac631200b2..93867743acd6 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py @@ -395,7 +395,7 @@ def _save_output(self, iq_output, iqxy_output, output_dir, property_manager): @param property_manager: property manager object """ output_msg = "" - + def _save_ws(iq_ws): if AnalysisDataService.doesExist(iq_ws): proc_xml = "" @@ -407,14 +407,14 @@ def _save_ws(iq_ws): elif len(process_file)>0: Logger("HFIRSANSReduction").error("Could not read %s\n" % process_file) if property_manager.existsProperty("SetupAlgorithm"): - setup_info = property_manager.getProperty("SetupAlgorithm").value - proc_xml += "\n\n" + setup_info = property_manager.getProperty("SetupAlgorithm").value + proc_xml += "\n\n" # The instrument name refers to the UI, which is named BIOSANS for all HFIR SANS - proc_xml += " BIOSANS\n" - proc_xml += " %s\n" % setup_info - filename = self.getProperty("Filename").value - proc_xml += " %s\n" % filename - proc_xml += "\n" + proc_xml += " BIOSANS\n" + proc_xml += " %s\n" % setup_info + filename = self.getProperty("Filename").value + proc_xml += " %s\n" % filename + proc_xml += "\n" filename = os.path.join(output_dir, iq_ws+'.txt') @@ -448,7 +448,7 @@ def _save_ws(iq_ws): filename = _save_ws(item) if filename is not None: output_msg += "I(Q) saved in %s\n" % (filename) - + # Save I(Qx,Qy) if iqxy_output is not None: if AnalysisDataService.doesExist(iqxy_output): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py index 5ec56cf0159c..673230721c69 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py @@ -5,74 +5,74 @@ class MuscatData(PythonAlgorithm): def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" + return "Workflow\\MIDAS;PythonAlgorithms" def summary(self): - return "Calculates multiple scattering using a sample S(Q,w)." + return "Calculates multiple scattering using a sample S(Q,w)." def PyInit(self): - self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') - self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004'])) - self.declareProperty(name='Geom',defaultValue='Flat',validator=StringListValidator(['Flat','Cyl']), doc='Sample geometry') - self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample data run number') - self.declareProperty(name='SqwInput',defaultValue='',validator=StringMandatoryValidator(), doc='Sqw file run number') - self.declareProperty(name='NR1', defaultValue=1000, doc='MonteCarlo neutrons NR1. Default=1000') - self.declareProperty(name='NR2', defaultValue=1000, doc='MonteCarlo neutrons NR2. Default=1000') - self.declareProperty(name='Nms', defaultValue=1, doc='Number of scatterings. Default=1') - self.declareProperty(name='DetAngle', defaultValue=90.0, doc='Detector angle. Default=90.0') - self.declareProperty(name='Thick', defaultValue='',validator=StringMandatoryValidator(), doc='Sample thickness') - self.declareProperty(name='Width', defaultValue='',validator=StringMandatoryValidator(), doc='Sample width') - self.declareProperty(name='Height', defaultValue=3.0, doc='Sample height. Default=3.0') - self.declareProperty(name='Density', defaultValue=0.1, doc='Sample number density. Default=0.1') - self.declareProperty(name='SigScat', defaultValue=5.0, doc='Scattering cross-section. Default=5.0') - self.declareProperty(name='SigAbs', defaultValue=0.1, doc='Absorption cross-section. Default=0.1') - self.declareProperty(name='Temperature', defaultValue=300.0, doc='Sample temperature (K). Default=300.0') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Totals','Scat1','All'])) - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') + self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') + self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004'])) + self.declareProperty(name='Geom',defaultValue='Flat',validator=StringListValidator(['Flat','Cyl']), doc='Sample geometry') + self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample data run number') + self.declareProperty(name='SqwInput',defaultValue='',validator=StringMandatoryValidator(), doc='Sqw file run number') + self.declareProperty(name='NR1', defaultValue=1000, doc='MonteCarlo neutrons NR1. Default=1000') + self.declareProperty(name='NR2', defaultValue=1000, doc='MonteCarlo neutrons NR2. Default=1000') + self.declareProperty(name='Nms', defaultValue=1, doc='Number of scatterings. Default=1') + self.declareProperty(name='DetAngle', defaultValue=90.0, doc='Detector angle. Default=90.0') + self.declareProperty(name='Thick', defaultValue='',validator=StringMandatoryValidator(), doc='Sample thickness') + self.declareProperty(name='Width', defaultValue='',validator=StringMandatoryValidator(), doc='Sample width') + self.declareProperty(name='Height', defaultValue=3.0, doc='Sample height. Default=3.0') + self.declareProperty(name='Density', defaultValue=0.1, doc='Sample number density. Default=0.1') + self.declareProperty(name='SigScat', defaultValue=5.0, doc='Scattering cross-section. Default=5.0') + self.declareProperty(name='SigAbs', defaultValue=0.1, doc='Absorption cross-section. Default=0.1') + self.declareProperty(name='Temperature', defaultValue=300.0, doc='Sample temperature (K). Default=300.0') + self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Totals','Scat1','All'])) + self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') + self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') def PyExec(self): - from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform + from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform - if is_supported_f2py_platform(): - import IndirectMuscat as Main - run_f2py_compatibility_test() + if is_supported_f2py_platform(): + import IndirectMuscat as Main + run_f2py_compatibility_test() - self.log().information('Muscat input') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - geom = self.getPropertyValue('Geom') - sam = self.getPropertyValue('SamNumber') - sqwi = self.getPropertyValue('SqwInput') - sname = prefix+sam+'_'+ana - sqw = prefix+sqwi+'_'+ana + self.log().information('Muscat input') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + geom = self.getPropertyValue('Geom') + sam = self.getPropertyValue('SamNumber') + sqwi = self.getPropertyValue('SqwInput') + sname = prefix+sam+'_'+ana + sqw = prefix+sqwi+'_'+ana - NRUN1 = self.getPropertyValue('NR1') - NRUN2 = self.getPropertyValue('NR2') - NMST = self.getPropertyValue('Nms') - JRAND = 12345 - MRAND = 67890 - neut = [int(NRUN1), int(NRUN2), int(JRAND), int(MRAND), int(NMST)] + NRUN1 = self.getPropertyValue('NR1') + NRUN2 = self.getPropertyValue('NR2') + NMST = self.getPropertyValue('Nms') + JRAND = 12345 + MRAND = 67890 + neut = [int(NRUN1), int(NRUN2), int(JRAND), int(MRAND), int(NMST)] - HEIGHT = 3.0 - alfa = self.getPropertyValue('DetAngle') - THICK = self.getPropertyValue('Thick') - WIDTH = self.getPropertyValue('Width') - HEIGHT = self.getPropertyValue('Height') - if geom == 'Flat': - beam = [float(THICK), float(WIDTH), float(HEIGHT), float(alfa)] - if geom == 'Cyl': - beam = [float(THICK), float(WIDTH), float(HEIGHT), 0.0] #beam = [WIDTH, WIDTH2, HEIGHT, 0.0] - dens = self.getPropertyValue('Density') - sigb = self.getPropertyValue('SigScat') - siga = self.getPropertyValue('SigAbs') - temp = self.getPropertyValue('Temperature') - sam = [float(temp), float(dens), float(siga), float(sigb)] + HEIGHT = 3.0 + alfa = self.getPropertyValue('DetAngle') + THICK = self.getPropertyValue('Thick') + WIDTH = self.getPropertyValue('Width') + HEIGHT = self.getPropertyValue('Height') + if geom == 'Flat': + beam = [float(THICK), float(WIDTH), float(HEIGHT), float(alfa)] + if geom == 'Cyl': + beam = [float(THICK), float(WIDTH), float(HEIGHT), 0.0] #beam = [WIDTH, WIDTH2, HEIGHT, 0.0] + dens = self.getPropertyValue('Density') + sigb = self.getPropertyValue('SigScat') + siga = self.getPropertyValue('SigAbs') + temp = self.getPropertyValue('Temperature') + sam = [float(temp), float(dens), float(siga), float(sigb)] - kr1 = 1 - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value - Main.MuscatDataStart(sname,geom,neut,beam,sam,sqw,kr1,verbOp,plotOp,saveOp) + kr1 = 1 + verbOp = self.getProperty('Verbose').value + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value + Main.MuscatDataStart(sname,geom,neut,beam,sam,sqw,kr1,verbOp,plotOp,saveOp) AlgorithmFactory.subscribe(MuscatData) # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py index a1a21ca4818d..eb93747adc62 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py @@ -5,96 +5,96 @@ class MuscatFunc(PythonAlgorithm): def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" + return "Workflow\\MIDAS;PythonAlgorithms" def summary(self): - return "Calculates multiple scattering using S(Q,w) from specified functions." + return "Calculates multiple scattering using S(Q,w) from specified functions." def PyInit(self): - self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') - self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004'])) - self.declareProperty(name='Geom',defaultValue='Flat',validator=StringListValidator(['Flat','Cyl']), doc='') - self.declareProperty(name='Dispersion',defaultValue='Poly',validator=StringListValidator(['Poly','CE','SS']), doc='') - self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample data run number') - self.declareProperty(name='NR1', defaultValue=1000, doc='MonteCarlo neutrons NR1. Default=1000') - self.declareProperty(name='NR2', defaultValue=1000, doc='MonteCarlo neutrons NR2. Default=1000') - self.declareProperty(name='Nms', defaultValue=1, doc='Number of scatterings. Default=1') - self.declareProperty(name='DetAngle', defaultValue=90.0, doc='Detector angle. Default=90.0') - self.declareProperty(name='NQ', defaultValue=10, doc='Q-w grid: number of Q values. Default=10') - self.declareProperty(name='dQ', defaultValue=0.2, doc='Q-w grid: Q increment. Default=0.2') - self.declareProperty(name='NW', defaultValue=100, doc='Q-w grid: number of w values. Default=100') - self.declareProperty(name='dW', defaultValue=2.0, doc='Q-w grid: w increment (microeV). Default=2.0') - self.declareProperty(name='Coeff1', defaultValue=0., doc='Coefficient 1. Default=0.0') - self.declareProperty(name='Coeff2', defaultValue=0., doc='Coefficient 2. Default=0.0') - self.declareProperty(name='Coeff3', defaultValue=50.0, doc='Coefficient 3. Default=50.0') - self.declareProperty(name='Coeff4', defaultValue=0., doc='Coefficient 4. Default=0.0') - self.declareProperty(name='Coeff5', defaultValue=0., doc='Coefficient 5. Default=0.0') - self.declareProperty(name='Thick', defaultValue='',validator=StringMandatoryValidator(), doc='Sample thickness') - self.declareProperty(name='Width', defaultValue='',validator=StringMandatoryValidator(), doc='Sample width') - self.declareProperty(name='Height', defaultValue=3.0, doc='Sample height. Default=3.0') - self.declareProperty(name='Density', defaultValue=0.1, doc='Sample density. Default=0.1') - self.declareProperty(name='SigScat', defaultValue=5.0, doc='Scattering cross-section. Default=5.0') - self.declareProperty(name='SigAbs', defaultValue=0.1, doc='Absorption cross-section. Default=0.1') - self.declareProperty(name='Temperature', defaultValue=300.0, doc='Sample temperature (K). Default=300.0') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Totals','Scat1','All'])) - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') + self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') + self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004'])) + self.declareProperty(name='Geom',defaultValue='Flat',validator=StringListValidator(['Flat','Cyl']), doc='') + self.declareProperty(name='Dispersion',defaultValue='Poly',validator=StringListValidator(['Poly','CE','SS']), doc='') + self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample data run number') + self.declareProperty(name='NR1', defaultValue=1000, doc='MonteCarlo neutrons NR1. Default=1000') + self.declareProperty(name='NR2', defaultValue=1000, doc='MonteCarlo neutrons NR2. Default=1000') + self.declareProperty(name='Nms', defaultValue=1, doc='Number of scatterings. Default=1') + self.declareProperty(name='DetAngle', defaultValue=90.0, doc='Detector angle. Default=90.0') + self.declareProperty(name='NQ', defaultValue=10, doc='Q-w grid: number of Q values. Default=10') + self.declareProperty(name='dQ', defaultValue=0.2, doc='Q-w grid: Q increment. Default=0.2') + self.declareProperty(name='NW', defaultValue=100, doc='Q-w grid: number of w values. Default=100') + self.declareProperty(name='dW', defaultValue=2.0, doc='Q-w grid: w increment (microeV). Default=2.0') + self.declareProperty(name='Coeff1', defaultValue=0., doc='Coefficient 1. Default=0.0') + self.declareProperty(name='Coeff2', defaultValue=0., doc='Coefficient 2. Default=0.0') + self.declareProperty(name='Coeff3', defaultValue=50.0, doc='Coefficient 3. Default=50.0') + self.declareProperty(name='Coeff4', defaultValue=0., doc='Coefficient 4. Default=0.0') + self.declareProperty(name='Coeff5', defaultValue=0., doc='Coefficient 5. Default=0.0') + self.declareProperty(name='Thick', defaultValue='',validator=StringMandatoryValidator(), doc='Sample thickness') + self.declareProperty(name='Width', defaultValue='',validator=StringMandatoryValidator(), doc='Sample width') + self.declareProperty(name='Height', defaultValue=3.0, doc='Sample height. Default=3.0') + self.declareProperty(name='Density', defaultValue=0.1, doc='Sample density. Default=0.1') + self.declareProperty(name='SigScat', defaultValue=5.0, doc='Scattering cross-section. Default=5.0') + self.declareProperty(name='SigAbs', defaultValue=0.1, doc='Absorption cross-section. Default=0.1') + self.declareProperty(name='Temperature', defaultValue=300.0, doc='Sample temperature (K). Default=300.0') + self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Totals','Scat1','All'])) + self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') + self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') def PyExec(self): - from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform + from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform - if is_supported_f2py_platform(): - import IndirectMuscat as Main + if is_supported_f2py_platform(): + import IndirectMuscat as Main - run_f2py_compatibility_test() + run_f2py_compatibility_test() - self.log().information('Muscat input') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - geom = self.getPropertyValue('Geom') - disp = self.getPropertyValue('Dispersion') - sam = self.getPropertyValue('SamNumber') - sname = prefix+sam+'_'+ana + self.log().information('Muscat input') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + geom = self.getPropertyValue('Geom') + disp = self.getPropertyValue('Dispersion') + sam = self.getPropertyValue('SamNumber') + sname = prefix+sam+'_'+ana - NRUN1 = self.getPropertyValue('NR1') - NRUN2 = self.getPropertyValue('NR2') - NMST = self.getPropertyValue('Nms') - JRAND = 12345 - MRAND = 67890 - neut = [int(NRUN1), int(NRUN2), int(JRAND), int(MRAND), int(NMST)] + NRUN1 = self.getPropertyValue('NR1') + NRUN2 = self.getPropertyValue('NR2') + NMST = self.getPropertyValue('Nms') + JRAND = 12345 + MRAND = 67890 + neut = [int(NRUN1), int(NRUN2), int(JRAND), int(MRAND), int(NMST)] - HEIGHT = 3.0 - alfa = self.getPropertyValue('DetAngle') - THICK = self.getPropertyValue('Thick') - WIDTH = self.getPropertyValue('Width') - HEIGHT = self.getPropertyValue('Height') - if geom == 'Flat': - beam = [float(THICK), float(WIDTH), float(HEIGHT), float(alfa)] - if geom == 'Cyl': - beam = [float(THICK), float(WIDTH), float(HEIGHT), 0.0] #beam = [WIDTH, WIDTH2, HEIGHT, 0.0] - dens = self.getPropertyValue('Density') - sigb = self.getPropertyValue('SigScat') - siga = self.getPropertyValue('SigAbs') - sigss=sigb - temp = self.getPropertyValue('Temperature') - sam = [float(temp), float(dens), float(siga), float(sigb)] + HEIGHT = 3.0 + alfa = self.getPropertyValue('DetAngle') + THICK = self.getPropertyValue('Thick') + WIDTH = self.getPropertyValue('Width') + HEIGHT = self.getPropertyValue('Height') + if geom == 'Flat': + beam = [float(THICK), float(WIDTH), float(HEIGHT), float(alfa)] + if geom == 'Cyl': + beam = [float(THICK), float(WIDTH), float(HEIGHT), 0.0] #beam = [WIDTH, WIDTH2, HEIGHT, 0.0] + dens = self.getPropertyValue('Density') + sigb = self.getPropertyValue('SigScat') + siga = self.getPropertyValue('SigAbs') + sigss=sigb + temp = self.getPropertyValue('Temperature') + sam = [float(temp), float(dens), float(siga), float(sigb)] - NQ = self.getPropertyValue('NQ') - dQ = self.getPropertyValue('dQ') - Nw = self.getPropertyValue('NW') - dw = self.getPropertyValue('dW') #in microeV - grid = [int(NQ), float(dQ), int(Nw), float(dw)] - c1 = self.getPropertyValue('Coeff1') - c2 = self.getPropertyValue('Coeff2') - c3 = self.getPropertyValue('Coeff3') - c4 = self.getPropertyValue('Coeff4') - c5 = self.getPropertyValue('Coeff5') - coeff = [float(c1), float(c2), float(c3), float(c4), float(c5)] - kr1 = 1 + NQ = self.getPropertyValue('NQ') + dQ = self.getPropertyValue('dQ') + Nw = self.getPropertyValue('NW') + dw = self.getPropertyValue('dW') #in microeV + grid = [int(NQ), float(dQ), int(Nw), float(dw)] + c1 = self.getPropertyValue('Coeff1') + c2 = self.getPropertyValue('Coeff2') + c3 = self.getPropertyValue('Coeff3') + c4 = self.getPropertyValue('Coeff4') + c5 = self.getPropertyValue('Coeff5') + coeff = [float(c1), float(c2), float(c3), float(c4), float(c5)] + kr1 = 1 - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value - Main.MuscatFuncStart(sname,geom,neut,beam,sam,grid,disp,coeff,kr1,verbOp,plotOp,saveOp) + verbOp = self.getProperty('Verbose').value + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value + Main.MuscatFuncStart(sname,geom,neut,beam,sam,grid,disp,coeff,kr1,verbOp,plotOp,saveOp) AlgorithmFactory.subscribe(MuscatFunc) # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py index fb07bc838bd3..c0d0e329f1fa 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py @@ -14,7 +14,7 @@ def name(self): return "NormaliseByThickness" def summary(self): - return "Normalise detector counts by the sample thickness." + return "Normalise detector counts by the sample thickness." def PyInit(self): self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py index 08b2797acd0e..9ce72199366f 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py @@ -149,7 +149,7 @@ def category(self): return 'Diffraction;PythonAlgorithms' def summary(self): - return "This Python algorithm performs the operations necessary for the reduction of diffraction data from the Osiris instrument at ISIS \ + return "This Python algorithm performs the operations necessary for the reduction of diffraction data from the Osiris instrument at ISIS \ into dSpacing, by correcting for the monitor and linking the various d-ranges together." def PyInit(self): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py index 06c3482b634a..20678332d280 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py @@ -7,35 +7,35 @@ class QLines(PythonAlgorithm): def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" + return "Workflow\\MIDAS;PythonAlgorithms" def summary(self): - return "The program estimates the quasielastic components of each of the groups of spectra and requires the resolution file (.RES file) and optionally the normalisation file created by ResNorm." + return "The program estimates the quasielastic components of each of the groups of spectra and requires the resolution file (.RES file) and optionally the normalisation file created by ResNorm." def PyInit(self): - self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) 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='Program',defaultValue='QL',validator=StringListValidator(['QL','QSe']), doc='Name of program to run') - self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') - self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') - self.declareProperty(name='ResType',defaultValue='Res',validator=StringListValidator(['Res','Data']), doc='Format of Resolution file') - self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') - self.declareProperty(name='ResNorm',defaultValue=False, doc='Use ResNorm output file') - self.declareProperty(name='ResNormInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of ResNorm input - File (_red.nxs) or Workspace') - self.declareProperty(name='ResNormNumber',defaultValue='', doc='ResNorm run number') - self.declareProperty(name='BackgroundOption',defaultValue='Sloping',validator=StringListValidator(['Sloping','Flat','Zero']), doc='Form of background to fit') - self.declareProperty(name='ElasticOption',defaultValue=True, doc='Include elastic peak in fit') - self.declareProperty(name='FixWidth',defaultValue=False, doc='Fix one of the widths') - self.declareProperty(name='WidthFile', defaultValue='', doc='Name of file containing fixed width values') - 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='SamBinning', defaultValue=1, doc='Binning value (integer) for sample. Default=1') - self.declareProperty(name='ResBinning', defaultValue=1, doc='Binning value (integer) for resolution - QLd only. Default=1') - self.declareProperty(name='Sequence',defaultValue=True, doc='Switch Sequence Off/On') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','ProbBeta','Intensity','FwHm','Fit','All']), doc='Plot options') - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') + self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) 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='Program',defaultValue='QL',validator=StringListValidator(['QL','QSe']), doc='Name of program to run') + self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') + self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') + self.declareProperty(name='ResType',defaultValue='Res',validator=StringListValidator(['Res','Data']), doc='Format of Resolution file') + self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') + self.declareProperty(name='ResNorm',defaultValue=False, doc='Use ResNorm output file') + self.declareProperty(name='ResNormInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of ResNorm input - File (_red.nxs) or Workspace') + self.declareProperty(name='ResNormNumber',defaultValue='', doc='ResNorm run number') + self.declareProperty(name='BackgroundOption',defaultValue='Sloping',validator=StringListValidator(['Sloping','Flat','Zero']), doc='Form of background to fit') + self.declareProperty(name='ElasticOption',defaultValue=True, doc='Include elastic peak in fit') + self.declareProperty(name='FixWidth',defaultValue=False, doc='Fix one of the widths') + self.declareProperty(name='WidthFile', defaultValue='', doc='Name of file containing fixed width values') + 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='SamBinning', defaultValue=1, doc='Binning value (integer) for sample. Default=1') + self.declareProperty(name='ResBinning', defaultValue=1, doc='Binning value (integer) for resolution - QLd only. Default=1') + self.declareProperty(name='Sequence',defaultValue=True, doc='Switch Sequence Off/On') + self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','ProbBeta','Intensity','FwHm','Fit','All']), doc='Plot options') + self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') + self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') def PyExec(self): from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform @@ -43,60 +43,60 @@ def PyExec(self): if is_supported_f2py_platform(): import IndirectBayes as Main - run_f2py_compatibility_test() - - self.log().information('QLines input') - inType = self.getPropertyValue('InputType') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - prog = self.getPropertyValue('Program') - sam = self.getPropertyValue('SamNumber') - rinType = self.getPropertyValue('ResInputType') - rtype = self.getPropertyValue('ResType') - res = self.getPropertyValue('ResNumber') - elastic = self.getProperty('ElasticOption').value - bgd = self.getPropertyValue('BackgroundOption') - width = self.getProperty('FixWidth').value - wfile = self.getPropertyValue('WidthFile') - rsnormType = self.getPropertyValue('ResNormInputType') - resnorm = self.getProperty('ResNorm').value - resn = self.getPropertyValue('ResNormNumber') - emin = self.getPropertyValue('EnergyMin') - emax = self.getPropertyValue('EnergyMax') - nbin = self.getPropertyValue('SamBinning') - nrbin = self.getPropertyValue('ResBinning') - nbins = [nbin, nrbin] - - if rtype == 'Res': + run_f2py_compatibility_test() + + self.log().information('QLines input') + inType = self.getPropertyValue('InputType') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + prog = self.getPropertyValue('Program') + sam = self.getPropertyValue('SamNumber') + rinType = self.getPropertyValue('ResInputType') + rtype = self.getPropertyValue('ResType') + res = self.getPropertyValue('ResNumber') + elastic = self.getProperty('ElasticOption').value + bgd = self.getPropertyValue('BackgroundOption') + width = self.getProperty('FixWidth').value + wfile = self.getPropertyValue('WidthFile') + rsnormType = self.getPropertyValue('ResNormInputType') + resnorm = self.getProperty('ResNorm').value + resn = self.getPropertyValue('ResNormNumber') + emin = self.getPropertyValue('EnergyMin') + emax = self.getPropertyValue('EnergyMax') + nbin = self.getPropertyValue('SamBinning') + nrbin = self.getPropertyValue('ResBinning') + nbins = [nbin, nrbin] + + if rtype == 'Res': rext = 'res' - if rtype == 'Data': + if rtype == 'Data': rext = 'red' - sname = prefix+sam+'_'+ana + '_red' - rname = prefix+res+'_'+ana + '_' + rext - rsname = prefix+resn+'_'+ana + '_ResNorm_Paras' - erange = [float(emin), float(emax)] - - fitOp = [elastic, bgd, width, resnorm] - loopOp = self.getProperty('Sequence').value - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value - - workdir = config['defaultsave.directory'] - if inType == 'File': + sname = prefix+sam+'_'+ana + '_red' + rname = prefix+res+'_'+ana + '_' + rext + rsname = prefix+resn+'_'+ana + '_ResNorm_Paras' + erange = [float(emin), float(emax)] + + fitOp = [elastic, bgd, width, resnorm] + loopOp = self.getProperty('Sequence').value + verbOp = self.getProperty('Verbose').value + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value + + workdir = config['defaultsave.directory'] + if inType == 'File': spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file LoadNexusProcessed(Filename=spath, OutputWorkspace=sname) Smessage = 'Sample from File : '+spath - else: + else: Smessage = 'Sample from Workspace : '+sname - if rinType == 'File': + if rinType == 'File': rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) Rmessage = 'Resolution from File : '+rpath - else: + else: Rmessage = 'Resolution from Workspace : '+rname - if resnorm: + if resnorm: if rsnormType == 'File': rpath = os.path.join(workdir, rsname+'.nxs') # path name for res nxs file LoadNexusProcessed(Filename=rpath, OutputWorkspace=rsname) @@ -104,12 +104,12 @@ def PyExec(self): else: Rmessage = 'ResNorm from Workspace : '+rsname - if verbOp: + if verbOp: logger.notice(Smessage) logger.notice(Rmessage) - rsname = rsname[:-6] + rsname = rsname[:-6] - Main.QLRun(prog,sname,rname,rsname,erange,nbins,fitOp,wfile,loopOp,verbOp,plotOp,saveOp) + Main.QLRun(prog,sname,rname,rsname,erange,nbins,fitOp,wfile,loopOp,verbOp,plotOp,saveOp) AlgorithmFactory.subscribe(QLines) # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py index b4c3a0d27b3b..b0f4decb1ded 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py @@ -7,104 +7,104 @@ class Quest(PythonAlgorithm): def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" + return "Workflow\\MIDAS;PythonAlgorithms" def summary(self): - return "This is a variation of the stretched exponential option of Quasi." + return "This is a variation of the stretched exponential option of Quasi." def PyInit(self): - self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) 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(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') - self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') - self.declareProperty(name='ResNormInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of ResNorm input - File (_red.nxs) or Workspace') - self.declareProperty(name='ResNormNumber',defaultValue='',validator=StringMandatoryValidator(), doc='ResNorm run number') - self.declareProperty(name='ElasticOption',defaultValue=True, doc='Include elastic peak in fit') - self.declareProperty(name='BackgroundOption',defaultValue='Sloping',validator=StringListValidator(['Sloping','Flat','Zero']), doc='Form of background to fit') - 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='SamBinning', defaultValue=1, doc='Binning value(integer) for sample. Default=1') - self.declareProperty(name='NumberSigma', defaultValue=50, doc='Number of sigma values. Default=50') - self.declareProperty(name='NumberBeta', defaultValue=30, doc='Number of beta values. Default=30') - self.declareProperty(name='Sequence',defaultValue=True, doc='Switch Sequence Off/On') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Sigma','Beta','All']), doc='Plot options') - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') + self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) 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(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') + self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') + self.declareProperty(name='ResNormInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of ResNorm input - File (_red.nxs) or Workspace') + self.declareProperty(name='ResNormNumber',defaultValue='',validator=StringMandatoryValidator(), doc='ResNorm run number') + self.declareProperty(name='ElasticOption',defaultValue=True, doc='Include elastic peak in fit') + self.declareProperty(name='BackgroundOption',defaultValue='Sloping',validator=StringListValidator(['Sloping','Flat','Zero']), doc='Form of background to fit') + 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='SamBinning', defaultValue=1, doc='Binning value(integer) for sample. Default=1') + self.declareProperty(name='NumberSigma', defaultValue=50, doc='Number of sigma values. Default=50') + self.declareProperty(name='NumberBeta', defaultValue=30, doc='Number of beta values. Default=30') + self.declareProperty(name='Sequence',defaultValue=True, doc='Switch Sequence Off/On') + self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Sigma','Beta','All']), doc='Plot options') + self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') + self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') def PyExec(self): - from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform + from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform - if is_supported_f2py_platform(): - import IndirectBayes as Main + if is_supported_f2py_platform(): + import IndirectBayes as Main - run_f2py_compatibility_test() + run_f2py_compatibility_test() - self.log().information('Quest input') - inType = self.getPropertyValue('InputType') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - sam = self.getPropertyValue('SamNumber') - rinType = self.getPropertyValue('ResInputType') - res = self.getPropertyValue('ResNumber') - rsnormType = self.getPropertyValue('ResNormInputType') - rsnormNum = self.getPropertyValue('ResNormNumber') - elastic = self.getProperty('ElasticOption').value - bgd = self.getPropertyValue('BackgroundOption') - emin = self.getPropertyValue('EnergyMin') - emax = self.getPropertyValue('EnergyMax') - nbin = self.getPropertyValue('SamBinning') - nbins = [nbin, 1] - nbet = self.getPropertyValue('NumberBeta') - nsig = self.getPropertyValue('NumberSigma') - nbs = [nbet, nsig] + self.log().information('Quest input') + inType = self.getPropertyValue('InputType') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + sam = self.getPropertyValue('SamNumber') + rinType = self.getPropertyValue('ResInputType') + res = self.getPropertyValue('ResNumber') + rsnormType = self.getPropertyValue('ResNormInputType') + rsnormNum = self.getPropertyValue('ResNormNumber') + elastic = self.getProperty('ElasticOption').value + bgd = self.getPropertyValue('BackgroundOption') + emin = self.getPropertyValue('EnergyMin') + emax = self.getPropertyValue('EnergyMax') + nbin = self.getPropertyValue('SamBinning') + nbins = [nbin, 1] + nbet = self.getPropertyValue('NumberBeta') + nsig = self.getPropertyValue('NumberSigma') + nbs = [nbet, nsig] - sname = prefix+sam+'_'+ana + '_red' - rname = prefix+res+'_'+ana + '_res' - rsname = prefix+rsnormNum+'_'+ana+ '_ResNorm_Paras' - erange = [float(emin), float(emax)] - if elastic: - o_el = 1 - else: - o_el = 0 - if bgd == 'Sloping': - o_bgd = 2 - if bgd == 'Flat': - o_bgd = 1 - if bgd == 'Zero': - o_bgd = 0 - fitOp = [o_el, o_bgd, 0, 0] - loopOp = self.getProperty('Sequence').value - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value + sname = prefix+sam+'_'+ana + '_red' + rname = prefix+res+'_'+ana + '_res' + rsname = prefix+rsnormNum+'_'+ana+ '_ResNorm_Paras' + erange = [float(emin), float(emax)] + if elastic: + o_el = 1 + else: + o_el = 0 + if bgd == 'Sloping': + o_bgd = 2 + if bgd == 'Flat': + o_bgd = 1 + if bgd == 'Zero': + o_bgd = 0 + fitOp = [o_el, o_bgd, 0, 0] + loopOp = self.getProperty('Sequence').value + verbOp = self.getProperty('Verbose').value + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value - workdir = config['defaultsave.directory'] - if inType == 'File': - spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file - LoadNexusProcessed(Filename=spath, OutputWorkspace=sname) - Smessage = 'Sample from File : '+spath - else: - Smessage = 'Sample from Workspace : '+sname + workdir = config['defaultsave.directory'] + if inType == 'File': + spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file + LoadNexusProcessed(Filename=spath, OutputWorkspace=sname) + Smessage = 'Sample from File : '+spath + else: + Smessage = 'Sample from Workspace : '+sname - if rinType == 'File': - rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file - LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) - Rmessage = 'Resolution from File : '+rpath - else: - Rmessage = 'Resolution from Workspace : '+rname + if rinType == 'File': + rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file + LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) + Rmessage = 'Resolution from File : '+rpath + else: + Rmessage = 'Resolution from Workspace : '+rname - if rsnormType == 'File': - rpath = os.path.join(workdir, rsname+'.nxs') # path name for res nxs file - LoadNexusProcessed(Filename=rpath, OutputWorkspace=rsname) - Rmessage = 'ResNorm from File : '+rpath - else: - Rmessage = 'ResNorm from Workspace : '+rsname + if rsnormType == 'File': + rpath = os.path.join(workdir, rsname+'.nxs') # path name for res nxs file + LoadNexusProcessed(Filename=rpath, OutputWorkspace=rsname) + Rmessage = 'ResNorm from File : '+rpath + else: + Rmessage = 'ResNorm from Workspace : '+rsname - if verbOp: - logger.notice(Smessage) - logger.notice(Rmessage) - Main.QuestRun(sname,rname,rsname,nbs,erange,nbins,fitOp,loopOp,verbOp,plotOp,saveOp) + if verbOp: + logger.notice(Smessage) + logger.notice(Rmessage) + Main.QuestRun(sname,rname,rsname,nbs,erange,nbins,fitOp,loopOp,verbOp,plotOp,saveOp) AlgorithmFactory.subscribe(Quest) # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py index d2aa68669a98..9b1946133b5d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py @@ -103,9 +103,9 @@ def stitch_data(self, input_file, output_dir, q_min, q_step): ws_list = AnalysisDataService.getObjectNames() for item in ws_list: if item.endswith('ts'): - (_name,_ts) = item.split('_#') - _list_name.append(item) - _list_ts.append(_ts) + (_name,_ts) = item.split('_#') + _list_name.append(item) + _list_ts.append(_ts) _name_ts = zip(_list_ts, _list_name) _name_ts.sort() @@ -147,14 +147,14 @@ def weightedMean(data_array, error_array): sz = len(data_array) # calculate the numerator of mean - dataNum = 0; + dataNum = 0 for i in range(sz): if not (data_array[i] == 0): tmpFactor = float(data_array[i]) / float((pow(error_array[i],2))) dataNum += tmpFactor # calculate denominator - dataDen = 0; + dataDen = 0 for i in range(sz): if not (error_array[i] == 0): tmpFactor = 1./float((pow(error_array[i],2))) @@ -212,7 +212,7 @@ def _average_y_of_same_x_(q_min, q_step, q_max=2): data_e_i = mtd[scaled_ws_list[i]+'_histo'].dataE(0) for j in range(len(data_y_i)): if data_y[j]>0 and data_y_i[j]>0: - [data_y[j], data_e[j]] = weightedMean([data_y[j], data_y_i[j]], [data_e[j], data_e_i[j]]); + [data_y[j], data_e[j]] = weightedMean([data_y[j], data_y_i[j]], [data_e[j], data_e_i[j]]) elif (data_y[j] == 0) and (data_y_i[j]>0): data_y[j] = data_y_i[j] data_e[j] = data_e_i[j] diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py index 7f4a1e088aeb..4dbd424925ed 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py @@ -69,7 +69,7 @@ def PyExec(self): res_factor += math.pow(k*pixel_size_x/sample_detector_distance, 2)/12.0 for i in range(len(input_ws.readX(0))): - input_ws.dataDx(0)[i] = math.sqrt(res_factor+math.pow((input_ws.readX(0)[i]*d_wvl), 2)/6.0) + input_ws.dataDx(0)[i] = math.sqrt(res_factor+math.pow((input_ws.readX(0)[i]*d_wvl), 2)/6.0) else: raise RuntimeError, "ReactorSANSResolution could not find all the run parameters needed to compute the resolution." diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py index c7dd0825540e..217086f0f431 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py @@ -6,68 +6,68 @@ class ResNorm(PythonAlgorithm): - def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" + def category(self): + return "Workflow\\MIDAS;PythonAlgorithms" - def summary(self): - return "This algorithm creates a group 'normalisation' file by taking a resolution file and fitting it to all the groups in the resolution (vanadium) data file which has the same grouping as the sample data of interest." + def summary(self): + return "This algorithm creates a group 'normalisation' file by taking a resolution file and fitting it to all the groups in the resolution (vanadium) data file which has the same grouping as the sample data of interest." - def PyInit(self): - self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) 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='VanNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') - self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') - self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') - self.declareProperty(name='EnergyMin', defaultValue=-0.2, doc='Minimum energy for fit. Default=-0.2') - self.declareProperty(name='EnergyMax', defaultValue=0.2, doc='Maximum energy for fit. Default=0.2') - self.declareProperty(name='VanBinning', defaultValue=1, doc='Binning value (integer) for sample. Default=1') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Intensity','Stretch','Fit','All']), doc='Plot options') - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') + def PyInit(self): + self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) 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='VanNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') + self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') + self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') + self.declareProperty(name='EnergyMin', defaultValue=-0.2, doc='Minimum energy for fit. Default=-0.2') + self.declareProperty(name='EnergyMax', defaultValue=0.2, doc='Maximum energy for fit. Default=0.2') + self.declareProperty(name='VanBinning', defaultValue=1, doc='Binning value (integer) for sample. Default=1') + self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Intensity','Stretch','Fit','All']), doc='Plot options') + self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') + self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') - def PyExec(self): - from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform + def PyExec(self): + from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform - if is_supported_f2py_platform(): + if is_supported_f2py_platform(): import IndirectBayes as Main - run_f2py_compatibility_test() + run_f2py_compatibility_test() - self.log().information('ResNorm input') - inType = self.getPropertyValue('InputType') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - van = self.getPropertyValue('VanNumber') - rinType = self.getPropertyValue('ResInputType') - res = self.getPropertyValue('ResNumber') - emin = self.getPropertyValue('EnergyMin') - emax = self.getPropertyValue('EnergyMax') - nbin = self.getPropertyValue('VanBinning') + self.log().information('ResNorm input') + inType = self.getPropertyValue('InputType') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + van = self.getPropertyValue('VanNumber') + rinType = self.getPropertyValue('ResInputType') + res = self.getPropertyValue('ResNumber') + emin = self.getPropertyValue('EnergyMin') + emax = self.getPropertyValue('EnergyMax') + nbin = self.getPropertyValue('VanBinning') - vname = prefix+van+'_'+ana+ '_red' - rname = prefix+res+'_'+ana+ '_res' - erange = [float(emin), float(emax)] - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value + vname = prefix+van+'_'+ana+ '_red' + rname = prefix+res+'_'+ana+ '_res' + erange = [float(emin), float(emax)] + verbOp = self.getProperty('Verbose').value + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value - workdir = config['defaultsave.directory'] - if inType == 'File': - vpath = os.path.join(workdir, vname+'.nxs') # path name for van nxs file - LoadNexusProcessed(Filename=vpath, OutputWorkspace=vname) - Vmessage = 'Vanadium from File : '+vpath - else: - Vmessage = 'Vanadium from Workspace : '+vname - if rinType == 'File': - rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file - LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) - Rmessage = 'Resolution from File : '+rpath - else: - Rmessage = 'Resolution from Workspace : '+rname - if verbOp: - logger.notice(Vmessage) - logger.notice(Rmessage) - Main.ResNormRun(vname,rname,erange,nbin,verbOp,plotOp,saveOp) + workdir = config['defaultsave.directory'] + if inType == 'File': + vpath = os.path.join(workdir, vname+'.nxs') # path name for van nxs file + LoadNexusProcessed(Filename=vpath, OutputWorkspace=vname) + Vmessage = 'Vanadium from File : '+vpath + else: + Vmessage = 'Vanadium from Workspace : '+vname + if rinType == 'File': + rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file + LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) + Rmessage = 'Resolution from File : '+rpath + else: + Rmessage = 'Resolution from Workspace : '+rname + if verbOp: + logger.notice(Vmessage) + logger.notice(Rmessage) + Main.ResNormRun(vname,rname,erange,nbin,verbOp,plotOp,saveOp) AlgorithmFactory.subscribe(ResNorm) # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py index 2642c5b5dbf7..295813c96ccb 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py @@ -35,7 +35,7 @@ def PyInit(self): self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", direction = Direction.Output), "I(q) workspace") - + self.declareProperty("NumberOfWedges", 2, "Number of wedges to calculate") self.declareProperty("WedgeAngle", 30.0, "Angular opening of each wedge, in degrees") self.declareProperty("WedgeOffset", 0.0, "Angular offset for the wedges, in degrees") @@ -166,7 +166,7 @@ def PyExec(self): alg.setProperty("InfinityError", 0.0) alg.execute() wedge_i = alg.getProperty("OutputWorkspace").value - + if compute_resolution: alg = AlgorithmManager.create("ReactorSANSResolution") alg.initialize() @@ -238,7 +238,7 @@ def _get_binning(self, workspace, wavelength_min, wavelength_max): if f_step-n_step>10e-10: qmax = math.pow(10.0, math.log10(qmin)+qstep*n_step) return qmin, -(math.pow(10.0,qstep)-1.0), qmax - + def _get_aligned_binning(self, qmin, qmax): npts = self.getProperty("NumberOfBins").value @@ -246,18 +246,18 @@ def _get_aligned_binning(self, qmin, qmax): x_max = math.pow(10,math.ceil(npts*math.log10(qmax))/npts) b = 1.0/npts nsteps = int(1+math.ceil(npts*math.log10(x_max/x_min))) - + binning = str(x_min) x_bound = x_min - ( x_min*math.pow(10,b) - x_min )/2.0 binning2 = str(x_bound) - + x = x_min for i in range(nsteps): x_bound = 2*x-x_bound x *= math.pow(10,b) binning += ",%g,%g" % (x,x) binning2 += ",%g,%g" % (x_bound,x_bound) - + return binning2 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py index f6940f4489e9..fc38ab31a45e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py @@ -402,17 +402,17 @@ def _save_output(self, iq_output, iqxy_output, output_dir, property_manager): elif len(process_file)>0 and process_file.lower().find("none") != 0: Logger("SANSReduction").error("Could not read process info file %s\n" % process_file) if property_manager.existsProperty("SetupAlgorithm"): - if property_manager.existsProperty('InstrumentName'): - instrument_name = property_manager.getProperty('InstrumentName').value - else: - instrument_name = 'EQSANS' - setup_info = property_manager.getProperty("SetupAlgorithm").value - proc_xml += "\n\n" - proc_xml += " %s\n" % instrument_name - proc_xml += " %s\n" % setup_info - filename = self.getProperty("Filename").value - proc_xml += " %s\n" % filename - proc_xml += "\n" + if property_manager.existsProperty('InstrumentName'): + instrument_name = property_manager.getProperty('InstrumentName').value + else: + instrument_name = 'EQSANS' + setup_info = property_manager.getProperty("SetupAlgorithm").value + proc_xml += "\n\n" + proc_xml += " %s\n" % instrument_name + proc_xml += " %s\n" % setup_info + filename = self.getProperty("Filename").value + proc_xml += " %s\n" % filename + proc_xml += "\n" filename = os.path.join(output_dir, iq_output+'.txt') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py index ce4a8202ae0c..21cfd657d717 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py @@ -269,7 +269,7 @@ def apply_transmission(self, workspace, trans_workspace): "OutputWorkspace": '__trans_rebin', "PreserveEvents": False }) - rebinned_ws = alg.getProperty("OutputWorkspace").value; + rebinned_ws = alg.getProperty("OutputWorkspace").value # Apply angle-dependent transmission correction using the zero-angle transmission theta_dependent = self.getProperty("ThetaDependent").value diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py index d52ec45d214f..4c0402409f89 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py @@ -209,7 +209,7 @@ def isNexusTakeAfterRefDate(self, nexus_date): This function parses the output.date and returns true if this date is after the ref date ''' nexus_date_acquisition = nexus_date.split('T')[0] - + if nexus_date_acquisition > self.ref_date: return True else: @@ -238,7 +238,7 @@ def _calculateFinalYAxis(self, bNumerator=True): nexus_file_numerator = file print '----> loading nexus file: ' + nexus_file_numerator EventDataWks = LoadEventNexus(Filename=nexus_file_numerator) - + self.is_nexus_detector_rotated_flag = self.isNexusTakeAfterRefDate(EventDataWks.getRun().getProperty('run_start').value) if self.is_nexus_detector_rotated_flag: @@ -431,7 +431,7 @@ def _createIntegratedWorkspace(self, y_axis[y, :] += InputWorkspace.readY(index)[:] y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) * (InputWorkspace.readE(index)[:])) - + else: for x in range(304): for y in y_range: @@ -566,13 +566,13 @@ def _removeBackground(self, peak_array = zeros(nbr_tof) peak_array_error = zeros(nbr_tof) - bMinBack = False; - bMaxBack = False; + bMinBack = False + bMaxBack = False - min_back = 0; - min_back_error = 0; - max_back = 0; - max_back_error = 0; + min_back = 0 + min_back_error = 0 + max_back = 0 + max_back_error = 0 for t in (range(nbr_tof-1)): @@ -616,8 +616,8 @@ def _removeBackground(self, [final_value, final_error] = self.sumWithError(new_tmp_peak, new_tmp_peak_error) - peak_array[t] = final_value; - peak_array_error[t] = final_error; + peak_array[t] = final_value + peak_array_error[t] = final_error # make new workspace @@ -1247,7 +1247,7 @@ def calculate(string_runs=None, """ - list_attenuator = None; + list_attenuator = None #use default string files if not provided if (string_runs is None): @@ -1284,7 +1284,7 @@ def calculate(string_runs=None, if (list_attenuator is None): # list_attenuator = [0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4] - list_attenuator = [0, 1, 1, 1, 1, 1]; + list_attenuator = [0, 1, 1, 1, 1, 1] if (list_peak_back is None): list_peak_back = zeros((len(list_runs), 4)) #[peak_min, peak_max, back_min, back_max] diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py index b53bc6465092..ec44cf7b469a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py @@ -53,8 +53,8 @@ def functionDeriv1D(self, xvals, jacobian): for x in xvals: s = math.sin(x*length)/(x*length) h = (1.0-s)/tau - jacobian.set(i,0,-h/tau); - jacobian.set(i,1,(math.cos(x*length)-s)/(length*tau)); + jacobian.set(i,0,-h/tau) + jacobian.set(i,1,(math.cos(x*length)-s)/(length*tau)) i += 1 # Required to have Mantid recognise the new function diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py index 00b807febc9a..5f5028b06537 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py @@ -31,139 +31,139 @@ class DSFinterp1DFit(IFunction1D): - def category(self): - return 'QuasiElastic' + def category(self): + return 'QuasiElastic' - def init(self): - '''Declare parameters and attributes that participate in the fitting''' + def init(self): + '''Declare parameters and attributes that participate in the fitting''' # Active fitting parameters - self.declareParameter('Intensity', 1.0, 'Intensity') - self.declareParameter('TargetParameter', 1.0, 'Target value of the structure factor parameter') - - self.declareAttribute('InputWorkspaces','') - self.declareAttribute('LoadErrors', False) - self.declareAttribute('WorkspaceIndex', 0) - self.declareAttribute('ParameterValues', '') - self.declareAttribute('LocalRegression', True) - self.declareAttribute('RegressionType', 'quadratic') - self.declareAttribute('RegressionWindow', 6) + self.declareParameter('Intensity', 1.0, 'Intensity') + self.declareParameter('TargetParameter', 1.0, 'Target value of the structure factor parameter') + + self.declareAttribute('InputWorkspaces','') + self.declareAttribute('LoadErrors', False) + self.declareAttribute('WorkspaceIndex', 0) + self.declareAttribute('ParameterValues', '') + self.declareAttribute('LocalRegression', True) + self.declareAttribute('RegressionType', 'quadratic') + self.declareAttribute('RegressionWindow', 6) # "private" attributes associated to the declare function attributes - self._InputWorkspaces = None - self._LoadErrors = None - self._WorkspaceIndex = None - self._ParameterValues = None - self._fmin = None - self._fmax = None - self._LocalRegression = None - self._RegressionType = None - self._RegressionTypes = set(['linear','quadratic']) #valid syntaxfor python >= 2.6 - self._RegressionWindow = None - self._minWindow = { 'linear':3, 'quadratic':4 } + self._InputWorkspaces = None + self._LoadErrors = None + self._WorkspaceIndex = None + self._ParameterValues = None + self._fmin = None + self._fmax = None + self._LocalRegression = None + self._RegressionType = None + self._RegressionTypes = set(['linear','quadratic']) #valid syntaxfor python >= 2.6 + self._RegressionWindow = None + self._minWindow = { 'linear':3, 'quadratic':4 } # channelgroup to interpolate values - self._channelgroup = None - self._xvalues = None #energies of the channels - - def setAttributeValue(self, name, value): - if name == "InputWorkspaces": - self._InputWorkspaces = value.split() - if ',' in value: - self._InputWorkspaces = [x.strip() for x in value.split(',')] - elif name == 'LoadErrors': - self._LoadErrors= bool(value) - elif name == 'WorkspaceIndex': - self._WorkspaceIndex = int(value) - elif name == 'ParameterValues': - self._ParameterValues = [ float(f) for f in value.split() ] - self._fmin = min(self._ParameterValues) - self._fmax = max(self._ParameterValues) - elif name == 'LocalRegression': - self._LocalRegression = bool(value) - elif name == 'RegressionType': - self._RegressionType = value.lower() - elif name == 'RegressionWindow': - self._RegressionWindow = value - - def validateParams(self): - '''Check parameters within expected range''' - intensity = self.getParameterValue('Intensity') - if intensity <=0: - message = 'Parameter Intensity in DSFinterp1DFit must be positive. Got {0} instead'.format(intensity) - logger.error(message) - return None - f = self.getParameterValue('TargetParameter') - if f < self._fmin or f > self._fmax: - message = 'TargetParameter {0} is out of bounds [{1}, {2}]. Applying penalty...'.format(f, self._fmin, self._fmax) - logger.error(message) - return None - return {'Intensity':intensity, 'TargetParameter':f} - - - def function1D(self, xvals): - ''' Fit using the interpolated structure factor ''' - p=self.validateParams() - if not p: - return numpy.zeros(len(xvals), dtype=float) # return zeros if parameters not valid + self._channelgroup = None + self._xvalues = None #energies of the channels + + def setAttributeValue(self, name, value): + if name == "InputWorkspaces": + self._InputWorkspaces = value.split() + if ',' in value: + self._InputWorkspaces = [x.strip() for x in value.split(',')] + elif name == 'LoadErrors': + self._LoadErrors= bool(value) + elif name == 'WorkspaceIndex': + self._WorkspaceIndex = int(value) + elif name == 'ParameterValues': + self._ParameterValues = [ float(f) for f in value.split() ] + self._fmin = min(self._ParameterValues) + self._fmax = max(self._ParameterValues) + elif name == 'LocalRegression': + self._LocalRegression = bool(value) + elif name == 'RegressionType': + self._RegressionType = value.lower() + elif name == 'RegressionWindow': + self._RegressionWindow = value + + def validateParams(self): + '''Check parameters within expected range''' + intensity = self.getParameterValue('Intensity') + if intensity <=0: + message = 'Parameter Intensity in DSFinterp1DFit must be positive. Got {0} instead'.format(intensity) + logger.error(message) + return None + f = self.getParameterValue('TargetParameter') + if f < self._fmin or f > self._fmax: + message = 'TargetParameter {0} is out of bounds [{1}, {2}]. Applying penalty...'.format(f, self._fmin, self._fmax) + logger.error(message) + return None + return {'Intensity':intensity, 'TargetParameter':f} + + + def function1D(self, xvals): + ''' Fit using the interpolated structure factor ''' + p=self.validateParams() + if not p: + return numpy.zeros(len(xvals), dtype=float) # return zeros if parameters not valid # The first time the function is called requires initialization of the interpolator - if self._channelgroup == None: + if self._channelgroup == None: # Check consistency of the input # check InputWorkspaces have at least the workspace index - for w in self._InputWorkspaces: - if mtd[w].getNumberHistograms() <= self._WorkspaceIndex: - message = 'Numer of histograms in Workspace {0} does not allow for workspace index {1}'.format(w,self._WorkspaceIndex) - logger.error(message) - raise IndexError(message) + for w in self._InputWorkspaces: + if mtd[w].getNumberHistograms() <= self._WorkspaceIndex: + message = 'Numer of histograms in Workspace {0} does not allow for workspace index {1}'.format(w,self._WorkspaceIndex) + logger.error(message) + raise IndexError(message) # check number of input workspaces and parameters is the same - if len(self._ParameterValues) != len(self._InputWorkspaces): - message = 'Number of InputWorkspaces and ParameterValues should be the same. Found {0} and {1}, respectively'.format(len(self._InputWorkspaces), len(self._ParameterValues)) - logger.error(message) - raise ValueError(message) + if len(self._ParameterValues) != len(self._InputWorkspaces): + message = 'Number of InputWorkspaces and ParameterValues should be the same. Found {0} and {1}, respectively'.format(len(self._InputWorkspaces), len(self._ParameterValues)) + logger.error(message) + raise ValueError(message) # check the regression type is valid - if self._RegressionType not in self._RegressionTypes: - message = 'Regression type {0} not implemented. choose one of {1}'.format(self._RegressionType, ', '.join(self._RegressionTypes)) - logger.error(message) - raise NotImplementedError(message) + if self._RegressionType not in self._RegressionTypes: + message = 'Regression type {0} not implemented. choose one of {1}'.format(self._RegressionType, ', '.join(self._RegressionTypes)) + logger.error(message) + raise NotImplementedError(message) # check the regression window is appropriate for the regression type selected - if self._RegressionWindow < self._minWindow[self._RegressionType]: - message = 'RegressionWindow must be equal or bigger than {0} for regression type {1}'.format(self._minWindow[self._RegressionType], self._RegressionType) - logger.error(message) - raise ValueError(message) + if self._RegressionWindow < self._minWindow[self._RegressionType]: + message = 'RegressionWindow must be equal or bigger than {0} for regression type {1}'.format(self._minWindow[self._RegressionType], self._RegressionType) + logger.error(message) + raise ValueError(message) # Initialize the energies of the channels with the first of the input workspaces - self._xvalues = numpy.copy( mtd[ self._InputWorkspaces[0] ].dataX(self._WorkspaceIndex) ) - if len(self._xvalues) == 1+ len( mtd[ self._InputWorkspaces[0] ].dataY(self._WorkspaceIndex) ): - self._xvalues = (self._xvalues[1:]+self._xvalues[:-1])/2.0 # Deal with histogram data + self._xvalues = numpy.copy( mtd[ self._InputWorkspaces[0] ].dataX(self._WorkspaceIndex) ) + if len(self._xvalues) == 1+ len( mtd[ self._InputWorkspaces[0] ].dataY(self._WorkspaceIndex) ): + self._xvalues = (self._xvalues[1:]+self._xvalues[:-1])/2.0 # Deal with histogram data # Initialize the channel group - nf = len(self._ParameterValues) + nf = len(self._ParameterValues) # Load the InputWorkspaces into a group of dynamic structure factors - from dsfinterp.dsf import Dsf - from dsfinterp.dsfgroup import DsfGroup - dsfgroup = DsfGroup() - for idsf in range(nf): - dsf = Dsf() - dsf.SetIntensities( mtd[ self._InputWorkspaces[idsf] ].dataY(self._WorkspaceIndex) ) - dsf.errors = None # do not incorporate error data - if self._LoadErrors: - dsf.SetErrors(mtd[ self._InputWorkspaces[idsf] ].dataE(self._WorkspaceIndex)) - dsf.SetFvalue( self._ParameterValues[idsf] ) - dsfgroup.InsertDsf(dsf) + from dsfinterp.dsf import Dsf + from dsfinterp.dsfgroup import DsfGroup + dsfgroup = DsfGroup() + for idsf in range(nf): + dsf = Dsf() + dsf.SetIntensities( mtd[ self._InputWorkspaces[idsf] ].dataY(self._WorkspaceIndex) ) + dsf.errors = None # do not incorporate error data + if self._LoadErrors: + dsf.SetErrors(mtd[ self._InputWorkspaces[idsf] ].dataE(self._WorkspaceIndex)) + dsf.SetFvalue( self._ParameterValues[idsf] ) + dsfgroup.InsertDsf(dsf) # Create the interpolator - from dsfinterp.channelgroup import ChannelGroup - self._channelgroup = ChannelGroup() - self._channelgroup.InitFromDsfGroup(dsfgroup) - if self._LocalRegression: - self._channelgroup.InitializeInterpolator(running_regr_type=self._RegressionType, windowlength=self._RegressionWindow) - else: - self._channelgroup.InitializeInterpolator(windowlength=0) + from dsfinterp.channelgroup import ChannelGroup + self._channelgroup = ChannelGroup() + self._channelgroup.InitFromDsfGroup(dsfgroup) + if self._LocalRegression: + self._channelgroup.InitializeInterpolator(running_regr_type=self._RegressionType, windowlength=self._RegressionWindow) + else: + self._channelgroup.InitializeInterpolator(windowlength=0) # channel group has been initialized, so evaluate the interpolator - dsf = self._channelgroup(p['TargetParameter']) + dsf = self._channelgroup(p['TargetParameter']) # Linear interpolation between the energies of the channels and the xvalues we require # NOTE: interpolator evaluates to zero for any of the xvals outside of the domain defined by self._xvalues - intensities_interpolator = interp1d(self._xvalues, p['Intensity']*dsf.intensities, kind='linear') - return intensities_interpolator(xvals) # can we pass by reference? + intensities_interpolator = interp1d(self._xvalues, p['Intensity']*dsf.intensities, kind='linear') + return intensities_interpolator(xvals) # can we pass by reference? # Required to have Mantid recognize the new function try: - import dsfinterp - FunctionFactory.subscribe(DSFinterp1DFit) + import dsfinterp + FunctionFactory.subscribe(DSFinterp1DFit) except: - logger.debug('Failed to subscribe fit function DSFinterp1DFit; Python package dsfinterp may be missing (https://pypi.python.org/pypi/dsfinterp)') - pass + logger.debug('Failed to subscribe fit function DSFinterp1DFit; Python package dsfinterp may be missing (https://pypi.python.org/pypi/dsfinterp)') + pass diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py index 314e436eaadd..7286ee94c80f 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py @@ -53,8 +53,8 @@ def functionDeriv1D(self, xvals, jacobian): """ i = 0 for x in xvals: - jacobian.set(i,0,1); - jacobian.set(i,1,x); + jacobian.set(i,0,1) + jacobian.set(i,1,x) i += 1 # Required to have Mantid recognise the new function diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py index a24fe9fc4d2c..2564aacabb9c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py @@ -49,7 +49,7 @@ def functionLocal(self, xvals): height = self.getParameterValue("Height") # Can also be retrieve by index self.getParameterValue(0) peak_centre = self.getParameterValue("PeakCentre") sigma = self.getParameterValue("Sigma") - weight = math.pow(1./sigma,2); + weight = math.pow(1./sigma,2) # Here you can use the NTerms attr if required by # using self._nterms: see setAttributeValue below or @@ -68,10 +68,10 @@ def functionDerivLocal(self, xvals, jacobian): ip = The index of the parameter value whose partial derivative this corresponds to value = The value of the derivative """ - height = self.getParameterValue("Height"); - peak_centre = self.getParameterValue("PeakCentre"); + height = self.getParameterValue("Height") + peak_centre = self.getParameterValue("PeakCentre") sigma = self.getParameterValue("Sigma") - weight = math.pow(1./sigma,2); + weight = math.pow(1./sigma,2) # X index i = 0 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py index bc57736a6c8d..250651bd0a91 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py @@ -43,7 +43,7 @@ def function1D(self, xvals): def functionDeriv1D(self, xvals, jacobian): i = 0 for x in xvals: - jacobian.set(i,0,2.0*x); + jacobian.set(i,0,2.0*x) i += 1 # Required to have Mantid recognise the new function diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Guinier.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Guinier.py index 71916353ad6d..96cc08f561d0 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Guinier.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Guinier.py @@ -30,7 +30,7 @@ class Guinier(IFunction1D): """ Provide a Guinier fit function for SANS - + I(q) = I(0) exp(-R^2 q^2 / 3) """ def category(self): @@ -58,7 +58,7 @@ def functionDeriv1D(self, xvals, jacobian): rg = self.getParameterValue('Rg') for x in xvals: jacobian.set(i,0, math.exp(-(rg*x)**2/3.0 ) ) - jacobian.set(i,1, -self.getParameterValue("Scale") * math.exp(-(rg*x)**2/3.0 )*2.0/3.0*rg*x*x ); + jacobian.set(i,1, -self.getParameterValue("Scale") * math.exp(-(rg*x)**2/3.0 )*2.0/3.0*rg*x*x ) i += 1 # Required to have Mantid recognise the new function diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/GuinierPorod.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/GuinierPorod.py index d567938f179e..c8ee3122b5dc 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/GuinierPorod.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/GuinierPorod.py @@ -30,7 +30,7 @@ class GuinierPorod(IFunction1D): """ Provide a Guinier-Porod model for SANS. - + See Hammouda, J. Appl. Cryst. (2010) 43, 716-719 """ def category(self): @@ -55,7 +55,7 @@ def _boundary_conditions(self, qval): m = self.getParameterValue('M') if Rg<=0: return True if m3.0: return True + if s>3.0: return True return False def _guinier_porod_core(self, qval): @@ -70,7 +70,7 @@ def _guinier_porod_core(self, qval): if self._boundary_conditions(qval): return 0.0 q1 = math.sqrt((m-s)*n/2.0)/Rg if qval < q1: - return math.pow(qval,-s)*math.exp((-qval*qval*Rg*Rg)/n) + return math.pow(qval,-s)*math.exp((-qval*qval*Rg*Rg)/n) else: return math.pow(qval,-m)*math.pow(Rg,s-m)*math.exp((s-m)/2.0)*math.pow((m-s)*n/2.0,(m-s)/2.0) @@ -93,13 +93,13 @@ def _first_derivative_dim(self, qval): result = (2.0*s-m-3.0)/(2.0*(3.0-s)) - 0.5*(math.log(m-s)+math.log(3-s)) result += math.log(Rg) + math.log(2.0) + 1.0 return result * math.pow(qval,-m) * math.pow(Rg,s-m) * math.exp((s-m)/2.0) * math.pow((m-s)*n/2.0,(m-s)/2.0) - - + + def _first_derivative_m(self, qval): """ Compute the first derivative dI/dM @param qval: q-value to evaluate at - + Derivatives can be obtained here: http://www.derivative-calculator.net/#expr=%28%28m-s%29%283-s%29%2F2%29%5E%28%28m%20-%20s%29%2F2%29q%5E-mr%5E%28s-m%29exp%28%28s-m%29%2F2%29&diffvar=m """ @@ -115,7 +115,7 @@ def _first_derivative_m(self, qval): result = -math.log(qval) - math.log(Rg) - math.log(2.0) - 1.0 result += ( (math.log(m-s)+math.log(3-s))/2.0 + 0.5 ) return result * math.pow(qval,-m) * math.pow(Rg,s-m) * math.exp((s-m)/2.0) * math.pow((m-s)*n/2.0,(m-s)/2.0) - + def _first_derivative_rg(self, qval): """ Compute the first derivative dI/d(Rg) @@ -133,7 +133,7 @@ def _first_derivative_rg(self, qval): else: return math.pow(qval,-m)*math.exp((s-m)/2.0)*math.pow(((m-s)*n/2.0), ((m-s)/2.0))*(s-m)*math.pow(Rg,(s-m-1)) - + def function1D(self, xvals): """ Evaluate the model @@ -143,7 +143,7 @@ def function1D(self, xvals): scale = self.getParameterValue('Scale') bgd = self.getParameterValue('Background') - output = np.zeros(len(xvals), dtype=float) + output = np.zeros(len(xvals), dtype=float) for i in range(len(xvals)): output[i] = scale * self._guinier_porod_core(xvals[i]) + bgd return output @@ -164,4 +164,4 @@ def functionDeriv1D(self, xvals, jacobian): i += 1 # Required to have Mantid recognise the new function -FunctionFactory.subscribe(GuinierPorod) \ No newline at end of file +FunctionFactory.subscribe(GuinierPorod) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py index 719057b103e6..9c83e34f4822 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py @@ -56,8 +56,8 @@ def functionDeriv1D(self, xvals, jacobian): for x in xvals: ex = math.exp(-l*x*x) h = (1.0-ex)/tau - jacobian.set(i,0,-h/tau); - jacobian.set(i,1,x*x*ex/tau); + jacobian.set(i,0,-h/tau) + jacobian.set(i,1,x*x*ex/tau) i += 1 # Required to have Mantid recognise the new function diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Lorentz.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Lorentz.py index c8814de43f78..17835da7dba4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Lorentz.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Lorentz.py @@ -30,7 +30,7 @@ class Lorentz(IFunction1D): """ Provide a Lorentz model for SANS - + I(q) = scale / ( 1 + q^2 L^2 ) + background """ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Porod.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Porod.py index 6f2f280682c5..47de2227a9e7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Porod.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Porod.py @@ -30,7 +30,7 @@ class Porod(IFunction1D): """ Provide a Porod model for SANS - + I(q) = C/q^4 + background """ def category(self): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py index 815faac3bc8f..a3ebf62a493b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py @@ -55,8 +55,8 @@ def functionDeriv1D(self, xvals, jacobian): i = 0 for x in xvals: h = x*x*length/(tau*(1+x*x*length)) - jacobian.set(i,0,-h/tau); - jacobian.set(i,1,h*(1.0-h*tau)/length); + jacobian.set(i,0,-h/tau) + jacobian.set(i,1,h*(1.0-h*tau)/length) i += 1 # Required to have Mantid recognise the new function diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py index bbcc5e81cd3d..71136bf0bd72 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py @@ -372,10 +372,10 @@ def findThoseTubesThatNeedSpecialCareForCalibration(filename): data = numpy.zeros((n,5)) line = 0 for row in peakTable: - data_row = [row['Peak%d'%(i)] for i in [1,2,3,4,5]] - data[line,:] = data_row - peaksId[line] = row['TubeId'] - line+=1 + data_row = [row['Peak%d'%(i)] for i in [1,2,3,4,5]] + data[line,:] = data_row + peaksId[line] = row['TubeId'] + line+=1 # data now has all the peaks positions for each tube # the mean value is the expected value for the peak position for each tube expected_peak_pos = numpy.mean(data,axis=0) diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py index dddf9ce9f258..966213c22bcb 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py @@ -53,10 +53,10 @@ def analisePeakTable(pTable, peaksName='Peaks'): data = numpy.zeros((n,peaks)) line = 0 for row in pTable: - data_row = [row['Peak%d'%(i)] for i in range(1,peaks+1)] - data[line,:] = data_row - peaksId[line] = row['TubeId'] - line+=1 + data_row = [row['Peak%d'%(i)] for i in range(1,peaks+1)] + data[line,:] = data_row + peaksId[line] = row['TubeId'] + line+=1 # data now has all the peaks positions for each tube # the mean value is the expected value for the peak position for each tube expected_peak_pos = numpy.mean(data,axis=0) @@ -73,60 +73,60 @@ def analisePeakTable(pTable, peaksName='Peaks'): def calibrateMerlin(filename): # == Set parameters for calibration == - rangeLower = 3000 # Integrate counts in each spectra from rangeLower to rangeUpper - rangeUpper = 20000 # + rangeLower = 3000 # Integrate counts in each spectra from rangeLower to rangeUpper + rangeUpper = 20000 # # Get calibration raw file and integrate it - rawCalibInstWS = LoadRaw(filename) #'raw' in 'rawCalibInstWS' means unintegrated. - print "Integrating Workspace" - CalibInstWS = Integration( rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper ) - DeleteWorkspace(rawCalibInstWS) - print "Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate" + rawCalibInstWS = LoadRaw(filename) #'raw' in 'rawCalibInstWS' means unintegrated. + print "Integrating Workspace" + CalibInstWS = Integration( rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper ) + DeleteWorkspace(rawCalibInstWS) + print "Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate" # the known positions are given in pixels inside the tubes and transformed to provide the positions # with the center of the tube as the origin - knownPositions = 2.92713867188*(numpy.array([ 27.30074322, 92.5, 294.65178585, 362.37861919 , 512.77103043 ,663.41425323, 798.3223896, 930.9, 997.08480835])/1024 - 0.5) - funcForm = numpy.array([2,2,1,1,1,1,1,2,2],numpy.int8) + knownPositions = 2.92713867188*(numpy.array([ 27.30074322, 92.5, 294.65178585, 362.37861919 , 512.77103043 ,663.41425323, 798.3223896, 930.9, 997.08480835])/1024 - 0.5) + funcForm = numpy.array([2,2,1,1,1,1,1,2,2],numpy.int8) # The calibration will follow different steps for sets of tubes # For the door9, the best points to define the known positions are the 1st edge, 5 peaks, last edge. - points7 = knownPositions[[0,2,3,4,5,6,8]] - points7func = funcForm[[0,2,3,4,5,6,8]] + points7 = knownPositions[[0,2,3,4,5,6,8]] + points7func = funcForm[[0,2,3,4,5,6,8]] - door9pos = points7 - door9func = points7func - CalibratedComponent = 'MERLIN/door9' # door9 + door9pos = points7 + door9func = points7func + CalibratedComponent = 'MERLIN/door9' # door9 # == Get the calibration and put results into calibration table == # also put peaks into PeakFile - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door9pos, door9func, + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door9pos, door9func, outputPeak=True, margin=30, rangeList=range(20) # because 20, 21, 22, 23 are defective detectors ) - print "Got calibration (new positions of detectors) and put slit peaks into file TubeDemoMerlin01.txt" - analisePeakTable(peakTable, 'door9_tube1_peaks') + print "Got calibration (new positions of detectors) and put slit peaks into file TubeDemoMerlin01.txt" + analisePeakTable(peakTable, 'door9_tube1_peaks') # For the door8, the best points to define the known positions are the 1st edge, 5 peaks, last_edge - door8pos = points7 - door8func = points7func - CalibratedComponent = 'MERLIN/door8' - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door8pos, + door8pos = points7 + door8func = points7func + CalibratedComponent = 'MERLIN/door8' + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door8pos, door8func, outputPeak = True, #change to peakTable to append to peakTable calibTable = calibrationTable, margin = 30) - analisePeakTable(peakTable, 'door8_peaks') + analisePeakTable(peakTable, 'door8_peaks') # For the doors 7,6,5,4, 2, 1 we may use the 9 points - doorpos = knownPositions - doorfunc = funcForm - CalibratedComponent = ['MERLIN/door%d'%(i) for i in [7,6,5,4, 2, 1]] - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, + doorpos = knownPositions + doorfunc = funcForm + CalibratedComponent = ['MERLIN/door%d'%(i) for i in [7,6,5,4, 2, 1]] + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, doorfunc, outputPeak = True, calibTable = calibrationTable, margin = 30) - analisePeakTable(peakTable, 'door1to7_peaks') + analisePeakTable(peakTable, 'door1to7_peaks') # The door 3 is a special case, because it is composed by diffent kind of tubes. # door 3 tubes: 5_8, 5_7, 5_6, 5_5, 5_4, 5_3, 5_2, 5_1, 4_8, 4_7, 4_6, 4_5, 4_4, 4_3, 4_2, 4_1, 3_8, 3_7, 3_6, 3_5, 3_4 @@ -138,87 +138,87 @@ def calibrateMerlin(filename): # NOTE: the smaller tubes they have length = 1.22879882813, but 1024 detectors # so we have to correct the known positiosn by multiplying by its lenght and dividing by the longer dimension - from tube_calib_fit_params import TubeCalibFitParams + from tube_calib_fit_params import TubeCalibFitParams # calibrating tubes 1_x - CalibratedComponent = ['MERLIN/door3/tube_1_%d'%(i) for i in range(1,9)] + CalibratedComponent = ['MERLIN/door3/tube_1_%d'%(i) for i in range(1,9)] - half_diff_center = (2.92713867188 -1.22879882813)/2 # difference among the expected center position for both tubes + half_diff_center = (2.92713867188 -1.22879882813)/2 # difference among the expected center position for both tubes # here a little bit of attempts is necessary. The efective center position and lengh is different for the calibrated tube, that # is the reason, the calibrated values of the smaller tube does not seems aligned with the others. By, finding the 'best' half_diff_center # value, the alignment occurs nicely. - half_diff_center = 0.835 # + half_diff_center = 0.835 # # the knownpositions were given with the center of the bigger tube as origin, to convert # to the center of the upper tube as origin is necessary to subtract them with the half_diff_center - doorpos = knownPositions[[5,6,7,8]] - half_diff_center - doorfunc = [1,1,2,2] + doorpos = knownPositions[[5,6,7,8]] - half_diff_center + doorfunc = [1,1,2,2] # for the smal tubes, automatically searching for the peak position in pixel was not working quite well, # so we will give the aproximate position for these tubes through fitPar argument - fitPar = TubeCalibFitParams([216, 527, 826, 989]) - fitPar.setAutomatic(True) + fitPar = TubeCalibFitParams([216, 527, 826, 989]) + fitPar.setAutomatic(True) - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, doorfunc, outputPeak = True, fitPar = fitPar, calibTable = calibrationTable, margin = 30) - analisePeakTable(peakTable, 'door3_tube1_peaks') + analisePeakTable(peakTable, 'door3_tube1_peaks') # calibrating tubes 2_x - CalibratedComponent = ['MERLIN/door3/tube_2_%d'%(i) for i in range(1,9)] + CalibratedComponent = ['MERLIN/door3/tube_2_%d'%(i) for i in range(1,9)] # the knownpositions were given with the center of the bigger tube as origin, to convert # to the center of the lower tube as origin is necessary to sum them with (len_big - len_small)/2 - doorpos = knownPositions[[0,1,2,3]] + half_diff_center + doorpos = knownPositions[[0,1,2,3]] + half_diff_center # print doorpos - doorfunc = [2,2,1,1] + doorfunc = [2,2,1,1] # for the smal tubes, automatically searching for the peak position in pixel was not working quite well, # so we will give the aproximate position for these tubes through fitPar argument - fitPar = TubeCalibFitParams([50, 202, 664, 815]) - fitPar.setAutomatic(True) + fitPar = TubeCalibFitParams([50, 202, 664, 815]) + fitPar.setAutomatic(True) - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, doorfunc, outputPeak = True, calibTable = calibrationTable, fitPar = fitPar, margin = 30) - analisePeakTable(peakTable, 'door3_tube2_peaks') + analisePeakTable(peakTable, 'door3_tube2_peaks') # calibrating tubes 3_3,3_2,3_1 - CalibratedComponent = ['MERLIN/door3/tube_3_%d'%(i) for i in [1,2,3]] - doorpos = knownPositions[[0,1,2,3,5,6,7,8]] - doorfunc = funcForm[[0,1,2,3,5,6,7,8]] - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, + CalibratedComponent = ['MERLIN/door3/tube_3_%d'%(i) for i in [1,2,3]] + doorpos = knownPositions[[0,1,2,3,5,6,7,8]] + doorfunc = funcForm[[0,1,2,3,5,6,7,8]] + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, doorfunc, outputPeak = True, calibTable = calibrationTable, margin = 30) - analisePeakTable(peakTable, 'door3_123_peaks') + analisePeakTable(peakTable, 'door3_123_peaks') # calibrating others inside door3 # 5_8, 5_7, 5_6, 5_5, 5_4, 5_3, 5_2, 5_1, 4_8, 4_7, 4_6, 4_5, 4_4, 4_3, 4_2, 4_1, 3_8, 3_7, 3_6, 3_5, 3_4 - part_3 = ['MERLIN/door3/tube_3_%d'%(i) for i in [4,5,6,7,8]] - part_4 = ['MERLIN/door3/tube_4_%d'%(i) for i in range(1,9)] - part_5 = ['MERLIN/door3/tube_5_%d'%(i) for i in range(1,9)] - CalibratedComponent = part_3 + part_4 + part_5 - doorpos = knownPositions - doorfunc = funcForm - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, + part_3 = ['MERLIN/door3/tube_3_%d'%(i) for i in [4,5,6,7,8]] + part_4 = ['MERLIN/door3/tube_4_%d'%(i) for i in range(1,9)] + part_5 = ['MERLIN/door3/tube_5_%d'%(i) for i in range(1,9)] + CalibratedComponent = part_3 + part_4 + part_5 + doorpos = knownPositions + doorfunc = funcForm + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, doorfunc, outputPeak = True, calibTable = calibrationTable, margin = 30) - analisePeakTable(peakTable, 'door3_peaks') + analisePeakTable(peakTable, 'door3_peaks') # == Apply the Calibation == - ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable) - print "Applied calibration" + ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable) + print "Applied calibration" # == Save workspace == #SaveNexusProcessed( CalibInstWS, 'TubeCalibDemoMerlinResult.nxs',"Result of Running TCDemoMerlin.py") @@ -226,5 +226,5 @@ def calibrateMerlin(filename): if __name__=="__main__": - filename = 'MER12024.raw' # Calibration run ( found in \\isis\inst$\NDXMERLIN\Instrument\data\cycle_11_5 ) - calibrateMerlin(filename) + filename = 'MER12024.raw' # Calibration run ( found in \\isis\inst$\NDXMERLIN\Instrument\data\cycle_11_5 ) + calibrateMerlin(filename) diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py index 9fa967b803d5..9d4bec946929 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py @@ -68,7 +68,7 @@ def CalibrateWish( run_per_panel_list): # copy data from the current panel to the whole_instrument for i in range(tube_set.getNumTubes()): for spec_num in tube_set.getTube(i): - whole_instrument.setY(spec_num,ws.dataY(spec_num)) + whole_instrument.setY(spec_num,ws.dataY(spec_num)) # calibrate the whole_instrument with the last calibrated panel which has the calibration accumulation # of all the others @@ -80,5 +80,5 @@ def CalibrateWish( run_per_panel_list): if __name__ == "__main__": # this file is found on cycle_11_1 - run_per_panel_list = [ (17706, 'panel01'), (17705, 'panel02'), (17701, 'panel03'), (17702, 'panel04'), (17695, 'panel05')] - CalibrateWish(run_per_panel_list) + run_per_panel_list = [ (17706, 'panel01'), (17705, 'panel02'), (17701, 'panel03'), (17702, 'panel04'), (17695, 'panel05')] + CalibrateWish(run_per_panel_list) diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py index 404bbd6ef09d..4736c9a00f24 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py @@ -67,6 +67,6 @@ def CalibrateWish( RunNumber, PanelNumber): # ==== End of CalibrateWish() ==== if __name__ == "__main__": # this file is found on cycle_11_1 - RunNumber = 17701 - PanelNumber = '03' - CalibrateWish(RunNumber, PanelNumber) + RunNumber = 17701 + PanelNumber = '03' + CalibrateWish(RunNumber, PanelNumber) diff --git a/Code/Mantid/scripts/Calibration/ideal_tube.py b/Code/Mantid/scripts/Calibration/ideal_tube.py index 086cb3c22de2..a77ce0b84e3d 100644 --- a/Code/Mantid/scripts/Calibration/ideal_tube.py +++ b/Code/Mantid/scripts/Calibration/ideal_tube.py @@ -6,7 +6,7 @@ # Author: Karl Palmen ISIS class IdealTube: - """ + """ The IdealTube specifies where the peaks formed by slits or edges should occur. They can be considered as the known positions as well. @@ -27,40 +27,40 @@ class IdealTube: * :meth:`~ideal_tube.IdealTube.getFunctionalForms` """ - def __init__( self ): + def __init__( self ): """ Create empty instance """ self.positions = numpy.ndarray((0)) # position of the points in metres self.functionalForms = [] # function form of points 1=peak 2=edge. peaks assumed if []. - def setArray ( self, array ): - """ + def setArray ( self, array ): + """ Construct an ideal tube directly from an array of positions :param points: Array of points where the peaks should be in Metres """ - self.positions =numpy.array( array) + self.positions =numpy.array( array) - def setForm(self, form): - """Define the functional form for the peaks""" - self.functionalForms = form + def setForm(self, form): + """Define the functional form for the peaks""" + self.functionalForms = form - def setPositionsAndForm ( self, pos, form ): - """ + def setPositionsAndForm ( self, pos, form ): + """ Construct and ideal tube directly from an array of positions and functional forms :param pos: Array of points where the peaks or edges should be in Metres :param form: Array of functional forms of the points 1=peak, 2=edge """ - self.positions = numpy.array(pos ) - self.functionalForms = form + self.positions = numpy.array(pos ) + self.functionalForms = form - def constructTubeFor3PointsMethod( self, idealAP, idealBP, idealCP, activeTubeLen ): - """ + def constructTubeFor3PointsMethod( self, idealAP, idealBP, idealCP, activeTubeLen ): + """ Construct and ideal tube for Merlin 3-point calibration :param idealAP: Ideal left (AP) in pixels @@ -70,22 +70,22 @@ def constructTubeFor3PointsMethod( self, idealAP, idealBP, idealCP, activeTubeLe """ #Contruct Ideal tube for 3 point calibration of MERLIN standard tube (code could be put into a function) - pixelLen = activeTubeLen/1024 # Pixel length + pixelLen = activeTubeLen/1024 # Pixel length # we then convert idealAP, idealCP and idealBP to Y coordinates and put into ideal tube array - self.positions = numpy.array([ idealAP*pixelLen - activeTubeLen/2, idealCP*pixelLen - activeTubeLen/2, idealBP*pixelLen - activeTubeLen/2]) - self.functionalForms = [ 2, 1, 2 ] + self.positions = numpy.array([ idealAP*pixelLen - activeTubeLen/2, idealCP*pixelLen - activeTubeLen/2, idealBP*pixelLen - activeTubeLen/2]) + self.functionalForms = [ 2, 1, 2 ] - def getArray( self ): - """ + def getArray( self ): + """ Reurn the array of of points where the peaks should be in Metres """ - return self.positions + return self.positions - def getFunctionalForms( self ): - """ + def getFunctionalForms( self ): + """ Reurn the array of of points where the peaks should be in Metres """ - return self.functionalForms + return self.functionalForms diff --git a/Code/Mantid/scripts/Calibration/tube_calib.py b/Code/Mantid/scripts/Calibration/tube_calib.py index cc6aeda7652c..91c3f8fd5b7a 100644 --- a/Code/Mantid/scripts/Calibration/tube_calib.py +++ b/Code/Mantid/scripts/Calibration/tube_calib.py @@ -43,9 +43,9 @@ def createTubeCalibtationWorkspaceByWorkspaceIndexList ( integratedWorkspace, ou pixel = 1 #integratedWorkspace. for i in workspaceIndexList: - pixelNumbers.append(pixel) - pixel = pixel + 1 - integratedPixelCounts.append( integratedWorkspace.dataY(i)[0] ) + pixelNumbers.append(pixel) + pixel = pixel + 1 + integratedPixelCounts.append( integratedWorkspace.dataY(i)[0] ) CreateWorkspace(dataX=pixelNumbers,dataY=integratedPixelCounts, OutputWorkspace=outputWorkspace) #if (showPlot): @@ -210,20 +210,20 @@ def getPoints ( IntegratedWorkspace, funcForms, fitParams, whichTube, showPlot=F # Loop over the points for i in range(len(funcForms)): - if funcForms[i] == 2: + if funcForms[i] == 2: # find the edge position - peakIndex = fitEdges(fitParams, i, getPointsWs, calibPointWs) - else: - peakIndex = fitGaussian(fitParams, i, getPointsWs, calibPointWs) + peakIndex = fitEdges(fitParams, i, getPointsWs, calibPointWs) + else: + peakIndex = fitGaussian(fitParams, i, getPointsWs, calibPointWs) # get the peak centre - peakCentre = mtd[calibPointWs + '_Parameters'].row(peakIndex).items()[1][1] - results.append(peakCentre) + peakCentre = mtd[calibPointWs + '_Parameters'].row(peakIndex).items()[1][1] + results.append(peakCentre) - if showPlot: - ws = mtd[calibPointWs + '_Workspace'] - fitt_y_values.append(copy.copy(ws.dataY(1))) - fitt_x_values.append(copy.copy(ws.dataX(1))) + if showPlot: + ws = mtd[calibPointWs + '_Workspace'] + fitt_y_values.append(copy.copy(ws.dataY(1))) + fitt_x_values.append(copy.copy(ws.dataX(1))) if showPlot: FittedData = CreateWorkspace(numpy.hstack(fitt_x_values), @@ -329,10 +329,10 @@ def correctTubeToIdealTube( tubePoints, idealTubePoints, nDets, TestMode=False, # Fit quadratic to ideal tube points CreateWorkspace(dataX=usedTubePoints,dataY=usedIdealTubePoints, OutputWorkspace="PolyFittingWorkspace") try: - Fit(InputWorkspace="PolyFittingWorkspace",Function='name=Polynomial,n=%d'%(polinFit),StartX=str(0.0),EndX=str(nDets),Output="QF") + Fit(InputWorkspace="PolyFittingWorkspace",Function='name=Polynomial,n=%d'%(polinFit),StartX=str(0.0),EndX=str(nDets),Output="QF") except: - print "Fit failed" - return [] + print "Fit failed" + return [] paramQF = mtd['QF_Parameters'] @@ -349,7 +349,7 @@ def correctTubeToIdealTube( tubePoints, idealTubePoints, nDets, TestMode=False, print "TestMode code" for i in range( len(usedTubePoints) ): #print "used point",i,"shoving pixel",int(usedTubePoints[i]) - xResult[ int(usedTubePoints[i]) ] = xResult[0] + xResult[ int(usedTubePoints[i]) ] = xResult[0] # print xResult return xResult @@ -383,8 +383,8 @@ def getCalibratedPixelPositions( ws, tubePts, idealTubePts, whichTube, peakTestM pixels = correctTubeToIdealTube ( tubePts, idealTubePts, nDets, TestMode=peakTestMode, polinFit=polinFit ) #print pixels if( len(pixels) != nDets): - print "Tube correction failed." - return detIDs, detPositions + print "Tube correction failed." + return detIDs, detPositions baseInstrument = ws.getInstrument().getBaseInstrument() # Get tube unit vector # get the detector from the baseInstrument, in order to get the positions @@ -502,9 +502,9 @@ def getCalibration( ws, tubeSet, calibTable, fitPar, iTube, peaksTable, print "Calibrating tube", i+1,"of",nTubes, tubeSet.getTubeName(i) if ( len(wht) < 1 ): - print "Unable to get any workspace indices (spectra) for this tube. Tube",tubeSet.getTubeName(i),"not calibrated." + print "Unable to get any workspace indices (spectra) for this tube. Tube",tubeSet.getTubeName(i),"not calibrated." #skip this tube - continue + continue # Calibribate the tube, if possible if (tubeSet.getTubeLength(i) <= excludeShortTubes): @@ -599,7 +599,7 @@ def getCalibrationFromPeakFile ( ws, calibTable, iTube, PeakFile ): calibTable.addRow ( nextRow ) if(nTubes == 0): - return + return # Delete temporary workspaces for getting new detector positions DeleteWorkspace('PolyFittingWorkspace') @@ -611,7 +611,7 @@ def getCalibrationFromPeakFile ( ws, calibTable, iTube, PeakFile ): ## implement this function def constructIdealTubeFromRealTube( ws, tube, fitPar, funcForm ): - """ + """ Construct an ideal tube from an actual tube (assumed ideal) :param ws: integrated workspace @@ -622,32 +622,32 @@ def constructIdealTubeFromRealTube( ws, tube, fitPar, funcForm ): """ # Get workspace indices - idealTube = IdealTube() + idealTube = IdealTube() - nTubes = tube.getNumTubes() - if(nTubes < 1): - raise RuntimeError("Invalid tube specification received by constructIdealTubeFromRealTube") - elif(nTubes > 1): - print "Specification has several tubes. The ideal tube will be based on the first tube",tube.getTubeName(0) + nTubes = tube.getNumTubes() + if(nTubes < 1): + raise RuntimeError("Invalid tube specification received by constructIdealTubeFromRealTube") + elif(nTubes > 1): + print "Specification has several tubes. The ideal tube will be based on the first tube",tube.getTubeName(0) - wht, _ = tube.getTube(0) + wht, _ = tube.getTube(0) # print wht # Check tube - if ( len(wht) < 1 ): + if ( len(wht) < 1 ): raise RuntimeError("Unable to get any workspace indices for this tube. Cannot use as ideal tube.") # Get actual tube on which ideal tube is based - actualTube = getPoints ( ws, funcForm, fitPar, wht) - print "Actual tube that ideal tube is to be based upon",actualTube + actualTube = getPoints ( ws, funcForm, fitPar, wht) + print "Actual tube that ideal tube is to be based upon",actualTube # Get ideal tube based on this actual tube - try: - idealTube.setArray(actualTube) - except: - msg = "Attempted to create ideal tube based on actual tube" + str(actualTube) - msg += "Unable to create ideal tube." - msg += "Please choose another tube for constructIdealTubeFromRealTube()." - raise RuntimeError(msg) - return idealTube + try: + idealTube.setArray(actualTube) + except: + msg = "Attempted to create ideal tube based on actual tube" + str(actualTube) + msg += "Unable to create ideal tube." + msg += "Please choose another tube for constructIdealTubeFromRealTube()." + raise RuntimeError(msg) + return idealTube diff --git a/Code/Mantid/scripts/Calibration/tube_spec.py b/Code/Mantid/scripts/Calibration/tube_spec.py index e22d27871c9e..4ce88e2224c2 100644 --- a/Code/Mantid/scripts/Calibration/tube_spec.py +++ b/Code/Mantid/scripts/Calibration/tube_spec.py @@ -91,7 +91,7 @@ def setTubeSpecByStringArray( self, tubeSpecArray ): """ for i in range(len(tubeSpecArray)): - self.setTubeSpecByString(tubeSpecArray[i]) + self.setTubeSpecByString(tubeSpecArray[i]) def getInstrumentName (self): @@ -107,26 +107,26 @@ def isTube(self, comp): """ # We simply assume it's a tube if it has a large number of children if( hasattr( comp, "nelements")): - return (comp.nelements() >= self.minNumDetsInTube ) + return (comp.nelements() >= self.minNumDetsInTube ) else: - return False + return False def searchForTubes(self, comp): - """ + """ Searches the component for tubes and saves them in array, appending if array is not empty. :param comp: the component """ # Go through all descendents that are not a descendent of a tube and if it's a tube, store and count it. - if self.isTube( comp ): - self.tubes.append( comp ) + if self.isTube( comp ): + self.tubes.append( comp ) #print "Tube found", comp.getName() # If not tube, Search children, if any - else: - if( hasattr( comp, "nelements")): - for i in range(comp.nelements()): - self.searchForTubes(comp[i]) + else: + if( hasattr( comp, "nelements")): + for i in range(comp.nelements()): + self.searchForTubes(comp[i]) def getNumTubes(self): @@ -144,7 +144,7 @@ def getNumTubes(self): return self.numTubes for i in range( len(comps)): - self.searchForTubes(comps[i]) + self.searchForTubes(comps[i]) self.numTubes = len(self.tubes) return self.numTubes @@ -165,7 +165,7 @@ def getComponent ( self ): comp = self.inst.getComponentByName(self.componentNameArray[0]) if( comp ): - self.componentArray.append(comp) + self.componentArray.append(comp) return self.componentArray[0] @@ -181,9 +181,9 @@ def getComponents ( self ): # We look for the components for i in range( len(self.componentNameArray)): - print "Looking for", self.componentNameArray[i] + print "Looking for", self.componentNameArray[i] - comp = self.inst.getComponentByName(self.componentNameArray[i]) + comp = self.inst.getComponentByName(self.componentNameArray[i]) if( comp ): self.componentArray.append(comp) @@ -214,11 +214,11 @@ def getDetectorInfoFromTube( self, tubeIx ): """ nTubes = self.getNumTubes() if(nTubes < 0): - print "Error in listing tubes" - return 0, 0, 1 + print "Error in listing tubes" + return 0, 0, 1 if(tubeIx < 0 or tubeIx >= nTubes): - print "Tube index",tubeIx,"out of range 0 to",nTubes - return 0, 0, 1 + print "Tube index",tubeIx,"out of range 0 to",nTubes + return 0, 0, 1 comp = self.tubes[tubeIx] @@ -228,15 +228,15 @@ def getDetectorInfoFromTube( self, tubeIx ): # Allow for reverse numbering of Detectors lastDet = comp[numDet-1].getID() if (lastDet < firstDet): - step = -1 - if( firstDet - lastDet + 1 != numDet): - print "Detector number range",firstDet-lastDet+1," not equal to number of detectors",numDet - print "Detectors not numbered continuously in this tube. Calibration will fail for this tube." + step = -1 + if( firstDet - lastDet + 1 != numDet): + print "Detector number range",firstDet-lastDet+1," not equal to number of detectors",numDet + print "Detectors not numbered continuously in this tube. Calibration will fail for this tube." else: - step = 1 - if( lastDet - firstDet + 1 != numDet): - print "Detector number range",lastDet-firstDet+1," not equal to number of detectors",numDet - print "Detectors not numbered continuously in this tube. Calibration will fail for this tube." + step = 1 + if( lastDet - firstDet + 1 != numDet): + print "Detector number range",lastDet-firstDet+1," not equal to number of detectors",numDet + print "Detectors not numbered continuously in this tube. Calibration will fail for this tube." #print "First dectector ", firstDet," Last detector ", firstDet+numDet-1, "Number of detectors ", numDet #print "First dectector ", firstDet," Last detector ", comp[numDet-1].getID() @@ -286,11 +286,11 @@ def getTubeName ( self, tubeIx ): """ nTubes = self.getNumTubes() if(nTubes < 0): - print "Error in listing tubes" - return 'Unknown' + print "Error in listing tubes" + return 'Unknown' if(tubeIx < 0 or tubeIx >= nTubes): - print "Tube index",tubeIx,"out of range 0 to",nTubes - return 'Unknown' + print "Tube index",tubeIx,"out of range 0 to",nTubes + return 'Unknown' comp = self.tubes[tubeIx] diff --git a/Code/Mantid/scripts/Engineering/EnginXUtils.py b/Code/Mantid/scripts/Engineering/EnginXUtils.py index 4aa0d044a4d7..15f74b45b94b 100644 --- a/Code/Mantid/scripts/Engineering/EnginXUtils.py +++ b/Code/Mantid/scripts/Engineering/EnginXUtils.py @@ -18,13 +18,13 @@ def getDetIDsForBank(bank): detIDs = set() for i in range(grouping.getNumberHistograms()): - if grouping.readY(i)[0] == bank: - detIDs.add(grouping.getDetector(i).getID()) + if grouping.readY(i)[0] == bank: + detIDs.add(grouping.getDetector(i).getID()) DeleteWorkspace(grouping) if len(detIDs) == 0: - raise Exception('Unknown bank') + raise Exception('Unknown bank') return detIDs @@ -34,11 +34,11 @@ def getWsIndicesForBank(bank, ws): detIDs = getDetIDsForBank(bank) def isIndexInBank(index): - try: - det = ws.getDetector(index) - return (det.getID() in detIDs) - except: - return False + try: + det = ws.getDetector(index) + return (det.getID() in detIDs) + except: + return False return filter(isIndexInBank, range(0, ws.getNumberHistograms())) diff --git a/Code/Mantid/scripts/FilterEvents.py b/Code/Mantid/scripts/FilterEvents.py index ef661b20f72e..3b14caff0bfe 100644 --- a/Code/Mantid/scripts/FilterEvents.py +++ b/Code/Mantid/scripts/FilterEvents.py @@ -2,13 +2,13 @@ from PyQt4 import QtGui import sys -def qapp(): - if QtGui.QApplication.instance(): - app = QtGui.QApplication.instance() - else: - app = QtGui.QApplication(sys.argv) +def qapp(): + if QtGui.QApplication.instance(): + app = QtGui.QApplication.instance() + else: + app = QtGui.QApplication(sys.argv) return app - + app = qapp() reducer = eventFilterGUI.MainWindow() #the main ui class in this file is called MainWindow diff --git a/Code/Mantid/scripts/FilterEvents/MplFigureCanvas.py b/Code/Mantid/scripts/FilterEvents/MplFigureCanvas.py index 183e6d9a55be..70749903430c 100644 --- a/Code/Mantid/scripts/FilterEvents/MplFigureCanvas.py +++ b/Code/Mantid/scripts/FilterEvents/MplFigureCanvas.py @@ -6,7 +6,7 @@ from matplotlib.figure import Figure class Qt4MplCanvas(FigureCanvas): - """ A customized Qt widget for matplotlib figure. + """ A customized Qt widget for matplotlib figure. It can be used to replace GraphicsView of QtGui """ def __init__(self, parent): @@ -21,7 +21,7 @@ def __init__(self, parent): self.setParent(parent) # Set size policy to be able to expanding and resizable with frame - FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, + FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) @@ -29,7 +29,7 @@ def __init__(self, parent): return def plot(self, x, y): - """ Plot a set of data + """ Plot a set of data Argument: - x: numpy array X - y: numpy array Y @@ -41,6 +41,6 @@ def plot(self, x, y): return def getPlot(self): - """ reture figure's axes to expose the matplotlib figure to PyQt client + """ reture figure's axes to expose the matplotlib figure to PyQt client """ return self.axes diff --git a/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py b/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py index 9b19740180a2..4f757a818fc9 100644 --- a/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py +++ b/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py @@ -7,8 +7,8 @@ # # WARNING! All changes made in this file will be lost! -from PyQt4 import QtCore, QtGui -from MplFigureCanvas import Qt4MplCanvas +from PyQt4 import QtCore, QtGui +from MplFigureCanvas import Qt4MplCanvas try: diff --git a/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py b/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py index 49d9cc7973c7..5a8a55e32d60 100644 --- a/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py +++ b/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py @@ -15,7 +15,7 @@ import mantid import mantid.simpleapi as api import mantid.kernel -from mantid.simpleapi import AnalysisDataService +from mantid.simpleapi import AnalysisDataService from mantid.kernel import ConfigService @@ -72,19 +72,19 @@ def XpaintEvent(self, e): return -class MainWindow(QtGui.QMainWindow): +class MainWindow(QtGui.QMainWindow): """ Class of Main Window (top) Copy to ui.setupUI # Version 3.0 + Import for Ui_MainWindow.py - from MplFigureCanvas import Qt4MplCanvas + from MplFigureCanvas import Qt4MplCanvas # Replace 'self.graphicsView = QtGui.QtGraphicsView' with the following self.graphicsView = Qt4MplCanvas(self.centralwidget) self.mainplot = self.graphicsView.getPlot() - + # Version 2.0 + Import import matplotlib from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas @@ -109,10 +109,10 @@ class MainWindow(QtGui.QMainWindow): self.ui.graphicsView.setGeometry(QtCore.QRect(40, 230, 821, 411)) self.ui.graphicsView.setObjectName(_fromUtf8("graphicsView")) - """ - + """ + def __init__(self, parent=None): - """ Intialization and set up + """ Intialization and set up """ # Base class QtGui.QMainWindow.__init__(self,parent) @@ -121,11 +121,11 @@ def __init__(self, parent=None): config = ConfigService.Instance() self._instrument = config["default.instrument"] - # Central widget + # Central widget self.centralwidget = QtGui.QWidget(self) - # UI Window (from Qt Designer) - self.ui = Ui_MainWindow() + # UI Window (from Qt Designer) + self.ui = Ui_MainWindow() self.ui.setupUi(self) # Do initialize plotting @@ -163,12 +163,12 @@ def __init__(self, parent=None): self.ui.horizontalSlider_2.setTracking(True) self.ui.horizontalSlider_2.setTickPosition(QSlider.NoTicks) self.connect(self.ui.horizontalSlider_2, SIGNAL('valueChanged(int)'), self.move_rightSlider) - - # self.connect(self.ui.lineEdit_3, QtCore.SIGNAL("textChanged(QString)"), - # self.set_startTime) + + # self.connect(self.ui.lineEdit_3, QtCore.SIGNAL("textChanged(QString)"), + # self.set_startTime) self.ui.lineEdit_3.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_3)) - self.connect(self.ui.pushButton_setT0, QtCore.SIGNAL("clicked()"), self.set_startTime) - # self.connect(self.ui.lineEdit_4, QtCore.SIGNAL("textChanged(QString)"), + self.connect(self.ui.pushButton_setT0, QtCore.SIGNAL("clicked()"), self.set_startTime) + # self.connect(self.ui.lineEdit_4, QtCore.SIGNAL("textChanged(QString)"), # self.set_stopTime) self.ui.lineEdit_4.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_4)) self.connect(self.ui.pushButton_setTf, QtCore.SIGNAL("clicked()"), self.set_stopTime) @@ -194,11 +194,11 @@ def __init__(self, parent=None): self.ui.lineEdit_7.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_7)) self.ui.lineEdit_8.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_8)) self.ui.lineEdit_9.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_9)) - - self.connect(self.ui.lineEdit_5, QtCore.SIGNAL("textChanged(QString)"), - self.set_minLogValue) - self.connect(self.ui.lineEdit_6, QtCore.SIGNAL("textChanged(QString)"), - self.set_maxLogValue) + + self.connect(self.ui.lineEdit_5, QtCore.SIGNAL("textChanged(QString)"), + self.set_minLogValue) + self.connect(self.ui.lineEdit_6, QtCore.SIGNAL("textChanged(QString)"), + self.set_maxLogValue) dirchangeops = ["Both", "Increase", "Decrease"] self.ui.comboBox_4.addItems(dirchangeops) @@ -230,7 +230,7 @@ def __init__(self, parent=None): self.ui.checkBox_from1.setChecked(False) self.ui.checkBox_groupWS.setChecked(True) - self.connect(self.ui.comboBox_tofCorr, SIGNAL('currentIndexChanged(int)'), self.showHideEi) + self.connect(self.ui.comboBox_tofCorr, SIGNAL('currentIndexChanged(int)'), self.showHideEi) self.connect(self.ui.pushButton_refreshCorrWSList, SIGNAL('clicked()'), self._searchTableWorkspaces) self.ui.lineEdit_Ei.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_Ei)) @@ -254,8 +254,8 @@ def __init__(self, parent=None): # Side information self.ui.label_mean.hide() self.ui.label_meanvalue.hide() - self.ui.label_avg.hide() - self.ui.label_timeAvgValue.hide() + self.ui.label_avg.hide() + self.ui.label_timeAvgValue.hide() self.ui.label_freq.hide() self.ui.label_freqValue.hide() self.ui.label_logname.hide() @@ -263,15 +263,15 @@ def __init__(self, parent=None): self.ui.label_logsize.hide() self.ui.label_logsizevalue.hide() - # Default + # Default self._defaultdir = os.getcwd() # self.ui.InputVal.setValidator(QtGui.QDoubleValidator(self.ui.InputVal)) - + # QtCore.QObject.connect(self.ui.convert, QtCore.SIGNAL("clicked()"), self.convert ) # QtCore.QObject.connect(self.ui.inputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) # QtCore.QObject.connect(self.ui.outputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) - # self.setInstrumentInputs() + # self.setInstrumentInputs() ##defaults @@ -284,7 +284,7 @@ def on_mouseDownEvent(self, event): x = event.xdata y = event.ydata - if x is not None and y is not None: + if x is not None and y is not None: msg = "You've clicked on a bar with coords:\n %f, %f" % (x, y) QMessageBox.information(self, "Click!", msg) @@ -302,7 +302,7 @@ def computeMock(self): vecx = [] vecy = [] - + x = x0 while x < xf: y = 0.0 @@ -317,9 +317,9 @@ def computeMock(self): def move_leftSlider(self): - """ Re-setup left range line in figure. - Triggered by a change in Qt Widget. NO EVENT is required. - """ + """ Re-setup left range line in figure. + Triggered by a change in Qt Widget. NO EVENT is required. + """ newx = self.ui.horizontalSlider.value() if newx <= self._rightSlideValue and newx != self._leftSlideValue: # Allowed value: move the value bar @@ -349,12 +349,12 @@ def set_startTime(self): """ inps = str(self.ui.lineEdit_3.text()) print "Starting time = %s" % (inps) - + xlim = self.ui.mainplot.get_xlim() if inps == "": # Empty. Use default newtime0 = xlim[0] - else: + else: newtime0 = float(inps) # Convert to integer slide value @@ -390,18 +390,18 @@ def set_startTime(self): self.ui.graphicsView.draw() - # Set the value to left slider + # Set the value to left slider self.ui.horizontalSlider.setValue(self._leftSlideValue) - # Reset the value of line edit - if resetT is True: + # Reset the value of line edit + if resetT is True: self.ui.lineEdit_3.setText(str(newtime0)) return def move_rightSlider(self): - """ Re-setup left range line in figure. - Triggered by a change in Qt Widget. NO EVENT is required. - """ + """ Re-setup left range line in figure. + Triggered by a change in Qt Widget. NO EVENT is required. + """ newx = self.ui.horizontalSlider_2.value() if newx >= self._leftSlideValue and newx != self._rightSlideValue: # Allowed value: move the value bar @@ -430,13 +430,13 @@ def set_stopTime(self): """ inps = str(self.ui.lineEdit_4.text()) print "Stopping time = %s" % (inps) - + xlim = self.ui.mainplot.get_xlim() if inps == "": # Empty. Use default newtimef = xlim[1] else: - # Parse + # Parse newtimef = float(inps) # Convert to integer slide value @@ -469,7 +469,7 @@ def set_stopTime(self): self.ui.graphicsView.draw() - # Set the value to left slider + # Set the value to left slider self.ui.horizontalSlider_2.setValue(self._rightSlideValue) # Reset to line edit @@ -479,9 +479,9 @@ def set_stopTime(self): return def move_lowerSlider(self): - """ Re-setup upper range line in figure. - Triggered by a change in Qt Widget. NO EVENT is required. - """ + """ Re-setup upper range line in figure. + Triggered by a change in Qt Widget. NO EVENT is required. + """ inewy = self.ui.verticalSlider_2.value() print "LowerSlider is set with value %d vs. class variable %d" % (inewy, self._lowerSlideValue) @@ -509,7 +509,7 @@ def move_lowerSlider(self): self.ui.graphicsView.draw() # Set line edit input - if setLineEdit is True: + if setLineEdit is True: # Change value to line edit (5) self.ui.lineEdit_5.setText(str(newy)) # Reset the class variable @@ -523,11 +523,11 @@ def set_minLogValue(self): print "Minimum Log Value = %s" %(str(self.ui.lineEdit_5.text())) ylim = self.ui.mainplot.get_ylim() - + if str(self.ui.lineEdit_5.text()) == "": # Empty. Default to minY newminY = ylim[0] - else: + else: # Non empty. Parse newminY = float(self.ui.lineEdit_5.text()) @@ -551,7 +551,7 @@ def set_minLogValue(self): # Move the vertical line lowerx = self.ui.mainplot.get_xlim() - lowery = [newminY, newminY] + lowery = [newminY, newminY] setp(self.lowerslideline, xdata=lowerx, ydata=lowery) self.ui.graphicsView.draw() @@ -568,9 +568,9 @@ def set_minLogValue(self): return def move_upperSlider(self): - """ Re-setup upper range line in figure. - Triggered by a change in Qt Widget. NO EVENT is required. - """ + """ Re-setup upper range line in figure. + Triggered by a change in Qt Widget. NO EVENT is required. + """ inewy = self.ui.verticalSlider.value() # Return w/o change @@ -640,7 +640,7 @@ def set_maxLogValue(self): # Move the vertical line upperx = self.ui.mainplot.get_xlim() - uppery = [newmaxY, newmaxY] + uppery = [newmaxY, newmaxY] setp(self.upperslideline, xdata=upperx, ydata=uppery) self.ui.graphicsView.draw() @@ -658,7 +658,7 @@ def set_maxLogValue(self): def browse_File(self): """ Open a file dialog to get file """ - filename = QtGui.QFileDialog.getOpenFileName(self, 'Input File Dialog', + filename = QtGui.QFileDialog.getOpenFileName(self, 'Input File Dialog', self._defaultdir, "Data (*.nxs *.dat);;All files (*.*)") self.ui.lineEdit.setText(str(filename)) @@ -699,10 +699,10 @@ def use_existWS(self): """ wsname = str(self.ui.comboBox.currentText()) - try: + try: dataws = AnalysisDataService.retrieve(wsname) self._importDataWorkspace(dataws) - except KeyError: + except KeyError: pass # Reset GUI @@ -725,7 +725,7 @@ def plotLogValue(self): vecvalue = samplelog.value # check - if len(vectimes) == 0: + if len(vectimes) == 0: print "Empty log!" # Convert absolute time to relative time in seconds @@ -748,7 +748,7 @@ def plotLogValue(self): self.ui.mainplot.set_xlim(xlim[0], xlim[1]) self.ui.mainplot.set_ylim(ylim[0], ylim[1]) - setp(self.mainline, xdata=vecreltimes, ydata=vecvalue) + setp(self.mainline, xdata=vecreltimes, ydata=vecvalue) samunit = samplelog.units if len(samunit) == 0: @@ -767,7 +767,7 @@ def plotLogValue(self): self.ui.verticalSlider_2.setValue(self._lowerSlideValue) self.ui.lineEdit_5.setText("") - setp(self.upperslideline, xdata=xlim, ydata=[ylim[1], ylim[1]]) + setp(self.upperslideline, xdata=xlim, ydata=[ylim[1], ylim[1]]) self._upperSlideValue = 100 self.ui.verticalSlider.setValue(self._upperSlideValue) self.ui.lineEdit_6.setText("") @@ -785,8 +785,8 @@ def plotLogValue(self): self.ui.label_mean.show() self.ui.label_meanvalue.show() - self.ui.label_avg.show() - self.ui.label_timeAvgValue.show() + self.ui.label_avg.show() + self.ui.label_timeAvgValue.show() self.ui.label_freq.show() self.ui.label_freqValue.show() self.ui.label_logname.show() @@ -803,7 +803,7 @@ def plotLogValue(self): # Set suggested processing scheme if numentries > HUGE_FAST: self.ui.checkBox_fastLog.setCheckState(True) - if numentries > HUGE_PARALLEL: + if numentries > HUGE_PARALLEL: self.ui.checkBox_doParallel.setCheckState(True) else: self.ui.checkBox_doParallel.setCheckState(False) @@ -817,7 +817,7 @@ def plotLogValue(self): def _importDataWorkspace(self, dataws): """ Import data workspace for filtering """ - if dataws is None: + if dataws is None: return # Plot time counts @@ -827,7 +827,7 @@ def _importDataWorkspace(self, dataws): failure! \n%s\n" % (str(dataws), errmsg) self._setErrorMsg(errmsg) return False - + # Import log self._sampleLogNames = [""] @@ -837,19 +837,19 @@ def _importDataWorkspace(self, dataws): pv = p.value if isinstance(pv, numpy.ndarray): times = p.times - if len(times) > 1: + if len(times) > 1: self._sampleLogNames.append(p.name) # ENDFOR(p) - # Set up sample log + # Set up sample log self.ui.comboBox_2.clear() self.ui.comboBox_2.addItems(self._sampleLogNames) # Side information self.ui.label_mean.hide() self.ui.label_meanvalue.hide() - self.ui.label_avg.hide() - self.ui.label_timeAvgValue.hide() + self.ui.label_avg.hide() + self.ui.label_timeAvgValue.hide() self.ui.label_freq.hide() self.ui.label_freqValue.hide() @@ -858,12 +858,12 @@ def _importDataWorkspace(self, dataws): self.ui.label_lognamevalue.hide() # Set dataws to class variable - self._dataWS = dataws + self._dataWS = dataws return True def scanEventWorkspaces(self): - """ + """ """ wsnames = AnalysisDataService.getObjectNames() @@ -874,7 +874,7 @@ def scanEventWorkspaces(self): eventwsnames.append(wsname) # ENDFOR - if len(eventwsnames) > 0: + if len(eventwsnames) > 0: self.ui.comboBox.clear() self.ui.comboBox.addItems(eventwsnames) @@ -894,7 +894,7 @@ def _loadFile(self, filename): if runnumber <= 0: print "Run number cannot be less or equal to zero. User gives %s. " % (filename) return None - else: + else: ishort = config.getInstrument(self._instrument).shortName() filename = "%s_%s" %(ishort, filename) wsname = filename + "_event" @@ -922,22 +922,22 @@ def _loadFile(self, filename): return None # Load - try: + try: ws = api.Load(Filename=filename, OutputWorkspace=wsname) except: ws = None return ws - + def _plotTimeCounts(self, wksp): - """ Plot time/counts + """ Plot time/counts """ import datetime # Rebin events by pulse time try: # Get run start and run stop - if wksp.getRun().hasProperty("run_start"): + if wksp.getRun().hasProperty("run_start"): runstart = wksp.getRun().getProperty("run_start").value else: runstart = wksp.getRun().getProperty("proton_charge").times[0] @@ -945,11 +945,11 @@ def _plotTimeCounts(self, wksp): runstart = str(runstart).split(".")[0].strip() runstop = str(runstop).split(".")[0].strip() - + t0 = datetime.datetime.strptime(runstart, "%Y-%m-%dT%H:%M:%S") tf = datetime.datetime.strptime(runstop, "%Y-%m-%dT%H:%M:%S") - - # Calcualte + + # Calcualte dt = tf-t0 timeduration = dt.days*3600*24 + dt.seconds @@ -959,7 +959,7 @@ def _plotTimeCounts(self, wksp): sumwsname = "_Summed_%s"%(str(wksp)) if AnalysisDataService.doesExist(sumwsname) is False: - sumws = api.RebinByPulseTimes(InputWorkspace=wksp, OutputWorkspace = sumwsname, + sumws = api.RebinByPulseTimes(InputWorkspace=wksp, OutputWorkspace = sumwsname, Params="0, %f, %d"%(timeres, timeduration)) sumws = api.SumSpectra(InputWorkspace=sumws, OutputWorkspace=str(sumws)) sumws = api.ConvertToPointData(InputWorkspace=sumws, OutputWorkspace=str(sumws)) @@ -976,7 +976,7 @@ def _plotTimeCounts(self, wksp): ymin = min(vecy) ymax = max(vecy) - # Reset graph + # Reset graph self.ui.mainplot.set_xlim(xmin, xmax) self.ui.mainplot.set_ylim(ymin, ymax) @@ -984,16 +984,16 @@ def _plotTimeCounts(self, wksp): self.ui.mainplot.set_ylabel('Counts', fontsize=13) # Set up main line - setp(self.mainline, xdata=vecx, ydata=vecy) + setp(self.mainline, xdata=vecx, ydata=vecy) # Reset slide newslidery = [min(vecy), max(vecy)] newleftx = xmin + (xmax-xmin)*self._leftSlideValue*0.01 - setp(self.leftslideline, xdata=[newleftx, newleftx], ydata=newslidery) + setp(self.leftslideline, xdata=[newleftx, newleftx], ydata=newslidery) newrightx = xmin + (xmax-xmin)*self._rightSlideValue*0.01 - setp(self.rightslideline, xdata=[newrightx, newrightx], ydata=newslidery) + setp(self.rightslideline, xdata=[newrightx, newrightx], ydata=newslidery) self.ui.graphicsView.draw() @@ -1020,7 +1020,7 @@ def filterByTime(self): title = str(self.ui.lineEdit_title.text()) - """ Debug + """ Debug for k in kwargs.keys(): print k, kwargs[k], type(kwargs[k]) print "Input workspace = ", str(self._dataWS) @@ -1073,7 +1073,7 @@ def filterByLogValue(self): if self.ui.lineEdit_8.text() != "": logvaluetol = float(self.ui.lineEdit_8.text()) kwargs["LogValueTolerance"] = logvaluetol - + splitwsname = str(self._dataWS) + "_splitters" splitinfowsname = str(self._dataWS) + "_info" @@ -1088,7 +1088,7 @@ def filterByLogValue(self): LogName = samplelog, InformationWorkspace = splitinfowsname, **kwargs) - try: + try: self.splitWksp(splitws, infows) except Exception as mtderror: self._setErrorMsg("Splitting Failed!\n %s" % (str(mtderror))) @@ -1119,19 +1119,19 @@ def splitWksp(self, splitws, infows): if len(outbasewsname) == 0: outbasewsname = "tempsplitted" self.ui.lineEdit_outwsname.setText(outbasewsname) - + api.FilterEvents( - InputWorkspace = self._dataWS, - SplitterWorkspace = splitws, - InformationWorkspace = infows, - OutputWorkspaceBaseName = outbasewsname, - GroupWorkspaces = dogroupws, - FilterByPulseTime = filterbypulse, - CorrectionToSample = corr2sample, - SpectrumWithoutDetector = how2skip, - SplitSampleLogs = splitsamplelog, - OutputWorkspaceIndexedFrom1 = startfrom1, - OutputTOFCorrectionWorkspace = 'TOFCorrTable', **kwargs) + InputWorkspace = self._dataWS, + SplitterWorkspace = splitws, + InformationWorkspace = infows, + OutputWorkspaceBaseName = outbasewsname, + GroupWorkspaces = dogroupws, + FilterByPulseTime = filterbypulse, + CorrectionToSample = corr2sample, + SpectrumWithoutDetector = how2skip, + SplitSampleLogs = splitsamplelog, + OutputWorkspaceIndexedFrom1 = startfrom1, + OutputTOFCorrectionWorkspace = 'TOFCorrTable', **kwargs) return @@ -1173,12 +1173,12 @@ def _searchTableWorkspaces(self): tablewsnames = [] for wsname in wsnames: wksp = AnalysisDataService.retrieve(wsname) - if isinstance(wksp, mantid.api._api.ITableWorkspace): + if isinstance(wksp, mantid.api._api.ITableWorkspace): tablewsnames.append(wsname) # ENDFOR self.ui.comboBox_corrWS.clear() - if len(tablewsnames) > 0: + if len(tablewsnames) > 0: self.ui.comboBox_corrWS.addItems(tablewsnames) return @@ -1193,7 +1193,7 @@ def _clearErrorMsg(self): def _setErrorMsg(self, errmsg): """ Clear error message - """ + """ #self.ui.plainTextEdit_ErrorMsg.setPlainText(errmsg) #self.ui.label_error.show() @@ -1206,7 +1206,7 @@ def _setErrorMsg(self, errmsg): def _resetGUI(self, resetfilerun=False, resetwslist=False): - """ Reset GUI including all text edits and etc. + """ Reset GUI including all text edits and etc. """ if resetfilerun is True: self.ui.lineEdit.clear() @@ -1231,7 +1231,7 @@ def _resetGUI(self, resetfilerun=False, resetwslist=False): ylim = self.ui.mainplot.get_ylim() miny = ylim[0] maxy = ylim[1] - xlim = self.ui.mainplot.get_xlim() + xlim = self.ui.mainplot.get_xlim() setp(self.lowerslideline, xdata=xlim, ydata=[miny, miny]) setp(self.upperslideline, xdata=xlim, ydata=[maxy, maxy]) self.ui.graphicsView.draw() @@ -1251,7 +1251,7 @@ def _resetGUI(self, resetfilerun=False, resetwslist=False): self.ui.checkBox_doParallel.setCheckState(False) self.ui.comboBox_skipSpectrum.setCurrentIndex(0) - + self.ui.checkBox_filterByPulse.setCheckState(False) self.ui.checkBox_from1.setCheckState(False) self.ui.checkBox_groupWS.setCheckState(True) diff --git a/Code/Mantid/scripts/Inelastic/Direct/CommonFunctions.py b/Code/Mantid/scripts/Inelastic/Direct/CommonFunctions.py index 478deaad9031..26d5a8e749fb 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/CommonFunctions.py +++ b/Code/Mantid/scripts/Inelastic/Direct/CommonFunctions.py @@ -7,7 +7,7 @@ class switch(object): - """ Helper class providing nice switch statement""" + """ Helper class providing nice switch statement""" def __init__(self, value): self.value = value self.fall = False @@ -16,7 +16,7 @@ def __iter__(self): """Return the match method once, then stop""" yield self.match raise StopIteration - + def match(self, *args): """Indicate whether or not to enter a case suite""" if self.fall or not args: @@ -25,4 +25,4 @@ def match(self, *args): self.fall = True return True else: - return False \ No newline at end of file + return False diff --git a/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py b/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py index b8f8a243a226..34d660382b0c 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py +++ b/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py @@ -26,7 +26,7 @@ def setup_reducer(inst_name,reload_instrument=False): class DirectEnergyConversion(object): """ - Performs a convert to energy assuming the provided instrument is + Performs a convert to energy assuming the provided instrument is an direct inelastic geometry instrument The class defines various methods to allow users to convert their @@ -34,7 +34,7 @@ class DirectEnergyConversion(object): Usage: >>red = DirectEnergyConversion('InstrumentName') - and then: + and then: >>red.convert_to_energy(wb_run,sample_run,ei_guess,rebin) or >>red.convert_to_energy(wb_run,sample_run,ei_guess,rebin,**arguments) @@ -42,7 +42,7 @@ class DirectEnergyConversion(object): >>red.convert_to_energy(wb_run,sample_run,ei_guess,rebin,mapfile,**arguments) or >>red.prop_man.sample_run = run number - >>red.prop_man.wb_run = Whitebeam + >>red.prop_man.wb_run = Whitebeam >>red.prop_man.incident_energy = energy guess >>red.prop_man.energy_bins = [min_val,step,max_val] >>red.convert_to_energy() @@ -51,14 +51,14 @@ class DirectEnergyConversion(object): Whitebeam run number or file name or workspace sample_run sample run number or file name or workspace ei_guess suggested value for incident energy of neutrons in direct inelastic instrument - energy_bins energy binning requested for resulting spe workspace. + energy_bins energy binning requested for resulting spe workspace. mapfile Mapfile -- if absent/'default' the defaults from IDF are used monovan_run If present will do the absolute units normalization. Number of additional parameters specified in **kwargs is usually requested for this. If they are absent, program uses defaults, but the defaults (e.g. sample_mass or sample_rmm ) are usually incorrect for a particular run. arguments The dictionary containing additional keyword arguments. - The list of allowed additional arguments is defined in InstrName_Parameters.xml + The list of allowed additional arguments is defined in InstrName_Parameters.xml file, located in: MantidPlot->View->Preferences->Mantid->Directories->Parameter Definitions @@ -87,13 +87,13 @@ class DirectEnergyConversion(object): bkgd_range =[15000,19000] :integration range for background tests - second_white - If provided an additional set of tests is performed on this. + second_white - If provided an additional set of tests is performed on this. (default = None) hardmaskPlus - A file specifying those spectra that should be masked without testing (default=None) tiny - Minimum threshold for acceptance (default = 1e-10) large - Maximum threshold for acceptance (default = 1e10) - bkgd_range - A list of two numbers indicating the background range + bkgd_range - A list of two numbers indicating the background range (default=instrument defaults) diag_van_median_rate_limit_lo - Lower bound defining outliers as fraction of median value (default = 0.01) diag_van_median_rate_limit_hi - Upper bound defining outliers as fraction of median value (default = 100.) @@ -133,7 +133,7 @@ class DirectEnergyConversion(object): """ #------------------------------------------------------------------------------- def diagnose(self, white,diag_sample=None,**kwargs): - """ run diagnostics on the provided workspaces. + """ run diagnostics on the provided workspaces. this method does some additional processing before moving on to the diagnostics: 1) Computes the white beam integrals, converting to energy @@ -177,325 +177,325 @@ def diagnose(self, white,diag_sample=None,**kwargs): bleed_pixels - If the bleed test is on then this is the number of pixels ignored within the bleed test diagnostic """ - lhs_names = funcreturns.lhs_info('names') - if len(lhs_names) > 0: - var_name = lhs_names[0] - else: - var_name = "diag_mask" + lhs_names = funcreturns.lhs_info('names') + if len(lhs_names) > 0: + var_name = lhs_names[0] + else: + var_name = "diag_mask" # modify properties using input arguments - self.prop_man.set_input_parameters(**kwargs) + self.prop_man.set_input_parameters(**kwargs) # obtain proper run descriptor in case it is not a run descriptor but # something else - white = self.get_run_descriptor(white) + white = self.get_run_descriptor(white) # return all diagnostics parameters - diag_params = self.prop_man.get_diagnostics_parameters() + diag_params = self.prop_man.get_diagnostics_parameters() - if self.use_hard_mask_only: - if mtd.doesExist('hard_mask_ws'): - diag_mask = mtd['hard_mask_ws'] - else: # build hard mask + if self.use_hard_mask_only: + if mtd.doesExist('hard_mask_ws'): + diag_mask = mtd['hard_mask_ws'] + else: # build hard mask # in this peculiar way we can obtain working mask which # accounts for initial data grouping in the # data file. SNS or 1 to 1 maps may probably avoid this # stuff and can load masks directly - white_data = white.get_ws_clone('white_ws_clone') + white_data = white.get_ws_clone('white_ws_clone') - diag_mask = LoadMask(Instrument=self.instr_name,InputFile=self.hard_mask_file, + diag_mask = LoadMask(Instrument=self.instr_name,InputFile=self.hard_mask_file, OutputWorkspace='hard_mask_ws') - MaskDetectors(Workspace=white_data, MaskedWorkspace=diag_mask) - DeleteWorkspace(diag_mask) - diag_mask,masked_list = ExtractMask(InputWorkspace=white_data) - DeleteWorkspace(Workspace='white_ws_clone') + MaskDetectors(Workspace=white_data, MaskedWorkspace=diag_mask) + DeleteWorkspace(diag_mask) + diag_mask,masked_list = ExtractMask(InputWorkspace=white_data) + DeleteWorkspace(Workspace='white_ws_clone') - return diag_mask + return diag_mask # Get the white beam vanadium integrals - whiteintegrals = self.do_white(white, None, None) # No grouping yet - if self.second_white: - second_white = self.second_white - other_whiteintegrals = self.do_white(PropertyManager.second_white, None, None) # No grouping yet - self.second_white = other_whiteintegrals + whiteintegrals = self.do_white(white, None, None) # No grouping yet + if self.second_white: + second_white = self.second_white + other_whiteintegrals = self.do_white(PropertyManager.second_white, None, None) # No grouping yet + self.second_white = other_whiteintegrals # Get the background/total counts from the sample run if present - if diag_sample: - diag_sample = self.get_run_descriptor(diag_sample) + if diag_sample: + diag_sample = self.get_run_descriptor(diag_sample) # If the bleed test is requested then we need to pass in the # sample_run as well - if self.bleed_test: + if self.bleed_test: # initiate reference to reducer to be able to work with Run # Descriptors - diagnostics.__Reducer__ = self - diag_params['sample_run'] = diag_sample + diagnostics.__Reducer__ = self + diag_params['sample_run'] = diag_sample # Set up the background integrals for diagnostic purposes - result_ws = self.normalise(diag_sample, self.normalise_method) + result_ws = self.normalise(diag_sample, self.normalise_method) #>>> here result workspace is being processed -- not touching #result ws - bkgd_range = self.background_test_range - background_int = Integration(result_ws, + bkgd_range = self.background_test_range + background_int = Integration(result_ws, RangeLower=bkgd_range[0],RangeUpper=bkgd_range[1], IncludePartialBins=True) - total_counts = Integration(result_ws, IncludePartialBins=True) - background_int = ConvertUnits(background_int, Target="Energy",EMode='Elastic', AlignBins=0) - self.prop_man.log("Diagnose: finished convertUnits ",'information') + total_counts = Integration(result_ws, IncludePartialBins=True) + background_int = ConvertUnits(background_int, Target="Energy",EMode='Elastic', AlignBins=0) + self.prop_man.log("Diagnose: finished convertUnits ",'information') - background_int *= self.scale_factor - diagnostics.normalise_background(background_int, whiteintegrals, + background_int *= self.scale_factor + diagnostics.normalise_background(background_int, whiteintegrals, diag_params.get('second_white',None)) - diag_params['background_int'] = background_int - diag_params['sample_counts'] = total_counts + diag_params['background_int'] = background_int + diag_params['sample_counts'] = total_counts # Check how we should run diag - diag_spectra_blocks = self.diag_spectra - if diag_spectra_blocks is None: + diag_spectra_blocks = self.diag_spectra + if diag_spectra_blocks is None: # Do the whole lot at once - diagnostics.diagnose(whiteintegrals, **diag_params) - else: - for index, bank in enumerate(diag_spectra_blocks): - diag_params['start_index'] = bank[0] - 1 - diag_params['end_index'] = bank[1] - 1 - diagnostics.diagnose(whiteintegrals, **diag_params) - - if 'sample_counts' in diag_params: - DeleteWorkspace(Workspace='background_int') - DeleteWorkspace(Workspace='total_counts') - if 'second_white' in diag_params: - DeleteWorkspace(Workspace=diag_params['second_white']) + diagnostics.diagnose(whiteintegrals, **diag_params) + else: + for index, bank in enumerate(diag_spectra_blocks): + diag_params['start_index'] = bank[0] - 1 + diag_params['end_index'] = bank[1] - 1 + diagnostics.diagnose(whiteintegrals, **diag_params) + + if 'sample_counts' in diag_params: + DeleteWorkspace(Workspace='background_int') + DeleteWorkspace(Workspace='total_counts') + if 'second_white' in diag_params: + DeleteWorkspace(Workspace=diag_params['second_white']) # Extract a mask workspace - diag_mask, det_ids = ExtractMask(InputWorkspace=whiteintegrals,OutputWorkspace=var_name) + diag_mask, det_ids = ExtractMask(InputWorkspace=whiteintegrals,OutputWorkspace=var_name) - DeleteWorkspace(Workspace=whiteintegrals) + DeleteWorkspace(Workspace=whiteintegrals) #TODO do we need this? #self.spectra_masks = diag_mask - return diag_mask + return diag_mask #------------------------------------------------------------------------------- def convert_to_energy(self,wb_run=None,sample_run=None,ei_guess=None,rebin=None,map_file=None, monovan_run=None,wb_for_monovan_run=None,**kwargs): - """ One step conversion of run into workspace containing information about energy transfer + """ One step conversion of run into workspace containing information about energy transfer - """ + """ # Support for old reduction interface: - self.prop_man.set_input_parameters_ignore_nan\ + self.prop_man.set_input_parameters_ignore_nan\ (wb_run=wb_run,sample_run=sample_run,incident_energy=ei_guess,energy_bins=rebin, map_file=map_file,monovan_run=monovan_run,wb_for_monovan_run=wb_for_monovan_run) # - self.prop_man.set_input_parameters(**kwargs) + self.prop_man.set_input_parameters(**kwargs) # output workspace name. - try: - n,r = funcreturns.lhs_info('both') - out_ws_name = r[0] - except: - out_ws_name = None + try: + n,r = funcreturns.lhs_info('both') + out_ws_name = r[0] + except: + out_ws_name = None # inform user on what parameters have changed from script or gui # if monovan present, check if abs_norm_ parameters are set - self.prop_man.log_changed_values('notice') - prop_man = self.prop_man + self.prop_man.log_changed_values('notice') + prop_man = self.prop_man #process complex parameters - start_time = time.time() + start_time = time.time() # check if reducer can find all non-run files necessary for the reduction # before starting long run. #TODO: # Reducer.check_necessary_files(monovan_run) - PropertyManager.sample_run.set_action_suffix('') - sample_ws = PropertyManager.sample_run.get_workspace() + PropertyManager.sample_run.set_action_suffix('') + sample_ws = PropertyManager.sample_run.get_workspace() # Update reduction properties which may change in the workspace but have # not been modified from input parameters. # E.g. detector number have changed - oldChanges = self.prop_man.getChangedProperties() - allChanges = self.prop_man.update_defaults_from_instrument(sample_ws.getInstrument()) - workspace_defined_prop = allChanges.difference(oldChanges) - if len(workspace_defined_prop) > 0: - prop_man.log("****************************************************************") - prop_man.log('*** Sample run {0} properties change default reduction properties: '.\ + oldChanges = self.prop_man.getChangedProperties() + allChanges = self.prop_man.update_defaults_from_instrument(sample_ws.getInstrument()) + workspace_defined_prop = allChanges.difference(oldChanges) + if len(workspace_defined_prop) > 0: + prop_man.log("****************************************************************") + prop_man.log('*** Sample run {0} properties change default reduction properties: '.\ format(PropertyManager.sample_run.get_ws_name())) - prop_man.log_changed_values('notice',False,oldChanges) - prop_man.log("****************************************************************") + prop_man.log_changed_values('notice',False,oldChanges) + prop_man.log("****************************************************************") - masking = None - masks_done = False - if not prop_man.run_diagnostics: - header = "*** Diagnostics including hard masking is skipped " - masks_done = True + masking = None + masks_done = False + if not prop_man.run_diagnostics: + header = "*** Diagnostics including hard masking is skipped " + masks_done = True #if Reducer.save_and_reuse_masks : # SAVE AND REUSE MASKS - if self.spectra_masks: - masks_done = True + if self.spectra_masks: + masks_done = True #-------------------------------------------------------------------------------------------------- # Diagnostics here # ------------------------------------------------------------------------------------------------- # diag the sample and detector vanadium. It will deal with hard mask only # if it is set that way - if not masks_done: - prop_man.log("======== Run diagnose for sample run ===========================",'notice') - masking = self.diagnose(PropertyManager.wb_run,PropertyManager.mask_run, + if not masks_done: + prop_man.log("======== Run diagnose for sample run ===========================",'notice') + masking = self.diagnose(PropertyManager.wb_run,PropertyManager.mask_run, second_white=None,print_diag_results=True) - if prop_man.use_hard_mask_only: - header = "*** Hard mask file applied to workspace with {0:d} spectra masked {1:d} spectra" - else: - header = "*** Diagnostics processed workspace with {0:d} spectra and masked {1:d} bad spectra" + if prop_man.use_hard_mask_only: + header = "*** Hard mask file applied to workspace with {0:d} spectra masked {1:d} spectra" + else: + header = "*** Diagnostics processed workspace with {0:d} spectra and masked {1:d} bad spectra" # diagnose absolute units: - if self.monovan_run != None : - if self.mono_correction_factor == None : - if self.use_sam_msk_on_monovan == True: - prop_man.log(' Applying sample run mask to mono van') - else: - if not self.use_hard_mask_only : # in this case the masking2 is different but + if self.monovan_run != None : + if self.mono_correction_factor == None : + if self.use_sam_msk_on_monovan == True: + prop_man.log(' Applying sample run mask to mono van') + else: + if not self.use_hard_mask_only : # in this case the masking2 is different but #points to the same #workspace # Should be better # solution for that. - prop_man.log("======== Run diagnose for monochromatic vanadium run ===========",'notice') + prop_man.log("======== Run diagnose for monochromatic vanadium run ===========",'notice') - masking2 = self.diagnose(PropertyManager.wb_for_monovan_run,PropertyManager.monovan_run, + masking2 = self.diagnose(PropertyManager.wb_for_monovan_run,PropertyManager.monovan_run, second_white = None,print_diag_results=True) - masking += masking2 - DeleteWorkspace(masking2) + masking += masking2 + DeleteWorkspace(masking2) - else: # if Reducer.mono_correction_factor != None : - pass + else: # if Reducer.mono_correction_factor != None : + pass # Very important statement propagating masks for further usage in # convert_to_energy. # This property is also directly accessible from GUI. - self.spectra_masks = masking + self.spectra_masks = masking # save mask if it does not exist and has been already loaded #if Reducer.save_and_reuse_masks and not masks_done: # SaveMask(InputWorkspace=masking,OutputFile = # mask_file_name,GroupedDetectors=True) - else: - header = '*** Using stored mask file for workspace with {0} spectra and {1} masked spectra' - masking = self.spectra_masks - + else: + header = '*** Using stored mask file for workspace with {0} spectra and {1} masked spectra' + masking = self.spectra_masks + # estimate and report the number of failing detectors - failed_sp_list,nMaskedSpectra = get_failed_spectra_list_from_masks(masking) - if masking: - nSpectra = masking.getNumberHistograms() - else: - nSpectra = 0 - prop_man.log(header.format(nSpectra,nMaskedSpectra),'notice') + failed_sp_list,nMaskedSpectra = get_failed_spectra_list_from_masks(masking) + if masking: + nSpectra = masking.getNumberHistograms() + else: + nSpectra = 0 + prop_man.log(header.format(nSpectra,nMaskedSpectra),'notice') #-------------------------------------------------------------------------------------------------- # now reduction #-------------------------------------------------------------------------------------------------- # SNS or GUI motor stuff - self.calculate_rotation(PropertyManager.sample_run.get_workspace()) + self.calculate_rotation(PropertyManager.sample_run.get_workspace()) # - if self.monovan_run != None: - MonovanCashNum = PropertyManager.monovan_run.run_number() - if self.mono_correction_factor: - calculate_abs_units = False # correction factor given, so no calculations - else: - calculate_abs_units = True - else: - MonovanCashNum = None - calculate_abs_units = False - PropertyManager.mono_correction_factor.set_cash_mono_run_number(MonovanCashNum) - - - if PropertyManager.incident_energy.multirep_mode(): - self._multirep_mode = True - ws_base = None - mono_ws_base = None - num_ei_cuts = len(self.incident_energy) - if self.check_background: + if self.monovan_run != None: + MonovanCashNum = PropertyManager.monovan_run.run_number() + if self.mono_correction_factor: + calculate_abs_units = False # correction factor given, so no calculations + else: + calculate_abs_units = True + else: + MonovanCashNum = None + calculate_abs_units = False + PropertyManager.mono_correction_factor.set_cash_mono_run_number(MonovanCashNum) + + + if PropertyManager.incident_energy.multirep_mode(): + self._multirep_mode = True + ws_base = None + mono_ws_base = None + num_ei_cuts = len(self.incident_energy) + if self.check_background: # find the count rate seen in the regions of the histograms # defined as the background regions, if the user defined such # region - ws_base = PropertyManager.sample_run.get_workspace() - bkgd_range = self.bkgd_range - bkgr_ws=self._find_or_build_bkgr_ws(ws_base,bkgd_range[0],bkgd_range[1]) - RenameWorkspace(InputWorkspace=bkgr_ws, OutputWorkspace='bkgr_ws_source') - # initialize list to store resulting workspaces to return - result = [] - else: - self._multirep_mode = False - num_ei_cuts = 0 - - cut_ind = 0 # do not do enumerate if it generates all sequence at once + ws_base = PropertyManager.sample_run.get_workspace() + bkgd_range = self.bkgd_range + bkgr_ws=self._find_or_build_bkgr_ws(ws_base,bkgd_range[0],bkgd_range[1]) + RenameWorkspace(InputWorkspace=bkgr_ws, OutputWorkspace='bkgr_ws_source') + # initialize list to store resulting workspaces to return + result = [] + else: + self._multirep_mode = False + num_ei_cuts = 0 + + cut_ind = 0 # do not do enumerate if it generates all sequence at once # -- code below uses current energy state from # PropertyManager.incident_energy - for ei_guess in PropertyManager.incident_energy: - cut_ind +=1 + for ei_guess in PropertyManager.incident_energy: + cut_ind +=1 #--------------- - if self._multirep_mode: - tof_range = self.find_tof_range_for_multirep(ws_base) - ws_base = PropertyManager.sample_run.chop_ws_part(ws_base,tof_range,self._do_early_rebinning,cut_ind,num_ei_cuts) - prop_man.log("*** Processing multirep chunk: #{0}/{1} for provisional energy: {2} meV".format(cut_ind,num_ei_cuts,ei_guess),'notice') + if self._multirep_mode: + tof_range = self.find_tof_range_for_multirep(ws_base) + ws_base = PropertyManager.sample_run.chop_ws_part(ws_base,tof_range,self._do_early_rebinning,cut_ind,num_ei_cuts) + prop_man.log("*** Processing multirep chunk: #{0}/{1} for provisional energy: {2} meV".format(cut_ind,num_ei_cuts,ei_guess),'notice') #--------------- #Run the conversion first on the sample - deltaE_ws_sample = self.mono_sample(PropertyManager.sample_run,ei_guess,PropertyManager.wb_run, + deltaE_ws_sample = self.mono_sample(PropertyManager.sample_run,ei_guess,PropertyManager.wb_run, self.map_file,masking) - + # calculate absolute units integral and apply it to the workspace - cashed_mono_int = PropertyManager.mono_correction_factor.get_val_from_cash(prop_man) - if MonovanCashNum != None or self.mono_correction_factor or cashed_mono_int : + cashed_mono_int = PropertyManager.mono_correction_factor.get_val_from_cash(prop_man) + if MonovanCashNum != None or self.mono_correction_factor or cashed_mono_int : # do not remove background from vanadium (sample background is not fit for that anyway) - current_bkg_opt = self.check_background - self.check_background= False - # what we want to do with absolute units: - if self.mono_correction_factor: # Correction provided. Just apply it - deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run, + current_bkg_opt = self.check_background + self.check_background= False + # what we want to do with absolute units: + if self.mono_correction_factor: # Correction provided. Just apply it + deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run, ei_guess,PropertyManager.wb_for_monovan_run) - elif cashed_mono_int: # Correction cashed from previous run - self.mono_correction_factor = cashed_mono_int - deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run, + elif cashed_mono_int: # Correction cashed from previous run + self.mono_correction_factor = cashed_mono_int + deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run, ei_guess,PropertyManager.wb_for_monovan_run) - self.mono_correction_factor = None - else: # Calculate corrections - if self._multirep_mode and calculate_abs_units: - mono_ws_base = PropertyManager.monovan_run.chop_ws_part(mono_ws_base,tof_range,self._do_early_rebinning, + self.mono_correction_factor = None + else: # Calculate corrections + if self._multirep_mode and calculate_abs_units: + mono_ws_base = PropertyManager.monovan_run.chop_ws_part(mono_ws_base,tof_range,self._do_early_rebinning, cut_ind,num_ei_cuts) - deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run, + deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run, ei_guess,PropertyManager.wb_for_monovan_run) - self.check_background = current_bkg_opt + self.check_background = current_bkg_opt # ensure that the sample_run name is intact with workspace - PropertyManager.sample_run.synchronize_ws(deltaE_ws_sample) + PropertyManager.sample_run.synchronize_ws(deltaE_ws_sample) # - ei = (deltaE_ws_sample.getRun().getLogData("Ei").value) + ei = (deltaE_ws_sample.getRun().getLogData("Ei").value) # PropertyManager.incident_energy.set_current(ei) # let's not do it -- # this makes subsequent calls to this method depend on # # previous calls - prop_man.log("*** Incident energy found for sample run: {0} meV".format(ei),'notice') + prop_man.log("*** Incident energy found for sample run: {0} meV".format(ei),'notice') # - self.save_results(deltaE_ws_sample) - if out_ws_name: - if self._multirep_mode: - result.append(deltaE_ws_sample) - else: # delete workspace if no output is requested - self.sample_run = None + self.save_results(deltaE_ws_sample) + if out_ws_name: + if self._multirep_mode: + result.append(deltaE_ws_sample) + else: # delete workspace if no output is requested + self.sample_run = None - results_name = deltaE_ws_sample.name() - if out_ws_name and not(self._multirep_mode): - if results_name != out_ws_name: - RenameWorkspace(InputWorkspace=results_name,OutputWorkspace=out_ws_name) - result = mtd[out_ws_name] - else: - pass + results_name = deltaE_ws_sample.name() + if out_ws_name and not(self._multirep_mode): + if results_name != out_ws_name: + RenameWorkspace(InputWorkspace=results_name,OutputWorkspace=out_ws_name) + result = mtd[out_ws_name] + else: + pass - end_time = time.time() - prop_man.log("*** Elapsed time = {0} sec".format(end_time - start_time),'notice') + end_time = time.time() + prop_man.log("*** Elapsed time = {0} sec".format(end_time - start_time),'notice') # Hack for multirep mode? # if mtd.doesExist('hard_mask_ws') == True: @@ -505,15 +505,15 @@ def convert_to_energy(self,wb_run=None,sample_run=None,ei_guess=None,rebin=None, # CLEAN-up (may be worth to do in separate procedure) # Currently clear masks unconditionally TODO: cash masks with appropriate # precautions - self.spectra_masks = None + self.spectra_masks = None #self.prop_man.wb_run = None # clean up memory of the wb run (only in #case of file based wb) - if 'bkgr_ws_source' in mtd: - DeleteWorkspace('bkgr_ws_source') + if 'bkgr_ws_source' in mtd: + DeleteWorkspace('bkgr_ws_source') - return result + return result def do_white(self, run, spectra_masks=None, map_file=None): """ @@ -552,7 +552,7 @@ def mono_sample(self, mono_run, ei_guess, white_run=None, map_file=None, #------------------------------------------------------------------------------- def calculate_rotation(self,sample_wkspace,motor=None, offset=None): """calculate psi from sample environment motor and offset - + TODO: should probably go to properties """ @@ -575,7 +575,7 @@ def calculate_rotation(self,sample_wkspace,motor=None, offset=None): self.prop_man.log("Could not find such sample environment log. Will use psi=motor_offset") motor_rotation = 0 else: - motor_rotation = float('nan') + motor_rotation = float('nan') self.prop_man.psi = motor_rotation + motor_offset #------------------------------------------------------------------------------- def get_ei(self, data_run, ei_guess): @@ -596,7 +596,7 @@ def get_ei(self, data_run, ei_guess): data_ws = data_run.get_workspace() monitor_ws = data_run.get_monitors_ws() if not monitor_ws: - raise RuntimeError("Can not find monitors workspace for workspace {0}, run N{1}".\ + raise RuntimeError("Can not find monitors workspace for workspace {0}, run N{1}".\ format(data_ws.name(),data_ws.getRunNumber())) separate_monitors = data_run.is_monws_separate() data_run.set_action_suffix('_shifted') @@ -622,8 +622,8 @@ def get_ei(self, data_run, ei_guess): # instrument is shifted in case it is shifted to this monitor (usual # case) #Find TOF range, correspondent to incident energy monitor peak - energy_rage = self.mon2_norm_energy_range - self._mon2_norm_time_range = self.get_TOF_for_energies(monitor_ws,energy_rage, + energy_rage = self.mon2_norm_energy_range + self._mon2_norm_time_range = self.get_TOF_for_energies(monitor_ws,energy_rage, [self.mon2_norm_spec],None,self._debug_mode) #end if separate_monitors: @@ -638,13 +638,13 @@ def get_ei(self, data_run, ei_guess): InstrumentParameter="DelayTime",Combine=True) # shift to monitor used to calculate energy transfer - spec_num = monitor_ws.getIndexFromSpectrumNumber(int(ei_mon_spectra[0])) + spec_num = monitor_ws.getIndexFromSpectrumNumber(int(ei_mon_spectra[0])) mon1_det = monitor_ws.getDetector(spec_num) mon1_pos = mon1_det.getPos() src_name = data_ws.getInstrument().getSource().getName() - MoveInstrumentComponent(Workspace=resultws_name,ComponentName= src_name, X=mon1_pos.getX(), + MoveInstrumentComponent(Workspace=resultws_name,ComponentName= src_name, X=mon1_pos.getX(), Y=mon1_pos.getY(), Z=mon1_pos.getZ(), RelativePosition=False) - + # data_run.synchronize_ws(mtd[resultws_name]) return ei, mon1_peak @@ -685,16 +685,16 @@ def normalise(self, run, method, range_offset=0.0,external_monitors_ws=None): method = method.lower() for case in common.switch(method): if case('monitor-1'): - method,old_ws_name = self._normalize_to_monitor1(run,old_ws_name, range_offset,external_monitors_ws) - break + method,old_ws_name = self._normalize_to_monitor1(run,old_ws_name, range_offset,external_monitors_ws) + break if case('monitor-2'): - method,old_ws_name = self._normalize_to_monitor2(run,old_ws_name, range_offset,external_monitors_ws) - break + method,old_ws_name = self._normalize_to_monitor2(run,old_ws_name, range_offset,external_monitors_ws) + break if case('current'): NormaliseByCurrent(InputWorkspace=old_ws_name,OutputWorkspace=old_ws_name) break if case(): # default - raise RuntimeError('Normalization method {0} not found. It must be one of monitor-1, monitor-2, current, or None'.format(method)) + raise RuntimeError('Normalization method {0} not found. It must be one of monitor-1, monitor-2, current, or None'.format(method)) #endCase @@ -706,32 +706,32 @@ def normalise(self, run, method, range_offset=0.0,external_monitors_ws=None): return output # def _normalize_to_monitor1(self,run,old_name,range_offset=0.0,external_monitor_ws=None): - """ Helper method implementing normalize_to_monitor1 """ + """ Helper method implementing normalize_to_monitor1 """ # get monitor's workspace separate_monitors = run.is_monws_separate() if external_monitor_ws: - separate_monitors = True - mon_ws = external_monitor_ws + separate_monitors = True + mon_ws = external_monitor_ws else: - mon_ws = run.get_monitors_ws() + mon_ws = run.get_monitors_ws() if not mon_ws: # no monitors - if self.__in_white_normalization: # we can normalize wb integrals by current separately as they often do not + if self.__in_white_normalization: # we can normalize wb integrals by current separately as they often do not # have monitors - self.normalise(run,'current',range_offset) - new_name = run.get_ws_name() - return ('current',new_name) - else: - raise RuntimeError('Normalise by monitor-1:: Workspace {0} for run {1} does not have monitors in it'\ + self.normalise(run,'current',range_offset) + new_name = run.get_ws_name() + return ('current',new_name) + else: + raise RuntimeError('Normalise by monitor-1:: Workspace {0} for run {1} does not have monitors in it'\ .format(run.get_ws_name(),run.__get__())) range = self.norm_mon_integration_range if self._debug_mode: - kwargs = {'NormFactorWS':'NormMon1_WS' + data_ws.getName()} + kwargs = {'NormFactorWS':'NormMon1_WS' + data_ws.getName()} else: - kwargs = {} + kwargs = {} mon_spect = self.prop_man.mon1_norm_spec if separate_monitors: @@ -746,36 +746,36 @@ def _normalize_to_monitor1(self,run,old_name,range_offset=0.0,external_monitor_w - NormaliseToMonitor(InputWorkspace=old_name,OutputWorkspace=old_name, IntegrationRangeMin=range_min, + NormaliseToMonitor(InputWorkspace=old_name,OutputWorkspace=old_name, IntegrationRangeMin=range_min, IntegrationRangeMax=range_max,IncludePartialBins=True,**kwargs) return ('monitor-1',old_name) # def _normalize_to_monitor2(self,run,old_name, range_offset=0.0,external_monitor_ws=None): - """ Helper method implementing normalize_to_monitor_2 """ + """ Helper method implementing normalize_to_monitor_2 """ # get monitor's workspace separate_monitors = run.is_monws_separate() if external_monitor_ws: - separate_monitors = True - mon_ws = external_monitor_ws + separate_monitors = True + mon_ws = external_monitor_ws else: - mon_ws = run.get_monitors_ws() + mon_ws = run.get_monitors_ws() + - if not mon_ws: # no monitors - if self.__in_white_normalization: # we can normalize wb integrals by current separately as they often do not + if self.__in_white_normalization: # we can normalize wb integrals by current separately as they often do not # have monitors - self.normalise(run,'current',range_offset) - new_name = run.get_ws_name() - return ('current',new_name) - else: - raise RuntimeError('Normalize by monitor-2:: Workspace {0} for run {1} does not have monitors in it'\ + self.normalise(run,'current',range_offset) + new_name = run.get_ws_name() + return ('current',new_name) + else: + raise RuntimeError('Normalize by monitor-2:: Workspace {0} for run {1} does not have monitors in it'\ .format(run.get_ws_name(),run.__get__())) # if self._debug_mode: - kwargs = {'NormFactorWS':'NormMon2_WS' + mon_ws.getName()} + kwargs = {'NormFactorWS':'NormMon2_WS' + mon_ws.getName()} else: - kwargs = {} + kwargs = {} mon_spect = self.prop_man.mon2_norm_spec mon_index = int(mon_ws.getIndexFromSpectrumNumber(mon_spect)) @@ -787,36 +787,36 @@ def _normalize_to_monitor2(self,run,old_name, range_offset=0.0,external_monitor_ #Find TOF range, correspondent to incident energy monitor peak if self._mon2_norm_time_range: # range has been found during ei-calculations - range = self._mon2_norm_time_range - range_min = range[0] + range_offset - range_max = range[1] + range_offset - self._mon2_norm_time_range = None + range = self._mon2_norm_time_range + range_min = range[0] + range_offset + range_max = range[1] + range_offset + self._mon2_norm_time_range = None else: - mon_ws_name = mon_ws.name() #monitor's workspace and detector's workspace are e - if mon_ws_name.find('_shifted') != -1: + mon_ws_name = mon_ws.name() #monitor's workspace and detector's workspace are e + if mon_ws_name.find('_shifted') != -1: # monitor-2 normalization ranges have to be identified before the # instrument is shifted - raise RuntimeError("Instrument have been shifted but no time range has been identified. Monitor-2 normalization can not be performed ") - else: + raise RuntimeError("Instrument have been shifted but no time range has been identified. Monitor-2 normalization can not be performed ") + else: # instrument and workspace shifted, so TOF will be calculated wrt # shifted instrument - energy_rage = self.mon2_norm_energy_range - TOF_range = self.get_TOF_for_energies(mon_ws,energy_rage,[mon_spect],None,self._debug_mode) - range_min = TOF_range[0] - range_max = TOF_range[1] + energy_rage = self.mon2_norm_energy_range + TOF_range = self.get_TOF_for_energies(mon_ws,energy_rage,[mon_spect],None,self._debug_mode) + range_min = TOF_range[0] + range_max = TOF_range[1] # Normalize to monitor 2 - NormaliseToMonitor(InputWorkspace=old_name,OutputWorkspace=old_name,IntegrationRangeMin=range_min, + NormaliseToMonitor(InputWorkspace=old_name,OutputWorkspace=old_name,IntegrationRangeMin=range_min, IntegrationRangeMax=range_max,IncludePartialBins=True,**kwargs) return ('monitor-2',old_name) #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- def find_tof_range_for_multirep(self,workspace): - """ Find range of tof-s (and time bin size) corresponding to the + """ Find range of tof-s (and time bin size) corresponding to the energy range requested - """ + """ if not workspace: - workspace = PropertyManager.sample_run.get_workspace() + workspace = PropertyManager.sample_run.get_workspace() spectra_id = self.prop_man.multirep_tof_specta_list if not spectra_id: @@ -839,32 +839,32 @@ def process_block(tof_range): nBlocks = len(spectra_id) if nBlocks > 1: - tof_min,t_step,tof_max = process_block(TOF_range[0]) - for ind in xrange(1,nBlocks): - tof_min1,t_step1,tof_max1 = process_block(TOF_range[ind]) - tof_min = min(tof_min,tof_min1) - tof_max = max(tof_max,tof_max1) - t_step = min(t_step,t_step1) + tof_min,t_step,tof_max = process_block(TOF_range[0]) + for ind in xrange(1,nBlocks): + tof_min1,t_step1,tof_max1 = process_block(TOF_range[ind]) + tof_min = min(tof_min,tof_min1) + tof_max = max(tof_max,tof_max1) + t_step = min(t_step,t_step1) else: - tof_min,t_step,tof_max = process_block(TOF_range) + tof_min,t_step,tof_max = process_block(TOF_range) #end return (tof_min,t_step,tof_max) # @staticmethod def get_TOF_for_energies(workspace,energy_list,specID_list,ei=None,debug_mode=False): - """ Method to find what TOF range corresponds to given energy range + """ Method to find what TOF range corresponds to given energy range for given workspace and detectors. Input: - workspace pointer to workspace with instrument attached. + workspace pointer to workspace with instrument attached. energy_list the list of input energies to process - detID_list list of detectors to find - ei incident energy. If present, TOF range is calculated in direct mode, + detID_list list of detectors to find + ei incident energy. If present, TOF range is calculated in direct mode, if not -- elastic mode - Returns: - list of TOF corresponding to input energies list. - """ + Returns: + list of TOF corresponding to input energies list. + """ template_ws_name = '_energy_range_ws' range_ws_name = '_TOF_range_ws' y = [1] * (len(energy_list) - 1) @@ -913,8 +913,8 @@ def save_results(self, workspace, save_file=None, formats=None): else: pass - prop_man = self.prop_man - + prop_man = self.prop_man + save_file,ext = os.path.splitext(save_file) if len(ext) > 1: formats.add(ext[1:]) @@ -923,27 +923,27 @@ def save_results(self, workspace, save_file=None, formats=None): for file_format in formats: for case in common.switch(file_format): if case('nxspe'): - filename = save_file + '.nxspe' - name_supported = name_orig.replace('/','of') - if name_supported != name_orig: - RenameWorkspace(InputWorkspace=name_orig,OutputWorkspace=name_supported) - SaveNXSPE(InputWorkspace=name_supported,Filename= filename, KiOverKfScaling=prop_man.apply_kikf_correction,psi=prop_man.psi) - if name_supported != name_orig: - RenameWorkspace(InputWorkspace=name_supported,OutputWorkspace=name_orig) - break + filename = save_file + '.nxspe' + name_supported = name_orig.replace('/','of') + if name_supported != name_orig: + RenameWorkspace(InputWorkspace=name_orig,OutputWorkspace=name_supported) + SaveNXSPE(InputWorkspace=name_supported,Filename= filename, KiOverKfScaling=prop_man.apply_kikf_correction,psi=prop_man.psi) + if name_supported != name_orig: + RenameWorkspace(InputWorkspace=name_supported,OutputWorkspace=name_orig) + break if case('spe'): - filename = save_file + '.spe' - SaveSPE(InputWorkspace=workspace,Filename= filename) - break + filename = save_file + '.spe' + SaveSPE(InputWorkspace=workspace,Filename= filename) + break if case('nxs'): - filename = save_file + '.nxs' - SaveNexus(InputWorkspace=workspace,Filename= filename) - break + filename = save_file + '.nxs' + SaveNexus(InputWorkspace=workspace,Filename= filename) + break if case(): # default, could also just omit condition or 'if True' - prop_man.log("Unknown file format {0} requested to save results. No saving performed this format".format(file_format)) + prop_man.log("Unknown file format {0} requested to save results. No saving performed this format".format(file_format)) ######### - @property + @property def prop_man(self): """ Return property manager containing DirectEnergyConversion parameters """ return self._propMan @@ -958,7 +958,7 @@ def prop_man(self,value): ######### @property def spectra_masks(self): - """ The property keeps a workspace with masks, stored for further usage """ + """ The property keeps a workspace with masks, stored for further usage """ # check if spectra masks is defined if hasattr(self,'_spectra_masks'): @@ -968,7 +968,7 @@ def spectra_masks(self): @spectra_masks.setter def spectra_masks(self,value): - """ set up spectra masks """ + """ set up spectra masks """ self._spectra_masks = value #------------------------------------------------------------------------------- def apply_absolute_normalization(self,sample_ws,monovan_run=None,ei_guess=None,wb_mono=None): @@ -1017,7 +1017,7 @@ def apply_absolute_normalization(self,sample_ws,monovan_run=None,ei_guess=None,w # workspace is not good for further processing any more mono_run_num = PropertyManager.monovan_run.run_number() prop_man.monovan_run = None # delete everything from memory - prop_man.monovan_run = mono_run_num + prop_man.monovan_run = mono_run_num #end prop_man.log('*** Using {0} value : {1} of absolute units correction factor (TGP)'.format(abs_norm_factor_is,absnorm_factor),'notice') prop_man.log('*******************************************************************************************','notice') @@ -1053,30 +1053,30 @@ def get_abs_normalization_factor(self,deltaE_wkspaceName,ei_monovan): data_ws = Integration(InputWorkspace=deltaE_wkspaceName,OutputWorkspace='van_int',RangeLower=minmax[0],RangeUpper=minmax[1],IncludePartialBins='1') - + nhist = data_ws.getNumberHistograms() # extract wb integrals for combined spectra signal = [] error = [] izerc = 0 for i in range(nhist): - try: - det = data_ws.getDetector(i) - except Exception: - continue - if det.isMasked(): - continue - sig = data_ws.readY(i)[0] - err = data_ws.readE(i)[0] - if sig != sig: #ignore NaN (hopefully it will mean mask some day) - continue - if ((err <= 0) or (sig <= 0)): # count Inf and negative||zero readings. Presence of this indicates that + try: + det = data_ws.getDetector(i) + except Exception: + continue + if det.isMasked(): + continue + sig = data_ws.readY(i)[0] + err = data_ws.readE(i)[0] + if sig != sig: #ignore NaN (hopefully it will mean mask some day) + continue + if ((err <= 0) or (sig <= 0)): # count Inf and negative||zero readings. Presence of this indicates that # something went wrong - izerc+=1 - continue + izerc+=1 + continue - signal.append(sig) - error.append(err) + signal.append(sig) + error.append(err) #---------------- Loop finished norm_factor = {} @@ -1135,11 +1135,11 @@ def get_abs_normalization_factor(self,deltaE_wkspaceName,ei_monovan): # check for NaN if (norm_factor['LibISIS'] != norm_factor['LibISIS']) | (izerc != 0): # It is an error, print diagnostics: - if (norm_factor['LibISIS'] != norm_factor['LibISIS']): - log_value = '\n--------> Absolute normalization factor is NaN <----------------------------------------------\n' - else: - log_value = '\n--------> Warning, Monovanadium has zero spectra <--------------------------------------------\n' - log1_value = \ + if (norm_factor['LibISIS'] != norm_factor['LibISIS']): + log_value = '\n--------> Absolute normalization factor is NaN <----------------------------------------------\n' + else: + log_value = '\n--------> Warning, Monovanadium has zero spectra <--------------------------------------------\n' + log1_value = \ "--------> Processing workspace: {0}\n"\ "--------> Monovan Integration range : min={1}, max={2} (meV)\n"\ "--------> Summed: {3} spectra with total signal: {4} and error: {5}\n"\ @@ -1151,8 +1151,8 @@ def get_abs_normalization_factor(self,deltaE_wkspaceName,ei_monovan): "--------> Abs norm factors: TGP : {11}\n"\ .format(deltaE_wkspaceName,minmax[0],minmax[1],nhist,sum(signal),sum(error),izerc,scale_factor, norm_factor['LibISIS'],norm_factor['SigSq'],norm_factor['Poisson'],norm_factor['TGP']) - log_value = log_value + log1_value - propman.log(log_value,'error') + log_value = log_value + log1_value + propman.log(log_value,'error') else: if not self._debug_mode: DeleteWorkspace(Workspace=deltaE_wkspaceName) @@ -1195,14 +1195,14 @@ def __init__(self, instr_name=None,reload_instrument=False): #end def __getattr__(self,attr_name): - """ overloaded to return values of properties non-existing in the class dictionary + """ overloaded to return values of properties non-existing in the class dictionary from the property manager class except this property already have descriptor in self class - """ - if attr_name in self._descriptors: - return object.__getattr__(self,attr_name) - else: - return getattr(self._propMan,attr_name) + """ + if attr_name in self._descriptors: + return object.__getattr__(self,attr_name) + else: + return getattr(self._propMan,attr_name) def __setattr__(self,attr_name,attr_value): """ overloaded to prohibit adding non-starting with _properties to the class instance @@ -1216,7 +1216,7 @@ def __setattr__(self,attr_name,attr_value): object.__setattr__(self,attr_name,attr_value) else: setattr(self._propMan,attr_name,attr_value) - + def initialise(self, instr,reload_instrument=False): """ Initialize the private attributes of the class and the nullify the attributes which expected @@ -1259,20 +1259,20 @@ def setup_instrument_properties(self, workspace=None,reload_instrument=False): instrument = workspace.getInstrument() name = instrument.getName() if name != self.prop_man.instr_name: - self.prop_man = PropertyManager(name,workspace) + self.prop_man = PropertyManager(name,workspace) + - def get_run_descriptor(self,run): - """ Spawn temporary run descriptor for input data given in format, - different from run descriptor. Return existing run descriptor, + """ Spawn temporary run descriptor for input data given in format, + different from run descriptor. Return existing run descriptor, if it is what provided. """ - if not isinstance(run,RunDescriptor): - tRun = copy.copy(PropertyManager._tmp_run) - tRun.__set__(None,run) - return tRun - else: - return run + if not isinstance(run,RunDescriptor): + tRun = copy.copy(PropertyManager._tmp_run) + tRun.__set__(None,run) + return tRun + else: + return run # # ------------------------------------------------------------------------------------------- # This actually does the conversion for the mono-sample and @@ -1333,10 +1333,10 @@ def _do_mono_ISIS(self, data_run, ei_guess, energy_bins = PropertyManager.energy_bins.get_abs_range(self.prop_man) if energy_bins: - Rebin(InputWorkspace=result_name,OutputWorkspace=result_name,Params= energy_bins,PreserveEvents=False) - if bkgr_ws: # remove background after converting units and rebinning - RemoveBackground(InputWorkspace=result_name,OutputWorkspace=result_name,BkgWorkspace=bkgr_ws,EMode='Direct') - DeleteWorkspace(bkgr_ws) + Rebin(InputWorkspace=result_name,OutputWorkspace=result_name,Params= energy_bins,PreserveEvents=False) + if bkgr_ws: # remove background after converting units and rebinning + RemoveBackground(InputWorkspace=result_name,OutputWorkspace=result_name,BkgWorkspace=bkgr_ws,EMode='Direct') + DeleteWorkspace(bkgr_ws) else: pass # TODO: investigate way of removing background from event workspace if we want # result to be an event workspace @@ -1345,35 +1345,35 @@ def _do_mono_ISIS(self, data_run, ei_guess, if self.apply_detector_eff and energy_bins: #should detector efficiency work on event workspace too? At the moment it is #not (01/02/2015) - DetectorEfficiencyCor(InputWorkspace=result_name,OutputWorkspace=result_name) - self.prop_man.log("_do_mono: finished DetectorEfficiencyCor for : " + result_name,'information') + DetectorEfficiencyCor(InputWorkspace=result_name,OutputWorkspace=result_name) + self.prop_man.log("_do_mono: finished DetectorEfficiencyCor for : " + result_name,'information') ############# data_run.synchronize_ws(mtd[result_name]) - return + return #------------------------------------------------------------------------------- def _find_or_build_bkgr_ws(self,result_ws,bkg_range_min=None,bkg_range_max=None,time_shift=0): - """ Method calculates background workspace or restore workspace with + """ Method calculates background workspace or restore workspace with the same name as the one produced by this method from ADS - """ + """ if not bkg_range_min or not bkg_range_max: bkg_range_min,bkg_range_max = self.bkgd_range bkg_range_min += time_shift bkg_range_max += time_shift - # has to have specific name for this all working. This ws is build at the beginning of + # has to have specific name for this all working. This ws is build at the beginning of # multirep run if 'bkgr_ws_source' in mtd: bkgr_ws = CloneWorkspace(InputWorkspace='bkgr_ws_source',OutputWorkspace='bkgr_ws') - if time_shift != 0: # Workspace has probably been shifted, so to have correct units conversion + if time_shift != 0: # Workspace has probably been shifted, so to have correct units conversion # one needs to do appropriate shift here as well - CopyInstrumentParameters(result_ws,bkgr_ws) + CopyInstrumentParameters(result_ws,bkgr_ws) # Adjust the TOF such that the first monitor peak is at t=0 - ScaleX(InputWorkspace=bkgr_ws,OutputWorkspace='bkgr_ws',Operation="Add",Factor=time_shift, + ScaleX(InputWorkspace=bkgr_ws,OutputWorkspace='bkgr_ws',Operation="Add",Factor=time_shift, InstrumentParameter="DelayTime",Combine=True) else: - bkgr_ws = Rebin(result_ws,Params=[bkg_range_min,(bkg_range_max - bkg_range_min) * 1.001,bkg_range_max],PreserveEvents=False) - bkgr_ws = self.normalise(bkgr_ws, self.normalise_method, time_shift) + bkgr_ws = Rebin(result_ws,Params=[bkg_range_min,(bkg_range_max - bkg_range_min) * 1.001,bkg_range_max],PreserveEvents=False) + bkgr_ws = self.normalise(bkgr_ws, self.normalise_method, time_shift) return bkgr_ws @@ -1386,13 +1386,13 @@ def _do_mono(self, run, ei_guess, """ if (self._do_ISIS_reduction): - self._do_mono_ISIS(run,ei_guess, + self._do_mono_ISIS(run,ei_guess, white_run, map_file, spectra_masks, Tzero) else: - result_name = run.set_action_suffix('_spe') - self._do_mono_SNS(run,result_name,ei_guess, + result_name = run.set_action_suffix('_spe') + self._do_mono_SNS(run,result_name,ei_guess, white_run, map_file, spectra_masks, Tzero) - run.synchronize_ws() + run.synchronize_ws() prop_man = self.prop_man result_name = run.get_ws_name() @@ -1405,8 +1405,8 @@ def _do_mono(self, run, ei_guess, # Make sure that our binning is consistent if prop_man.energy_bins: - bins = PropertyManager.energy_bins.get_abs_range(prop_man) - Rebin(InputWorkspace=result_name,OutputWorkspace= result_name,Params=bins) + bins = PropertyManager.energy_bins.get_abs_range(prop_man) + Rebin(InputWorkspace=result_name,OutputWorkspace= result_name,Params=bins) # Masking and grouping result_ws = mtd[result_name] @@ -1442,12 +1442,12 @@ def _get_wb_inegrals(self,run): old_log_val = targ_ws.getRun().getLogData(done_Log).value done_log_VAL = self._build_white_tag() if old_log_val == done_log_VAL: - run.synchronize_ws(targ_ws) - if self._keep_wb_workspace: + run.synchronize_ws(targ_ws) + if self._keep_wb_workspace: result = run.get_ws_clone() - else: + else: result = run.get_workspace() - return result + return result else: DeleteWorkspace(Workspace=new_ws_name) else: @@ -1483,7 +1483,7 @@ def _get_wb_inegrals(self,run): return result #------------------------------------------------------------------------------- def _build_white_tag(self): - """ build tag indicating wb-integration ranges """ + """ build tag indicating wb-integration ranges """ low,upp = self.wb_integr_range white_tag = 'NormBy:{0}_IntergatedIn:{1:0>10.2f}:{2:0>10.2f}'.format(self.normalise_method,low,upp) return white_tag @@ -1502,7 +1502,7 @@ def get_failed_spectra_list_from_masks(masked_wksp): failed_spectra = [] if masked_wksp is None: - return (failed_spectra,0) + return (failed_spectra,0) masking_wksp,sp_list = ExtractMask(masked_wksp) DeleteWorkspace(masking_wksp) @@ -1514,4 +1514,4 @@ def get_failed_spectra_list_from_masks(masked_wksp): #----------------------------------------------------------------- if __name__ == "__main__": pass - #unittest.main() \ No newline at end of file + #unittest.main() diff --git a/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py b/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py index 4ff69c2b4c71..7fcdcf165c34 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py +++ b/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py @@ -3,13 +3,13 @@ class NonIDF_Properties(object): - """ Class defines the interface for main properties, used in reduction, and not described in + """ Class defines the interface for main properties, used in reduction, and not described in IDF ( Instrument_Properties.xml file) - These properties are main set of properties, user have to set up - for reduction to work with defaults. + These properties are main set of properties, user have to set up + for reduction to work with defaults. - The example of such properties are run numbers, energy bins and incident energies. + The example of such properties are run numbers, energy bins and incident energies. """ # logging levels available for user @@ -21,9 +21,9 @@ class NonIDF_Properties(object): "debug" : (5,lambda (msg): logger.debug(msg))} - def __init__(self,Instrument,run_workspace=None): + def __init__(self,Instrument,run_workspace=None): """ initialize main properties, defined by the class - @parameter Instrument -- name or pointer to the instrument, + @parameter Instrument -- name or pointer to the instrument, deployed in reduction """ # @@ -35,14 +35,14 @@ def __init__(self,Instrument,run_workspace=None): object.__setattr__(self,'_log_to_mantid',False) object.__setattr__(self,'_current_log_level',3) - + object.__setattr__(self,'_psi',float('NaN')) # SNS motor stuff which is difficult to test as I've never seen it object.__setattr__(self,'_motor_name',None) object.__setattr__(self,'_motor_offset',0) object.__setattr__(self,'_save_file_name',None) - + self._set_instrument_and_facility(Instrument,run_workspace) # set up descriptors holder class reference @@ -68,8 +68,8 @@ def log(self, msg,level="notice"): logger(msg) else: # TODO: reconcile this with Mantid. - if lev <= self._current_log_level: - print msg + if lev <= self._current_log_level: + print msg #----------------------------------------------------------------------------- # Complex properties with personal descriptors #----------------------------------------------------------------------------- @@ -93,8 +93,8 @@ def log(self, msg,level="notice"): wb_for_monovan_run = RunDescriptorDependent(wb_run,"MV_WB_"," white beam run used to calculate monovanadium integrals.\n If not explicitly set, white beam for processing run is used") # TODO: do something about it. Second white is explicitly used in # diagnostics but not accessed at all - second_white = RunDescriptor("Second white beam currently unused in the workflow despite being referred to in Diagnostics. Should it be used for Monovan Diagnostics?") - # + second_white = RunDescriptor("Second white beam currently unused in the workflow despite being referred to in Diagnostics. Should it be used for Monovan Diagnostics?") + # _tmp_run = RunDescriptor("_TMP","Property used for storing intermediate run data during reduction") # property responsible for summing runs sum_runs = SumRuns(sample_run) @@ -106,7 +106,7 @@ def getDefaultParameterValue(self,par_name): def instrument(self): if self._pInstrument is None: raise KeyError("Attempt to use uninitialized property manager") - else: + else: return self._pInstrument # #----------------------------------------------------------------------------------- @@ -122,7 +122,7 @@ def print_diag_results(self,value): # ----------------------------------------------------------------------------- @property def log_to_mantid(self): - """ Property specify if high level log should be printed to stdout or added to common Mantid log""" + """ Property specify if high level log should be printed to stdout or added to common Mantid log""" return self._log_to_mantid @log_to_mantid.setter @@ -130,11 +130,11 @@ def log_to_mantid(self,val): object.__setattr__(self,'_log_to_mantid',bool(val)) # ----------------------------------------------------------------------------- #----------------------------------------------------------------------------------- - @property + @property def psi(self): """ rotation angle (not available from IDF)""" return self._psi - @psi.setter + @psi.setter def psi(self,value): """set rotation angle (not available from IDF). This value will be saved into NXSpe file""" object.__setattr__(self,'_psi',value) @@ -170,7 +170,7 @@ def _set_instrument_and_facility(self,Instrument,run_workspace=None): if isinstance(Instrument,geometry._geometry.Instrument): instrument = Instrument instr_name = instrument.getFullName() - try: + try: new_name,full_name,facility_ = prop_helpers.check_instrument_name(None,instr_name) except KeyError: # the instrument pointer is not found in any facility but we have it after all new_name = instr_name @@ -185,7 +185,7 @@ def _set_instrument_and_facility(self,Instrument,run_workspace=None): idf_file = api.ExperimentInfo.getInstrumentFilename(full_name) tmp_ws_name = '__empty_' + full_name if not mtd.doesExist(tmp_ws_name): - LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) + LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) instrument = mtd[tmp_ws_name].getInstrument() else: raise TypeError(' neither correct instrument name nor instrument pointer provided as instrument parameter') @@ -195,7 +195,7 @@ def _set_instrument_and_facility(self,Instrument,run_workspace=None): object.__setattr__(self,'_facility',facility_) object.__setattr__(self,'_short_instr_name',new_name) - + diff --git a/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py b/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py index 6cd58050e8b7..b2efa1f7dcbc 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py +++ b/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py @@ -1,6 +1,6 @@ """ File contains collection of Descriptors used to define complex - properties in NonIDF_Properties and PropertyManager classes -""" + properties in NonIDF_Properties and PropertyManager classes +""" import os from mantid.simpleapi import * @@ -17,7 +17,7 @@ class PropDescriptor(object): """ Class provides common custom interface for property descriptors """ def dependencies(self): - """ Returns the list of other properties names, this property depends on""" + """ Returns the list of other properties names, this property depends on""" return [] # end PropDescriptor @@ -26,12 +26,12 @@ def dependencies(self): #----------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------- class SumRuns(PropDescriptor): - """ Boolean property specifies if list of files provided as input for sample_run property - should be summed. + """ Boolean property specifies if list of files provided as input for sample_run property + should be summed. - It also specifies various auxiliary operations, defined for summing runs, so property + It also specifies various auxiliary operations, defined for summing runs, so property is deeply entangled with the sample_run property - """ + """ def __init__(self,sample_run_prop): # internal reference to sample run property self._sample_run = sample_run_prop @@ -47,28 +47,28 @@ def __init__(self,sample_run_prop): # def __get__(self,instance,holder_class): - if not self._holder: - self._holder = holder_class - if instance is None: - return self - return self._sum_runs + if not self._holder: + self._holder = holder_class + if instance is None: + return self + return self._sum_runs # def __set__(self,instance,value): if not self._holder: - from Direct.PropertyManager import PropertyManager - self._holder = PropertyManager - + from Direct.PropertyManager import PropertyManager + self._holder = PropertyManager + old_value = self._sum_runs if isinstance(value,bool): self._sum_runs = value self._last_ind2sum = -1 elif isinstance(value,int): if value > 0: - self._last_ind2sum = int(value) - 1 - self._sum_runs = True + self._last_ind2sum = int(value) - 1 + self._sum_runs = True else: - self._last_ind2sum = -1 - self._sum_runs = False + self._last_ind2sum = -1 + self._sum_runs = False else: self._sum_runs = bool(value) self._last_ind2sum = -1 @@ -76,29 +76,29 @@ def __set__(self,instance,value): if old_value != self._sum_runs: if len(self._run_numbers) > 0 and self._sum_runs: # clear previous state of sample_run - ind = self.get_last_ind2sum() - self._sample_run.__set__(None,self._run_numbers[ind]) + ind = self.get_last_ind2sum() + self._sample_run.__set__(None,self._run_numbers[ind]) # def set_list2add(self,runs_to_add,fnames=None,fext=None): - """Set run numbers to add together with possible file guess-es """ - if not isinstance(runs_to_add,list): - raise KeyError('Can only set list of run numbers to add') - runs = [] - for item in runs_to_add: - runs.append(int(item)) - self._run_numbers = runs - if fnames: - self._file_guess = fnames - if len(self._file_guess) != len(self._run_numbers): - self._file_guess = [''] * len(self._run_numbers) - - if fext: - self._fext = fext - if len(self._fext) != len(self._run_numbers): - self._fext = [''] * len(self._run_numbers) + """Set run numbers to add together with possible file guess-es """ + if not isinstance(runs_to_add,list): + raise KeyError('Can only set list of run numbers to add') + runs = [] + for item in runs_to_add: + runs.append(int(item)) + self._run_numbers = runs + if fnames: + self._file_guess = fnames + if len(self._file_guess) != len(self._run_numbers): + self._file_guess = [''] * len(self._run_numbers) + + if fext: + self._fext = fext + if len(self._fext) != len(self._run_numbers): + self._fext = [''] * len(self._run_numbers) # def clear_sum(self): - """Clear all defined summation""" + """Clear all defined summation""" # if last_to_sum is -1, sum all run list provided self._last_ind2sum = -1 self._sum_runs = False @@ -107,14 +107,14 @@ def clear_sum(self): self._fext = [] # def get_last_ind2sum(self): - """Get last run number contributing to sum""" + """Get last run number contributing to sum""" if self._last_ind2sum > 0: - return self._last_ind2sum + return self._last_ind2sum else: - return len(self._run_numbers) - 1 + return len(self._run_numbers) - 1 # def set_last_ind2sum(self,run_number): - """Check and set last number, contributing to summation + """Check and set last number, contributing to summation if this number is out of summation range, clear the summation """ run_number = int(run_number) @@ -126,15 +126,15 @@ def set_last_ind2sum(self,run_number): return 0 # def get_run_list2sum(self): - """Get run numbers of the files to be summed together """ + """Get run numbers of the files to be summed together """ num_to_load = len(self._run_numbers) if self._last_ind2sum > 0 and self._last_ind2sum < num_to_load: - num_to_load = self._last_ind2sum + num_to_load = self._last_ind2sum return self._run_numbers[:num_to_load] # def load_and_sum_runs(self,inst_name,monitors_with_ws): - """ Load multiple runs and sum them together """ + """ Load multiple runs and sum them together """ logger = lambda mess : (getattr(getattr(self,'_holder'),'log')\ (self._sample_run._holder,mess)) @@ -157,27 +157,27 @@ def load_and_sum_runs(self,inst_name,monitors_with_ws): for ind,run_num in enumerate(runs_to_load[1:num_to_load]): - file_h = os.path.join(self._file_guess[ind + 1],'{0}{1}{2}'.\ + file_h = os.path.join(self._file_guess[ind + 1],'{0}{1}{2}'.\ format(inst_name,run_num,self._fext[ind + 1])) - logger("*** Adding #{0}/{1}, run N: {2} ".\ + logger("*** Adding #{0}/{1}, run N: {2} ".\ format(ind + 2,num_to_load,run_num)) - term_name = '{0}_ADDITIVE_#{1}/{2}'.format(inst_name,ind + 2,num_to_load)# + term_name = '{0}_ADDITIVE_#{1}/{2}'.format(inst_name,ind + 2,num_to_load)# - wsp = self._sample_run.load_file(inst_name,term_name,False, + wsp = self._sample_run.load_file(inst_name,term_name,False, monitors_with_ws,False,file_hint=file_h) - wsp_name = wsp.name() - wsp_mon_name = wsp_name + '_monitors' - Plus(LHSWorkspace=sum_ws_name,RHSWorkspace=wsp_name, + wsp_name = wsp.name() + wsp_mon_name = wsp_name + '_monitors' + Plus(LHSWorkspace=sum_ws_name,RHSWorkspace=wsp_name, OutputWorkspace=sum_ws_name,ClearRHSWorkspace=True) - AddedRunNumbers+=',{0}'.format(run_num) - if not monitors_with_ws: - Plus(LHSWorkspace=sum_mon_name,RHSWorkspace=wsp_mon_name, + AddedRunNumbers+=',{0}'.format(run_num) + if not monitors_with_ws: + Plus(LHSWorkspace=sum_mon_name,RHSWorkspace=wsp_mon_name, OutputWorkspace=sum_mon_name,ClearRHSWorkspace=True) - if wsp_name in mtd: - DeleteWorkspace(wsp_name) - if wsp_mon_name in mtd: - DeleteWorkspace(wsp_mon_name) + if wsp_name in mtd: + DeleteWorkspace(wsp_name) + if wsp_mon_name in mtd: + DeleteWorkspace(wsp_mon_name) logger("*** Summing multiple runs completed ****") AddSampleLog(Workspace=sum_ws_name,LogName = 'SumOfRuns:', @@ -185,7 +185,7 @@ def load_and_sum_runs(self,inst_name,monitors_with_ws): ws = mtd[sum_ws_name] return ws # - def sum_ext(self): + def sum_ext(self): if self._sum_runs: last = self.get_last_ind2sum() sum_ext = "SumOf{0}".format(len(self._run_numbers[:last + 1])) @@ -197,82 +197,82 @@ def get_runs(self): return self._run_numbers #-------------------------------------------------------------------------------------------------------------------- class IncidentEnergy(PropDescriptor): - """ Property for incident energy or range of incident energies to be processed + """ Property for incident energy or range of incident energies to be processed - Set it up to list of values (even with single value i.e. prop_man.incident_energy=[10]) + Set it up to list of values (even with single value i.e. prop_man.incident_energy=[10]) if the energy_bins property value to be treated as relative energy ranges. - Set it up to single value (e.g. prop_man.incident_energy=10) to treat energy energy_bins + Set it up to single value (e.g. prop_man.incident_energy=10) to treat energy energy_bins as absolute energy values """ - def __init__(self): + def __init__(self): self._incident_energy = 0 self._num_energies = 1 self._cur_iter_en = 0 def __get__(self,instance,owner=None): - """ return incident energy or list of incident energies """ + """ return incident energy or list of incident energies """ if instance is None: - return self + return self - return self._incident_energy + return self._incident_energy def __set__(self,instance,value): - """ Set up incident energy or range of energies in various formats """ - if value != None: - if isinstance(value,str): - if value.find('[') > -1: - energy_list = True - value = value.translate(None, '[]').strip() - else: - energy_list = False - en_list = str.split(value,',') - if len(en_list) > 1: - rez = [] - for en_str in en_list: - val = float(en_str) - rez.append(val) - self._incident_energy = rez - else: - if energy_list: - self._incident_energy = [float(value)] - else: - self._incident_energy = float(value) - else: - if isinstance(value,list): - rez = [] - for val in value: - en_val = float(val) - if en_val <= 0: - raise KeyError("Incident energy has to be positive, but is: {0} ".format(en_val)) + """ Set up incident energy or range of energies in various formats """ + if value != None: + if isinstance(value,str): + if value.find('[') > -1: + energy_list = True + value = value.translate(None, '[]').strip() + else: + energy_list = False + en_list = str.split(value,',') + if len(en_list) > 1: + rez = [] + for en_str in en_list: + val = float(en_str) + rez.append(val) + self._incident_energy = rez + else: + if energy_list: + self._incident_energy = [float(value)] else: - rez.append(en_val) - self._incident_energy = rez + self._incident_energy = float(value) else: - self._incident_energy = float(value) - else: - raise KeyError("Incident energy have to be positive number of list of positive numbers. Got None") - + if isinstance(value,list): + rez = [] + for val in value: + en_val = float(val) + if en_val <= 0: + raise KeyError("Incident energy has to be positive, but is: {0} ".format(en_val)) + else: + rez.append(en_val) + self._incident_energy = rez + else: + self._incident_energy = float(value) + else: + raise KeyError("Incident energy have to be positive number of list of positive numbers. Got None") + # - inc_en = self._incident_energy - if isinstance(inc_en,list): - self._num_energies = len(inc_en) - for en in inc_en: - if en <= 0: - raise KeyError("Incident energy have to be positive number of list of positive numbers." + " For input argument {0} got negative value {1}".format(value,en)) - else: - self._num_energies = 1 - if inc_en <= 0: - raise KeyError("Incident energy have to be positive number of list of positive numbers." + " For value {0} got negative {1}".format(value,inc_en)) - self._cur_iter_en = 0 - + inc_en = self._incident_energy + if isinstance(inc_en,list): + self._num_energies = len(inc_en) + for en in inc_en: + if en <= 0: + raise KeyError("Incident energy have to be positive number of list of positive numbers." + " For input argument {0} got negative value {1}".format(value,en)) + else: + self._num_energies = 1 + if inc_en <= 0: + raise KeyError("Incident energy have to be positive number of list of positive numbers." + " For value {0} got negative {1}".format(value,inc_en)) + self._cur_iter_en = 0 + def multirep_mode(self): - """ return true if energy is defined as list of energies and false otherwise """ + """ return true if energy is defined as list of energies and false otherwise """ if isinstance(self._incident_energy,list): return True else: return False def get_current(self): - """ Return current energy out of range of energies""" + """ Return current energy out of range of energies""" if isinstance(self._incident_energy,list): ind = self._cur_iter_en return self._incident_energy[ind] @@ -280,8 +280,8 @@ def get_current(self): return self._incident_energy # def set_current(self,value): - """ set current energy value (used in multirep mode) to - + """ set current energy value (used in multirep mode) to + """ if isinstance(self._incident_energy,list): ind = self._cur_iter_en @@ -296,28 +296,28 @@ def __iter__(self): return self def next(self): # Python 3: def __next__(self) - """ part of iterator """ + """ part of iterator """ self._cur_iter_en += 1 ind = self._cur_iter_en if ind < self._num_energies: - if isinstance(self._incident_energy,list): - return self._incident_energy[ind] - else: - return self._incident_energy + if isinstance(self._incident_energy,list): + return self._incident_energy[ind] + else: + return self._incident_energy else: - raise StopIteration + raise StopIteration # end IncidentEnergy #----------------------------------------------------------------------------------------- class EnergyBins(PropDescriptor): - """ Energy binning, requested for final converted to energy transfer workspace. + """ Energy binning, requested for final converted to energy transfer workspace. Provide it in the form: - [min_energy,step,max_energy] if energy to process (incident_energy property ) + [min_energy,step,max_energy] if energy to process (incident_energy property ) has a single value - or + or [min_rel_enrgy,rel_step,max_rel_energy] where rel_energy is relative energy - if energy(ies) to process are list of energies. The list of energies can + if energy(ies) to process are list of energies. The list of energies can consist of single value (e.g. prop_man.incident_energy=[100]) """ @@ -330,22 +330,22 @@ def __init__(self,IncidentEnergyProp): def __get__(self,instance,owner=None): """ binning range for the result of convertToenergy procedure or list of such ranges """ if instance is None: - return self + return self return self._energy_bins def __set__(self,instance,values): - if values != None: - if isinstance(values,str): - values = values.translate(None, '[]').strip() - lst = values.split(',') - self.__set__(instance,lst) - return - else: - value = values - if len(value) != 3: - raise KeyError("Energy_bin value has to be a tuple of 3 elements or string of 3 comma-separated numbers") - value = (float(value[0]),float(value[1]),float(value[2])) + if values != None: + if isinstance(values,str): + values = values.translate(None, '[]').strip() + lst = values.split(',') + self.__set__(instance,lst) + return + else: + value = values + if len(value) != 3: + raise KeyError("Energy_bin value has to be a tuple of 3 elements or string of 3 comma-separated numbers") + value = (float(value[0]),float(value[1]),float(value[2])) # Let's not support list of multiple absolute energy bins for the # time being # nBlocks = len(value) @@ -353,51 +353,51 @@ def __set__(self,instance,values): # raise KeyError("Energy_bin value has to be either list of # n-blocks of 3 number each or string representation of this list # with numbers separated by commas") - else: - value = None + else: + value = None #TODO: implement single value settings according to rebin? - self._energy_bins = value + self._energy_bins = value def get_abs_range(self,instance=None): - """ return energies related to incident energies either as - + """ return energies related to incident energies either as + """ if self._incident_energy.multirep_mode(): # Relative energy ei = self._incident_energy.get_current() if self._energy_bins: if self.is_range_valid(): - rez = self._calc_relative_range(ei) + rez = self._calc_relative_range(ei) else: - if instance: - instance.log("*** WARNING! Got energy_bins specified as absolute values in multirep mode.\n"\ + if instance: + instance.log("*** WARNING! Got energy_bins specified as absolute values in multirep mode.\n"\ " Will normalize these values by max value and treat as relative values ", "warning") - mult = self._range / self._energy_bins[2] - rez = self._calc_relative_range(ei,mult) + mult = self._range / self._energy_bins[2] + rez = self._calc_relative_range(ei,mult) return rez else: - return None + return None else: # Absolute energy ranges - if self.is_range_valid(): - return self._energy_bins - else: - if instance: - instance.log("*** WARNING! Requested maximum binning range exceeds incident energy!\n"\ + if self.is_range_valid(): + return self._energy_bins + else: + if instance: + instance.log("*** WARNING! Requested maximum binning range exceeds incident energy!\n"\ " Will normalize binning range by max value and treat as relative range", "warning") - mult = self._range / self._energy_bins[2] - ei = self._incident_energy.get_current() - return self._calc_relative_range(ei,mult) + mult = self._range / self._energy_bins[2] + ei = self._incident_energy.get_current() + return self._calc_relative_range(ei,mult) def is_range_valid(self): - """Method verifies if binning range is consistent with incident energy """ + """Method verifies if binning range is consistent with incident energy """ if self._incident_energy.multirep_mode(): return (self._energy_bins[2] <= self._range) else: return (self._energy_bins[2] <= self._incident_energy.get_current()) def _calc_relative_range(self,ei,range_mult=1): - """ """ + """ """ mult = range_mult * ei return (self._energy_bins[0] * mult ,self._energy_bins[1] * mult,self._energy_bins[2] * mult) @@ -410,16 +410,16 @@ class SaveFileName(PropDescriptor): See similar property get_sample_ws_name TODO: (leave only one) """ def __init__(self,Name=None): - self._file_name = Name + self._file_name = Name def __get__(self,instance,owner=None): if instance is None: - return self + return self if self._file_name: return self._file_name else: if instance.instr_name: - name = instance.short_inst_name + name = instance.short_inst_name else: name = '_EMPTY' @@ -443,26 +443,26 @@ def __set__(self,instance,value): #end SaveFileName #----------------------------------------------------------------------------------------- class InstrumentDependentProp(PropDescriptor): - """ Generic property describing some aspects of instrument (e.g. name, short name etc), + """ Generic property describing some aspects of instrument (e.g. name, short name etc), which are undefined if no instrument is defined """ def __init__(self,prop_name): self._prop_name = prop_name def __get__(self,instance,owner=None): - if instance is None: - return self + if instance is None: + return self - if instance._pInstrument is None: + if instance._pInstrument is None: raise KeyError("Attempt to use uninitialized property manager") - else: + else: return getattr(instance,self._prop_name) def __set__(self,instance,values): raise AttributeError("Property {0} can not be assigned".format(self._prop_name)) #end InstrumentDependentProp #----------------------------------------------------------------------------------------- def check_ei_bin_consistent(ei,binning_range): - """ function verifies if the energy binning is consistent with incident energies """ + """ function verifies if the energy binning is consistent with incident energies """ if isinstance(ei,list): for en in ei: range = binning_range[en] @@ -475,7 +475,7 @@ def check_ei_bin_consistent(ei,binning_range): return (True,'') #----------------------------------------------------------------------------------------- class VanadiumRMM(PropDescriptor): - """ define constant static rmm for vanadium """ + """ define constant static rmm for vanadium """ def __get__(self,instance,owner=None): """ return rmm for vanadium """ @@ -492,35 +492,35 @@ def __set__(self,instance,value): # PropertyManager #----------------------------------------------------------------------------------------- class mon2NormalizationEnergyRange(PropDescriptor): - """ Energy range to integrate signal on monitor 2 when normalized by this monitor - - This class contains relative range of energies in which the monitor-2 signal should - be integrated, and returns the energy range for integration according to + """ Energy range to integrate signal on monitor 2 when normalized by this monitor + + This class contains relative range of energies in which the monitor-2 signal should + be integrated, and returns the energy range for integration according to formula: range = [min_range*ei,max_range*ei] where ei is incident monitor energy - To find actual integration ranges one should convert these values into TOF (or + To find actual integration ranges one should convert these values into TOF (or convert monitor signal to energy) - """ + """ def __init__(self): # default range self._relative_range = [0.8,1.2] def __get__(self,instance,owner): - """ Return actual energy range from internal relative range and incident energy """ - if instance is None: - return self - return [self._relative_range[0] * instance.incident_energy,self._relative_range[1] * instance.incident_energy] + """ Return actual energy range from internal relative range and incident energy """ + if instance is None: + return self + return [self._relative_range[0] * instance.incident_energy,self._relative_range[1] * instance.incident_energy] def __set__(self,instance,val): - """ set detector calibration file using various formats """ - if isinstance(val,list): - self._relative_range = self._check_range(val,instance) - elif isinstance(val,str): - val = self._parce_string2list(val) - self.__set__(instance,val) - else: - raise KeyError('mon2_norm_energy_range needs to be initialized by two values.\n' + """ set detector calibration file using various formats """ + if isinstance(val,list): + self._relative_range = self._check_range(val,instance) + elif isinstance(val,str): + val = self._parce_string2list(val) + self.__set__(instance,val) + else: + raise KeyError('mon2_norm_energy_range needs to be initialized by two values.\n' 'Trying to assign value {0} of unknown type {1}'.format(val,type(val))) # def _check_range(self,val,instance): @@ -537,12 +537,12 @@ def _check_range(self,val,instance): instance.log(message,'warning') val2 = float(val[1]) if val2 < 1.1 or val2 > 1.9: - message = "Upper mon2_norm_energy_range describes upper limit of energy to integrate neutron signal after the chopper.\n"\ + message = "Upper mon2_norm_energy_range describes upper limit of energy to integrate neutron signal after the chopper.\n"\ "The limit is defined as (this value)*incident_energy. Are you sure you want to set this_value to {0}?\n".format(val2) - if val2 < 1: - raise KeyError(message) - else: - instance.log(message,'warning') + if val2 < 1: + raise KeyError(message) + else: + instance.log(message,'warning') return [val1,val2] # @@ -562,15 +562,15 @@ def __init__(self,availible_values,default_value): def __get__(self,instance,owner): """ Return current value for the property with range of values. """ if instance is None: - return self + return self return self._current_value def __set__(self,instance,val): - """ set detector calibration file using various formats """ - if val in self._availible_values: - self._current_value = val - else: - raise KeyError(' Property can not have value {0}'.format(val)) + """ set detector calibration file using various formats """ + if val in self._availible_values: + self._current_value = val + else: + raise KeyError(' Property can not have value {0}'.format(val)) #----------------------------------------------------------------------------------------- class DetCalFile(PropDescriptor): @@ -580,31 +580,31 @@ def __init__(self): def __get__(self,instance,owner): if instance is None: - return self + return self return self._det_cal_file def __set__(self,instance,val): - """ set detector calibration file using various formats """ - - if val is None or isinstance(val,api.Workspace) or isinstance(val,str): + """ set detector calibration file using various formats """ + + if val is None or isinstance(val,api.Workspace) or isinstance(val,str): # nothing provided or workspace provided or filename probably provided - if str(val) in mtd: + if str(val) in mtd: # workspace name provided val = mtd[str(val)] - self._det_cal_file = val - return - + self._det_cal_file = val + return - if isinstance(val,int): + + if isinstance(val,int): #if val in instance.all_run_numbers: TODO: retrieve workspace from #run numbers - file_hint = str(val) - file_name = FileFinder.findRuns(file_hint)[0] - self._det_cal_file = file_name - return + file_hint = str(val) + file_name = FileFinder.findRuns(file_hint)[0] + self._det_cal_file = file_name + return - raise NameError('Detector calibration file name can be a workspace name present in Mantid or string describing an file name') + raise NameError('Detector calibration file name can be a workspace name present in Mantid or string describing an file name') #if Reducer.det_cal_file != None : # if isinstance(Reducer.det_cal_file,str) and not Reducer.det_cal_file # in mtd : # it is a file @@ -628,56 +628,56 @@ def __init__(self,file_ext,doc_string=None): def __get__(self,instance,type=None): if instance is None: - return self + return self return self._file_name def __set__(self,instance,value): if value != None: - fileName, fileExtension = os.path.splitext(value) - if (not fileExtension): - value = value + self._file_ext + fileName, fileExtension = os.path.splitext(value) + if (not fileExtension): + value = value + self._file_ext self._file_name = value - + #end MapMaskFile #----------------------------------------------------------------------------------------- class HardMaskPlus(prop_helpers.ComplexProperty): - """ Legacy HardMaskPlus class which sets up hard_mask_file to file and use_hard_mask_only to True""" + """ Legacy HardMaskPlus class which sets up hard_mask_file to file and use_hard_mask_only to True""" def __init__(self): prop_helpers.ComplexProperty.__init__(self,['use_hard_mask_only','run_diagnostics']) def __get__(self,instance,type=None): if instance is None: - return self + return self return instance.hard_mask_file def __set__(self,instance,value): if value != None: - fileName, fileExtension = os.path.splitext(value) - if (not fileExtension): - value = value + '.msk' - instance.hard_mask_file = value - prop_helpers.ComplexProperty.__set__(self,instance.__dict__,[False,True]) + fileName, fileExtension = os.path.splitext(value) + if (not fileExtension): + value = value + '.msk' + instance.hard_mask_file = value + prop_helpers.ComplexProperty.__set__(self,instance.__dict__,[False,True]) else: - prop_helpers.ComplexProperty.__set__(self,instance.__dict__,[True,False]) + prop_helpers.ComplexProperty.__set__(self,instance.__dict__,[True,False]) try: - del instance.__changed_properties['hardmaskOnly'] + del instance.__changed_properties['hardmaskOnly'] except: - pass - + pass + #----------------------------------------------------------------------------------------- class HardMaskOnly(prop_helpers.ComplexProperty): """ Sets diagnostics algorithm to use hard mask file provided and to disable all other diagnostics routines It controls two options, where the first one is use_hard_mask_only=True/False, controls diagnostics algorithm - and another one: hard_mask_file provides file for masking. + and another one: hard_mask_file provides file for masking. """ def __init__(self): prop_helpers.ComplexProperty.__init__(self,['use_hard_mask_only','run_diagnostics']) def __get__(self,instance,type=None): if instance is None: - return self + return self return prop_helpers.gen_getter(instance.__dict__,'use_hard_mask_only') def __set__(self,instance,value): @@ -694,7 +694,7 @@ def __set__(self,instance,value): elif value.lower() in ['false','no']: use_hard_mask_only = False else: # it is probably a hard mask file provided: - instance.hard_mask_file = value + instance.hard_mask_file = value use_hard_mask_only = True hard_mask_file = instance.hard_mask_file #end @@ -707,9 +707,9 @@ def __set__(self,instance,value): run_diagnostics = True prop_helpers.ComplexProperty.__set__(self,instance.__dict__,[use_hard_mask_only,run_diagnostics]) try: - del instance.__changed_properties['hardmaskPlus'] + del instance.__changed_properties['hardmaskPlus'] except: - pass + pass #end HardMaskOnly #----------------------------------------------------------------------------------------- class MonovanIntegrationRange(prop_helpers.ComplexProperty): @@ -718,28 +718,28 @@ class MonovanIntegrationRange(prop_helpers.ComplexProperty): Defined either directly or as the function of the incident energy(s) - If list of incident energies is provided, map of ranges in the form 'ei'=range is returned + If list of incident energies is provided, map of ranges in the form 'ei'=range is returned """ def __init__(self,DepType=None): if DepType: self._rel_range = False prop_helpers.ComplexProperty.__init__(self,['monovan_lo_value','monovan_hi_value']) else: - self._rel_range = True + self._rel_range = True prop_helpers.ComplexProperty.__init__(self,['monovan_lo_frac','monovan_hi_frac']) pass def __get__(self,instance,owner): if instance is None: - return self + return self if isinstance(instance,dict): - ei = 1 - tDict = instance + ei = 1 + tDict = instance else: - ei = owner.incident_energy.get_current() - tDict = instance.__dict__ + ei = owner.incident_energy.get_current() + tDict = instance.__dict__ if self._rel_range: # relative range if ei is None: @@ -752,17 +752,17 @@ def __get__(self,instance,owner): def __set__(self,instance,value): if isinstance(instance,dict): - dDict = instance + dDict = instance else: - tDict = instance.__dict__ + tDict = instance.__dict__ if value is None: if (not self._rel_range): self._rel_range = True self._other_prop = ['monovan_lo_frac','monovan_hi_frac'] else: if self._rel_range: - self._rel_range = False - self._other_prop = ['monovan_lo_value','monovan_hi_value'] + self._rel_range = False + self._other_prop = ['monovan_lo_value','monovan_hi_value'] if isinstance(value,str): values = value.split(',') @@ -778,33 +778,33 @@ def __set__(self,instance,value): #----------------------------------------------------------------------------------------- class SpectraToMonitorsList(PropDescriptor): - """ property describes list of spectra, used as monitors to estimate incident energy - in a direct scattering experiment. + """ property describes list of spectra, used as monitors to estimate incident energy + in a direct scattering experiment. - Necessary when a detector working in event mode is used as monitor. Specifying this number would copy + Necessary when a detector working in event mode is used as monitor. Specifying this number would copy correspondent spectra to monitor workspace and rebin it according to monitors binning Written to work with old IDF too, where this property is absent. - """ - def __init__(self): - self._spectra_to_monitors_list = None + """ + def __init__(self): + self._spectra_to_monitors_list = None - def __get__(self,instance,type=None): - if instance is None: - return self - return self._spectra_to_monitors_list + def __get__(self,instance,type=None): + if instance is None: + return self + return self._spectra_to_monitors_list - def __set__(self,instance,spectra_list): + def __set__(self,instance,spectra_list): """ Sets copy spectra to monitors variable as a list of monitors using different forms of input """ self._spectra_to_monitors_list = self._convert_to_list(spectra_list) - def _convert_to_list(self,spectra_list): - """ convert any spectra_list representation into a list """ - if spectra_list is None: + def _convert_to_list(self,spectra_list): + """ convert any spectra_list representation into a list """ + if spectra_list is None: return None - if isinstance(spectra_list,str): + if isinstance(spectra_list,str): if spectra_list.lower() is 'none': result = None else: @@ -813,7 +813,7 @@ def _convert_to_list(self,spectra_list): for spectum in spectra : result.append(int(spectum)) - else: + else: if isinstance(spectra_list,list): if len(spectra_list) == 0: result = None @@ -823,23 +823,23 @@ def _convert_to_list(self,spectra_list): result.append(int(spectra_list[i])) else: result = [int(spectra_list)] - return result + return result #end SpectraToMonitorsList #----------------------------------------------------------------------------------------- class SaveFormat(PropDescriptor): # formats available for saving the data - save_formats = ['spe','nxspe','nxs'] - def __init__(self): - self._save_format = set() + save_formats = ['spe','nxspe','nxs'] + def __init__(self): + self._save_format = set() - def __get__(self,instance,type=None): + def __get__(self,instance,type=None): if instance is None: - return self + return self return self._save_format - def __set__(self,instance,value): + def __set__(self,instance,value): """ user can clear save formats by setting save_format=None or save_format = [] or save_format='' if empty string or empty list is provided as part of the list, all save_format-s set up earlier are cleared""" @@ -856,19 +856,19 @@ def __set__(self,instance,value): self.__set__(instance,subformats) return else: - value = subformats[0] + value = subformats[0] if not(value in SaveFormat.save_formats): instance.log("Trying to set saving in unknown format: \"" + str(value) + "\" No saving will occur for this format") return - else: + else: try: # set single default save format recursively - for val in value: + for val in value: self.__set__(instance,val) - return - except: - raise KeyError(' Attempting to set unknown saving format {0} of type {1}. Allowed values can be spe, nxspe or nxs'\ + return + except: + raise KeyError(' Attempting to set unknown saving format {0} of type {1}. Allowed values can be spe, nxspe or nxs'\ .format(value,type(value))) #end if different types self._save_format.add(value) @@ -876,9 +876,9 @@ def __set__(self,instance,value): #----------------------------------------------------------------------------------------- class DiagSpectra(PropDescriptor): - """ class describes spectra list which should be used in diagnostics + """ class describes spectra list which should be used in diagnostics - consist of tuples list where each tuple are the numbers + consist of tuples list where each tuple are the numbers indicating first-last spectra in the group. if None, all spectra are used in diagnostics @@ -888,7 +888,7 @@ def __init__(self): def __get__(self,instance,type=None): if instance is None: - return self + return self return self._diag_spectra @@ -919,27 +919,27 @@ def _process_spectra_list(self,specta_sring): #----------------------------------------------------------------------------------------- class BackbgroundTestRange(PropDescriptor): - """ The TOF range used in diagnostics to reject high background spectra. + """ The TOF range used in diagnostics to reject high background spectra. - Usually it is the same range as the TOF range used to remove - background (usually in powders) though it may be set up separately. + Usually it is the same range as the TOF range used to remove + background (usually in powders) though it may be set up separately. """ def __init__(self): self._background_test_range = None def __get__(self,instance,type=None): - if instance is None: - return self + if instance is None: + return self - if self._background_test_range: - return self._background_test_range - else: + if self._background_test_range: + return self._background_test_range + else: return instance.bkgd_range def __set__(self,instance,value): if value is None: - self._background_test_range = None - return + self._background_test_range = None + return if isinstance(value,str): value = str.split(value,',') if len(value) != 2: @@ -949,52 +949,52 @@ def __set__(self,instance,value): #----------------------------------------------------------------------------------------- class MultirepTOFSpectraList(PropDescriptor): - """ property describes list of spectra numbers, used to identify - TOF range corresponding to the particular energy range + """ property describes list of spectra numbers, used to identify + TOF range corresponding to the particular energy range - Usually it is list of two numbers, specifying monitors which are - closest and furthest from the sample + Usually it is list of two numbers, specifying monitors which are + closest and furthest from the sample """ def __init__(self): self._spectra_list = None def __get__(self,instance,type=None): - if instance is None: - return self + if instance is None: + return self - return self._spectra_list + return self._spectra_list def __set__(self,instance,value): if value is None: - self._spectra_list = None - return + self._spectra_list = None + return if isinstance(value,str): value = str.split(value,',') self.__set__(instance,value) return if isinstance(value, list): - rez =[] - for val in value: - rez.append(int(val)) + rez =[] + for val in value: + rez.append(int(val)) else: rez = [int(value)] self._spectra_list=rez #end MultirepTOFSpectraList class MonoCorrectionFactor(PropDescriptor): - """ property contains correction factor, used to convert - experimental scattering cross-section into absolute - units ( mb/str/mev/fu) + """ property contains correction factor, used to convert + experimental scattering cross-section into absolute + units ( mb/str/mev/fu) - There are independent two sources for this factor: - 1) if user explicitly specifies correction value. - This value then will be applied to all subsequent runs + There are independent two sources for this factor: + 1) if user explicitly specifies correction value. + This value then will be applied to all subsequent runs without any checks if the correction is appropriate - 2) set/get cashed value correspondent to current monovan + 2) set/get cashed value correspondent to current monovan run number, incident energy and integration range. - This value is cashed at first run and reapplied if + This value is cashed at first run and reapplied if no changes to the values it depends on were identified - """ + """ def __init__(self,ei_prop): self._cor_factor = None self._mono_run_number=None @@ -1002,21 +1002,21 @@ def __init__(self,ei_prop): self.cashed_values={} def __get__(self,instance,type=None): - if instance is None: - return self + if instance is None: + return self - return self._cor_factor + return self._cor_factor def __set__(self,instance,value): - self._cor_factor = value - # + self._cor_factor = value + # def set_val_to_cash(self,instance,value): - """ """ + """ """ mono_int_range = instance.monovan_integr_range cash_id = self._build_cash_val_id(mono_int_range) self.cashed_values[cash_id] = value # tell property manager that mono_correction_factor has been modified - # to avoid automatic resetting this property from any workspace + # to avoid automatic resetting this property from any workspace cp = getattr(instance,'_PropertyManager__changed_properties') cp.add('mono_correction_factor') @@ -1024,24 +1024,24 @@ def get_val_from_cash(self,instance): mono_int_range = instance.monovan_integr_range cash_id = self._build_cash_val_id(mono_int_range) if cash_id in self.cashed_values: - return self.cashed_values[cash_id] + return self.cashed_values[cash_id] else: - return None - + return None + def set_cash_mono_run_number(self,new_value): if new_value is None: - self.cashed_values={} - self._mono_run_number = None - return + self.cashed_values={} + self._mono_run_number = None + return if self._mono_run_number != int(new_value): - self.cashed_values={} - self._mono_run_number = int(new_value) + self.cashed_values={} + self._mono_run_number = int(new_value) def _build_cash_val_id(self,mono_int_range): - ei = self._ei_prop.get_current() - cash_id = "Ei={0:0>9.4e}:Int({1:0>9.4e}:{2:0>9.5e}):Run{3}".\ + ei = self._ei_prop.get_current() + cash_id = "Ei={0:0>9.4e}:Int({1:0>9.4e}:{2:0>9.5e}):Run{3}".\ format(ei,mono_int_range[0],mono_int_range[1],self._mono_run_number) - return cash_id + return cash_id #----------------------------------------------------------------------------------------- diff --git a/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py b/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py index 987c33499bb5..9e436d64316f 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py +++ b/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py @@ -4,30 +4,30 @@ class PropertyManager(NonIDF_Properties): - """ Class defines the interface for Direct inelastic reduction with properties + """ Class defines the interface for Direct inelastic reduction with properties present in Instrument_Properties.xml file These properties are responsible for fine turning up of the reduction - Supported properties in IDF can be simple (prop[name]=value e.g. - prop['vanadium_mass']=30.5 - - or complex + Supported properties in IDF can be simple (prop[name]=value e.g. + prop['vanadium_mass']=30.5 + + or complex where prop[name_complex_prop] value is equal [prop[name_1],prop[name_2]] e.g. time interval used in normalization on monitor 1: prop[norm_mon_integration_range] = [prop['norm-mon1-min'],prop['norm-mon1-max']] prop['norm-mon1-min']=1000,prop['norm-mon1-max']=2000 - There are properties which provide even more complex functionality. These defined using Descriptors. + There are properties which provide even more complex functionality. These defined using Descriptors. + - - The class is written to provide the following functionality. + The class is written to provide the following functionality. - 1) Properties are initiated from Instrument_Properties.xml file as defaults. - 2) Attempt to access property, not present in this file throws. - 3) Attempt to create property not present in this file throws. - 4) A standard behavior is defined for the most of the properties (get/set appropriate value) when there is number of - overloaded properties, which support more complex behavior using specially written Descriptors + 1) Properties are initiated from Instrument_Properties.xml file as defaults. + 2) Attempt to access property, not present in this file throws. + 3) Attempt to create property not present in this file throws. + 4) A standard behavior is defined for the most of the properties (get/set appropriate value) when there is number of + overloaded properties, which support more complex behavior using specially written Descriptors 5) Changes to the properties are recorded and the list of changed properties is available on request ######## @@ -41,9 +41,9 @@ class PropertyManager(NonIDF_Properties): __getattr__ and __setattr__ are overloaded to understand such calls. The property_name itself is naturally not placed into system dictionary. - 3) Descriptors with the name present in IDF do not store their values and names in __dict__ + 3) Descriptors with the name present in IDF do not store their values and names in __dict__ (the name is removed during IDF parsing) but keep their information in the descriptor. - This is not considered a problem as only one instance of property manager is expected. If this need to be changed, + This is not considered a problem as only one instance of property manager is expected. If this need to be changed, adding property values to the __dict__ as values of _property_name keys should be safe. 4) __getattr__ (and __setattr__ ) method are overloaded to provide call to a descriptor before the search in the system dictionary. @@ -51,10 +51,10 @@ class PropertyManager(NonIDF_Properties): e.g. in case when an descriptor is called through one of its synonym name. A problem will occur if a key with name equal to descriptor name is also present in __dict__. This name would override descriptor. - This is why any new descriptor should never place a key with its name in __dict__. Current design automatically remove IDF name + This is why any new descriptor should never place a key with its name in __dict__. Current design automatically remove IDF name from __dict__ if a descriptor with such name exist, so further development should support this behavior. - 5) In many places (descriptors, RunDescriptor itself), PropertyManager assumed to be a singleton, so most Descriptors are defined on a + 5) In many places (descriptors, RunDescriptor itself), PropertyManager assumed to be a singleton, so most Descriptors are defined on a class level. If this changes, careful refactoring will be necessary @@ -76,10 +76,10 @@ def __init__(self,Instrument,instr_run=None): 'file_properties':[],'abs_norm_file_properties':[]} # place these properties to __dict__ with proper decoration self._init_private_properties(private_properties) - # + # class_dec = '_'+type(self).__name__+'__' # --------------------------------------------------------------------------------------------- - # overloaded descriptors. These properties have their personal descriptors, different from default. + # overloaded descriptors. These properties have their personal descriptors, different from default. all_methods = dir(self) object.__setattr__(self,class_dec+'descriptors',prop_helpers.extract_non_system_names(all_methods)) # --------------------------------------------------------------------------------------------- @@ -99,11 +99,11 @@ def __init__(self,Instrument,instr_run=None): object.__setattr__(self,class_dec+'abs_norm_file_properties',['monovan_mapfile']) # properties with allowed values - + def _convert_params_to_properties(self,param_list,detine_subst_dict=True,descr_list=[]): """ method processes parameters obtained from IDF and modifies the IDF properties - to the form allowing them be assigned as python class properties. - """ + to the form allowing them be assigned as python class properties. + """ subst_name = '_'+type(self).__name__+'__subst_dict' # build and use substitution dictionary @@ -117,12 +117,12 @@ def _convert_params_to_properties(self,param_list,detine_subst_dict=True,descr_l #end - # build properties list and descriptors list with their initial values - param_dict,descr_dict = prop_helpers.build_properties_dict(param_list,self.__dict__[subst_name],descr_list) + # build properties list and descriptors list with their initial values + param_dict,descr_dict = prop_helpers.build_properties_dict(param_list,self.__dict__[subst_name],descr_list) return (param_dict,descr_dict) def _init_private_properties(self,prop_dict): - """ helper method used to define all private dictionaries at once + """ helper method used to define all private dictionaries at once during __init__ procedure """ @@ -133,15 +133,15 @@ def _init_private_properties(self,prop_dict): new_key = class_decor+key object.__setattr__(self,new_key,val) - + def __setattr__(self,name0,val): """ Overloaded generic set method, disallowing non-existing properties being set. - - It also provides common checks for generic properties groups + + It also provides common checks for generic properties groups and records all properties changed - """ + """ - # Let's set private properties directly. Normally, nobody should try + # Let's set private properties directly. Normally, nobody should try # to set them through PropertyManager interface #if name0[:2]=='_P': # self.__dict__[name0] = val @@ -155,47 +155,47 @@ def __setattr__(self,name0,val): # replace common substitutions for string value if type(val) is str : - val1 = val.lower() - if (val1 == 'none' or len(val1) == 0): - val = None - if val1 == 'default': - val = self.getDefaultParameterValue(name0) + val1 = val.lower() + if (val1 == 'none' or len(val1) == 0): + val = None + if val1 == 'default': + val = self.getDefaultParameterValue(name0) # boolean property? - if val1 in ['true','yes']: - val = True - if val1 in ['false','no']: - val = False + if val1 in ['true','yes']: + val = True + if val1 in ['false','no']: + val = False if type(val) is list and len(val) == 0: val = None - + # set property value: if name in self.__descriptors: - super(PropertyManager,self).__setattr__(name,val) + super(PropertyManager,self).__setattr__(name,val) else: - other_prop=prop_helpers.gen_setter(self.__dict__,name,val) + other_prop=prop_helpers.gen_setter(self.__dict__,name,val) # record the fact that the property have changed self.__changed_properties.add(name) # ---------------------------- def __getattr__(self,name): - """ Overloaded get method, disallowing non-existing properties being get but allowing - a property been called with different names specified in substitution dictionary. """ + """ Overloaded get method, disallowing non-existing properties being get but allowing + a property been called with different names specified in substitution dictionary. """ - if name in self.__subst_dict: - name = self.__subst_dict[name] - return getattr(self,name) - #end + if name in self.__subst_dict: + name = self.__subst_dict[name] + return getattr(self,name) + #end - if name in self.__descriptors: - # This can only happen only if descriptor is called through synonims dictionary + if name in self.__descriptors: + # This can only happen only if descriptor is called through synonims dictionary # This to work, all descriptors should define getter to return self on Null instance. - descr=getattr(PropertyManager,name) - return descr.__get__(self,name) - else: - return prop_helpers.gen_getter(self.__dict__,name) + descr=getattr(PropertyManager,name) + return descr.__get__(self,name) + else: + return prop_helpers.gen_getter(self.__dict__,name) ##end #---------------------------------------------------------------------------------- # Overloaded setters/getters @@ -212,7 +212,7 @@ def __getattr__(self,name): monovan_integr_range = MonovanIntegrationRange() # spectra_to_monitors_list = SpectraToMonitorsList() - # + # save_format = SaveFormat() # hardmaskOnly = HardMaskOnly() @@ -226,7 +226,7 @@ def __getattr__(self,name): # Properties with allowed value normalise_method= PropertyFromRange([None,'monitor-1','monitor-2','current'],'current') deltaE_mode = PropertyFromRange(['direct'],'direct') # other modes should not be considered here - # + # multirep_tof_specta_list=MultirepTOFSpectraList() # mono_correction_factor = MonoCorrectionFactor(NonIDF_Properties.incident_energy) @@ -237,7 +237,7 @@ def getChangedProperties(self): decor_prop = '_'+type(self).__name__+'__changed_properties' return self.__dict__[decor_prop] def setChangedProperties(self,value=set([])): - """ Method to clear changed properties list""" + """ Method to clear changed properties list""" if isinstance(value,set): decor_prop = '_'+type(self).__name__+'__changed_properties' self.__dict__[decor_prop] =value @@ -250,17 +250,17 @@ def relocate_dets(self) : return True else: return False - + def set_input_parameters_ignore_nan(self,**kwargs): - """ Like similar method set_input_parameters this one is used to - set changed parameters from dictionary of parameters. + """ Like similar method set_input_parameters this one is used to + set changed parameters from dictionary of parameters. - Unlike set_input_parameters, this method does not set parameter, - with value equal to None. As such, this method is used as interface to + Unlike set_input_parameters, this method does not set parameter, + with value equal to None. As such, this method is used as interface to set data from a function with a list of given parameters (*args vrt **kwargs), with some parameters missing. - """ - # if sum is in parameters one needs to set it first + """ + # if sum is in parameters one needs to set it first if 'sum_runs' in kwargs and not (kwargs['sum_runs'] is None): self.sum_runs = kwargs['sum_runs'] del kwargs['sum_runs'] @@ -280,7 +280,7 @@ def set_input_parameters(self,**kwargs): """ # if sum is in parameters one needs to set it first to interpret - # + # if 'sum_runs' in kwargs : self.sum_runs = kwargs['sum_runs'] del kwargs['sum_runs'] @@ -295,7 +295,7 @@ def set_input_parameters(self,**kwargs): return self.getChangedProperties() def get_used_monitors_list(self): - """ Method returns list of monitors ID used during reduction """ + """ Method returns list of monitors ID used during reduction """ used_mon=set() for case in common.switch(self.normalise_method): @@ -306,7 +306,7 @@ def get_used_monitors_list(self): used_mon.add(self.mon2_norm_spec) break if case(): # default, could also just omit condition or 'if True' - pass + pass used_mon.add(self.ei_mon1_spec) used_mon.add(self.ei_mon2_spec) @@ -316,9 +316,9 @@ def get_used_monitors_list(self): def get_diagnostics_parameters(self): """ Return the dictionary of the properties used in diagnostics with their values defined in IDF - + if some values are not in IDF, default values are used instead - """ + """ diag_param_list ={'tiny':1e-10, 'huge':1e10, 'samp_zero':False, 'samp_lo':0.0, 'samp_hi':2,'samp_sig':3,\ 'van_out_lo':0.01, 'van_out_hi':100., 'van_lo':0.1, 'van_hi':1.5, 'van_sig':0.0, 'variation':1.1,\ @@ -330,26 +330,26 @@ def get_diagnostics_parameters(self): for key,val in diag_param_list.iteritems(): try: result[key] = getattr(self,key) - except KeyError: + except KeyError: self.log('--- Diagnostics property {0} is not found in instrument properties. Default value: {1} is used instead \n'.format(key,value),'warning') - + return result def update_defaults_from_instrument(self,pInstrument,ignore_changes=False): """ Method used to update default parameters from the same instrument (with different parameters). - Used if initial parameters correspond to instrument with one validity dates and - current instrument has different validity dates and different default values for + Used if initial parameters correspond to instrument with one validity dates and + current instrument has different validity dates and different default values for these dates. - List of synonims is not modified and new properties are not added assuming that + List of synonims is not modified and new properties are not added assuming that recent dictionary and properties are most comprehensive one ignore_changes==True when changes, caused by setting properties from instrument are not recorded - ignore_changes==False -- getChangedProperties properties after applied this method would return set + ignore_changes==False -- getChangedProperties properties after applied this method would return set of all properties changed when applying this method - """ + """ if self.instr_name != pInstrument.getName(): self.log("*** WARNING: Setting reduction properties of the instrument {0} from the instrument {1}.\n" "*** This only works if both instruments have the same reduction properties!"\ @@ -362,48 +362,48 @@ def update_defaults_from_instrument(self,pInstrument,ignore_changes=False): for prop_name in old_changes_list: old_changes[prop_name] = getattr(self,prop_name) - + param_list = prop_helpers.get_default_idf_param_list(pInstrument) # remove old changes which are not related to IDF (not to reapply it again) for prop_name in old_changes: if not (prop_name in param_list): - try: - dependencies = getattr(PropertyManager,prop_name).dependencies() - except: - dependencies = [] - modified = False - for name in dependencies: - if name in param_list: - modified = True - break - if not modified: - del old_changes[prop_name] + try: + dependencies = getattr(PropertyManager,prop_name).dependencies() + except: + dependencies = [] + modified = False + for name in dependencies: + if name in param_list: + modified = True + break + if not modified: + del old_changes[prop_name] #end param_list,descr_dict = self._convert_params_to_properties(param_list,False,self.__descriptors) # clear record about previous changes self.setChangedProperties(set()) - #sort parameters to have complex properties (with underscore _) first + #sort parameters to have complex properties (with underscore _) first sorted_param = OrderedDict(sorted(param_list.items(),key=lambda x : ord((x[0][0]).lower()))) - # Walk through descriptors list and set their values + # Walk through descriptors list and set their values # Assignment to descriptors should accept the form, descriptor is written in IDF changed_descriptors = set() for key,val in descr_dict.iteritems(): if not (key in old_changes_list): - try: # this is reliability check, and except ideally should never be hit. May occur if old IDF contains + try: # this is reliability check, and except ideally should never be hit. May occur if old IDF contains # properties, not present in recent IDF. - cur_val = getattr(self,key) - setattr(self,key,val) - new_val = getattr(self,key) + cur_val = getattr(self,key) + setattr(self,key,val) + new_val = getattr(self,key) except: - self.log("property {0} have not been found in existing IDF. Ignoring this property"\ + self.log("property {0} have not been found in existing IDF. Ignoring this property"\ .format(key),'warning') - continue + continue if isinstance(new_val,api.Workspace) and isinstance(cur_val,api.Workspace): - # do simplified workspace comparison which is appropriate here - if new_val.name() == cur_val.name() and \ + # do simplified workspace comparison which is appropriate here + if new_val.name() == cur_val.name() and \ new_val.getNumberHistograms() == cur_val.getNumberHistograms() and \ new_val.getNEvents() == cur_val.getNEvents() and \ new_val.getAxis(0).getUnit().unitID() == cur_val.getAxis(0).getUnit().unitID(): @@ -411,16 +411,16 @@ def update_defaults_from_instrument(self,pInstrument,ignore_changes=False): # #end if new_val != cur_val: - changed_descriptors.add(key) + changed_descriptors.add(key) # dependencies removed either properties are equal or not try: - dependencies = getattr(PropertyManager,key).dependencies() + dependencies = getattr(PropertyManager,key).dependencies() except: - dependencies = [] + dependencies = [] for dep_name in dependencies: if dep_name in sorted_param: - del sorted_param[dep_name] + del sorted_param[dep_name] else: # remove property from old changes list not to reapply it again? pass #end loop @@ -439,21 +439,21 @@ def update_defaults_from_instrument(self,pInstrument,ignore_changes=False): public_name = key prop_new_val = val - try: # this is reliability check, and except ideally should never be hit. May occur if old IDF contains + try: # this is reliability check, and except ideally should never be hit. May occur if old IDF contains # properties, not present in recent IDF. - cur_val = getattr(self,public_name) + cur_val = getattr(self,public_name) except: self.log("property {0} have not been found in existing IDF. Ignoring this property"\ .format(public_name),'warning') continue if prop_new_val !=cur_val : - setattr(self,public_name,prop_new_val) + setattr(self,public_name,prop_new_val) # Dependencies removed either properties are equal or not try: - dependencies = val.dependencies() + dependencies = val.dependencies() except: - dependencies =[] + dependencies =[] for dep_name in dependencies: # delete dependent properties not to deal with them again del sorted_param[dep_name] @@ -462,11 +462,11 @@ def update_defaults_from_instrument(self,pInstrument,ignore_changes=False): new_changes_list = self.getChangedProperties() self.setChangedProperties(set()) - # set back all changes stored earlier and may be overwritten by new IDF + # set back all changes stored earlier and may be overwritten by new IDF # (this is just to be sure -- should not change anything as we do not set properties changed) for key,val in old_changes.iteritems(): setattr(self,key,val) - + # Clear changed properties list (is this wise?, may be we want to know that some defaults changed?) if ignore_changes: self.setChangedProperties(old_changes_list) @@ -505,8 +505,8 @@ def check_files_list(files_list): if not (file is None) and isinstance(file,str): file_path = self._check_file_exist(file) if len(file_path)==0: - self.log(" Can not find file ""{0}"" for property: {1} ".format(file,prop),'error') - file_missing=True + self.log(" Can not find file ""{0}"" for property: {1} ".format(file,prop),'error') + file_missing=True return file_missing @@ -516,7 +516,7 @@ def check_files_list(files_list): abs_file_missing = check_files_list(self.__abs_norm_file_properties) if base_file_missing or abs_file_missing: - raise RuntimeError(" Files needed for the run are missing ") + raise RuntimeError(" Files needed for the run are missing ") # def _check_monovan_par_changed(self): """ method verifies, if properties necessary for monovanadium reduction have indeed been changed from defaults """ @@ -532,62 +532,62 @@ def _check_monovan_par_changed(self): # def log_changed_values(self,log_level='notice',display_header=True,already_changed=set()): - """ inform user about changed parameters and about the parameters that should be changed but have not - + """ inform user about changed parameters and about the parameters that should be changed but have not + This method is abstract method of NonIDF_Properties but is fully defined in PropertyManager - display_header==True prints nice additional information about run. If False, only + display_header==True prints nice additional information about run. If False, only list of changed properties displayed. """ - if display_header: + if display_header: # we may want to run absolute units normalization and this function has been called with monovan run or helper procedure - if self.monovan_run != None : + if self.monovan_run != None : # check if mono-vanadium is provided as multiple files list or just put in brackets occasionally - self.log("****************************************************************",'notice') - self.log('*** Output will be in absolute units of mb/str/mev/fu','notice') - non_changed = self._check_monovan_par_changed() - if len(non_changed) > 0: - for prop in non_changed: - value = getattr(self,prop) - message = "\n***WARNING!: Abs units norm. parameter : {0} not changed from default val: {1}"\ + self.log("****************************************************************",'notice') + self.log('*** Output will be in absolute units of mb/str/mev/fu','notice') + non_changed = self._check_monovan_par_changed() + if len(non_changed) > 0: + for prop in non_changed: + value = getattr(self,prop) + message = "\n***WARNING!: Abs units norm. parameter : {0} not changed from default val: {1}"\ "\n This may need to change for correct absolute units reduction\n" - self.log(message.format(prop,value),'warning') + self.log(message.format(prop,value),'warning') # now let's report on normal run. - if PropertyManager.incident_energy.multirep_mode(): - ei = self.incident_energy - mess = "*** Provisional Incident energies: {0:>8.3f}".format(ei[0]) - for en in ei[1:]: - mess += "; {0:>8.3f}".format(en) - mess+=" mEv" - self.log(mess,log_level) - else: - self.log("*** Provisional Incident energy: {0:>12.3f} mEv".format(self.incident_energy),log_level) + if PropertyManager.incident_energy.multirep_mode(): + ei = self.incident_energy + mess = "*** Provisional Incident energies: {0:>8.3f}".format(ei[0]) + for en in ei[1:]: + mess += "; {0:>8.3f}".format(en) + mess+=" mEv" + self.log(mess,log_level) + else: + self.log("*** Provisional Incident energy: {0:>12.3f} mEv".format(self.incident_energy),log_level) #end display_header - self.log("****************************************************************",log_level) - changed_Keys= self.getChangedProperties() - for key in changed_Keys: - if key in already_changed: - continue - val = getattr(self,key) - self.log(" Value of : {0:<25} is set to : {1:<20} ".format(key,val),log_level) - - if not display_header: - return - - save_dir = config.getString('defaultsave.directory') - self.log("****************************************************************",log_level) - if self.monovan_run != None and not('van_mass' in changed_Keys): # This output is - self.log("*** Monochromatic vanadium mass used : {0} ".format(self.van_mass),log_level) # Adroja request from may 2014 + self.log("****************************************************************",log_level) + changed_Keys= self.getChangedProperties() + for key in changed_Keys: + if key in already_changed: + continue + val = getattr(self,key) + self.log(" Value of : {0:<25} is set to : {1:<20} ".format(key,val),log_level) + + if not display_header: + return + + save_dir = config.getString('defaultsave.directory') + self.log("****************************************************************",log_level) + if self.monovan_run != None and not('van_mass' in changed_Keys): # This output is + self.log("*** Monochromatic vanadium mass used : {0} ".format(self.van_mass),log_level) # Adroja request from may 2014 # - self.log("*** By default results are saved into: {0}".format(save_dir),log_level) - self.log("*** Output will be normalized to {0}".format(self.normalise_method),log_level) - if self.map_file == None: + self.log("*** By default results are saved into: {0}".format(save_dir),log_level) + self.log("*** Output will be normalized to {0}".format(self.normalise_method),log_level) + if self.map_file == None: self.log('*** one2one map selected',log_level) - self.log("****************************************************************",log_level) + self.log("****************************************************************",log_level) #def help(self,keyword=None) : diff --git a/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py b/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py index 3aaa2f271fa9..73c3b8038457 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py +++ b/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py @@ -2,13 +2,13 @@ import os """ -Set of functions to assist with processing instrument parameters relevant to reduction. +Set of functions to assist with processing instrument parameters relevant to reduction. """ class ComplexProperty(object): - """ Class describes property which depends on other properties and stores/receives values in other properties """ + """ Class describes property which depends on other properties and stores/receives values in other properties """ def __init__(self,other_prop_list): - self._other_prop = other_prop_list; - + self._other_prop = other_prop_list + def __get__(self,spec_dict,owner=None): """ return complex properties list """ if spec_dict is None: @@ -19,24 +19,24 @@ def __get__(self,spec_dict,owner=None): spec_dict = spec_dict.__dict__ rez = list() for key in self._other_prop: - rez.append(spec_dict[key]); - return rez; + rez.append(spec_dict[key]) + return rez def __set__(self,instance,value): try: lv = len(value) except: - raise KeyError("Complex property values can be assigned only by list of other values"); + raise KeyError("Complex property values can be assigned only by list of other values") if lv != len(self._other_prop): - raise KeyError("Complex property values can be set equal to the same length values list"); + raise KeyError("Complex property values can be set equal to the same length values list") if isinstance(instance,dict): spec_dict = instance else: spec_dict = instance.__dict__ - + #changed_prop=[]; for key,val in zip(self._other_prop,value): - spec_dict[key] =val; + spec_dict[key] =val #changed_prop.append(key); #return changed_prop; def dependencies(self): @@ -52,37 +52,37 @@ def len(self): def get_default_parameter(instrument, name): - """ Function gets the value of a default instrument parameter and - assign proper(the one defined in IPF ) type to this parameter - @param instrument -- - """ - - if instrument is None: - raise ValueError("Cannot initiate default parameter, instrument has not been properly defined.") - - type_name = instrument.getParameterType(name) - if type_name == "double": - val = instrument.getNumberParameter(name) - elif type_name == "bool": - val = instrument.getBoolParameter(name) - elif type_name == "string": - val = instrument.getStringParameter(name) - if val[0] == "None" : - return None - elif type_name == "int" : - val = instrument.getIntParameter(name) - else : - raise KeyError(" Instrument: {0} does not have parameter with name: {1}".format(instrument.getName(),name)) - - return val[0] + """ Function gets the value of a default instrument parameter and + assign proper(the one defined in IPF ) type to this parameter + @param instrument -- + """ + + if instrument is None: + raise ValueError("Cannot initiate default parameter, instrument has not been properly defined.") + + type_name = instrument.getParameterType(name) + if type_name == "double": + val = instrument.getNumberParameter(name) + elif type_name == "bool": + val = instrument.getBoolParameter(name) + elif type_name == "string": + val = instrument.getStringParameter(name) + if val[0] == "None" : + return None + elif type_name == "int" : + val = instrument.getIntParameter(name) + else : + raise KeyError(" Instrument: {0} does not have parameter with name: {1}".format(instrument.getName(),name)) + + return val[0] def get_default_idf_param_list(pInstrument,synonims_list=None): """ Obtain default reduction parameters list from the instrument """ - params = pInstrument.getParameterNames(); - par_list = {}; + params = pInstrument.getParameterNames() + par_list = {} for name in params: - par_list[name] = get_default_parameter(pInstrument,name); + par_list[name] = get_default_parameter(pInstrument,name) return par_list @@ -91,25 +91,25 @@ def get_default_idf_param_list(pInstrument,synonims_list=None): def build_properties_dict(param_map,synonims,descr_list=[]) : """ function builds the properties list from the properties strings obtained from Insturment_Parameters.xml file - + The properties, which have simple values are added to dictionary in the form: properties_dict[prop_name]=(False,value); - The properties, expressed trough the values of other properties - e.g. strings in a form key1 = key2:key3 + The properties, expressed trough the values of other properties + e.g. strings in a form key1 = key2:key3 are added to the dictionary in the form: in the form properties_dict[key1]=(True,['key2','key3']) - """ + """ # dictionary used for substituting composite keys. prelim_dict = dict() for name in param_map: - if name in synonims: - final_name = str(synonims[name]) - else: - final_name = str(name) - prelim_dict[final_name]=None + if name in synonims: + final_name = str(synonims[name]) + else: + final_name = str(name) + prelim_dict[final_name]=None param_keys = prelim_dict.keys() properties_dict = dict() @@ -124,46 +124,46 @@ def build_properties_dict(param_map,synonims,descr_list=[]) : if final_name in descr_list: is_descriptor = True - if isinstance(val,str): - val = val.strip() - keys_candidates = val.split(":") - n_keys = len(keys_candidates) + if isinstance(val,str): + val = val.strip() + keys_candidates = val.split(":") + n_keys = len(keys_candidates) # - if n_keys>1 : # this is the property we want to modify - result=list() - for key in keys_candidates : - if key in synonims: - rkey = str(synonims[key]) - else: - rkey = str(key) - if rkey in param_keys: - result.append(rkey) - else: - raise KeyError('Substitution key : {0} is not in the list of allowed keys'.format(rkey)) - if is_descriptor: - descr_dict[final_name] = result - else: - properties_dict['_'+final_name]=ComplexProperty(result) - else: - if is_descriptor: - descr_dict[final_name] = keys_candidates[0] - else: - properties_dict[final_name] =keys_candidates[0] + if n_keys>1 : # this is the property we want to modify + result=list() + for key in keys_candidates : + if key in synonims: + rkey = str(synonims[key]) + else: + rkey = str(key) + if rkey in param_keys: + result.append(rkey) + else: + raise KeyError('Substitution key : {0} is not in the list of allowed keys'.format(rkey)) + if is_descriptor: + descr_dict[final_name] = result + else: + properties_dict['_'+final_name]=ComplexProperty(result) + else: + if is_descriptor: + descr_dict[final_name] = keys_candidates[0] + else: + properties_dict[final_name] =keys_candidates[0] else: - if is_descriptor: + if is_descriptor: descr_dict[final_name] = val - else: + else: properties_dict[final_name]=val return (properties_dict,descr_dict) def extract_non_system_names(names_list,prefix='_'): - """ The function processes the input list and returns - the list with names which do not have the system framing (leading __) + """ The function processes the input list and returns + the list with names which do not have the system framing (leading __) """ - result = list(); - ns = len(prefix); + result = list() + ns = len(prefix) for name in names_list: pend = min(ns,len(name)) if name[:pend] != prefix: @@ -180,11 +180,11 @@ def build_subst_dictionary(synonims_list=None) : norm-mon1-spec=my_detector in the synonyms field of the IDF parameters file. """ if not synonims_list : # nothing to do - return dict(); + return dict() if type(synonims_list) == dict : # all done - return synonims_list + return synonims_list if type(synonims_list) != str : - raise AttributeError("The synonyms field of Reducer object has to be special format string or the dictionary") + raise AttributeError("The synonyms field of Reducer object has to be special format string or the dictionary") # we are in the right place and going to transform string into dictionary subst_lines = synonims_list.split(";") @@ -193,20 +193,20 @@ def build_subst_dictionary(synonims_list=None) : lin=lin.strip() keys = lin.split("=") if len(keys) < 2 : - raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present") + raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present") if len(keys[0]) == 0: - raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present, but the first key is empty") + raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present, but the first key is empty") for i in xrange(1,len(keys)) : - if len(keys[i]) == 0 : - raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present, but the key"+str(i)+" is empty") - kkk = keys[i].strip(); - rez[kkk]=keys[0].strip() + if len(keys[i]) == 0 : + raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present, but the key"+str(i)+" is empty") + kkk = keys[i].strip() + rez[kkk]=keys[0].strip() return rez def gen_getter(keyval_dict,key): - """ function returns value from dictionary with substitution - + """ function returns value from dictionary with substitution + e.g. if keyval_dict[A] = 10, keyval_dict[B] = 20 and key_val[C] = [A,B] gen_getter(keyval_dict,A) == 10; gen_getter(keyval_dict,B) == 20; and gen_getter(keyval_dict,C) == [10,20]; @@ -214,11 +214,11 @@ def gen_getter(keyval_dict,key): if not(key in keyval_dict): name = '_'+key if not(name in keyval_dict): - raise KeyError('Property with name: {0} is not among the class properties '.format(key)); + raise KeyError('Property with name: {0} is not among the class properties '.format(key)) else: name = key - a_val= keyval_dict[name]; + a_val= keyval_dict[name] if isinstance(a_val,ComplexProperty): return a_val.__get__(keyval_dict) else: @@ -229,8 +229,8 @@ def gen_getter(keyval_dict,key): def gen_setter(keyval_dict,key,val): - """ function sets value to dictionary with substitution - + """ function sets value to dictionary with substitution + e.g. if keyval_dict[A] = 10, keyval_dict[B] = 20 and key_val[C] = [A,B] gen_setter(keyval_dict,A,20) causes keyval_dict[A] == 20 @@ -245,16 +245,16 @@ def gen_setter(keyval_dict,key,val): else: name = key - test_val = keyval_dict[name]; + test_val = keyval_dict[name] if isinstance(test_val,ComplexProperty): - if not isinstance(val,list): - raise KeyError(' You can not assign non-list value to complex property {0}'.format(key)) - pass + if not isinstance(val,list): + raise KeyError(' You can not assign non-list value to complex property {0}'.format(key)) + pass # Assigning values for composite function to the function components - test_val.__set__(keyval_dict,val) - return None + test_val.__set__(keyval_dict,val) + return None else: - keyval_dict[key] = val; + keyval_dict[key] = val return None @@ -263,13 +263,13 @@ def check_instrument_name(old_name,new_name): if new_name is None: - if not(old_name is None): + if not(old_name is None): return (None,None,str(config.getFacility())) - else: + else: raise KeyError("No instrument name is defined") if old_name == new_name: - return; + return # Instrument name might be a prefix, query Mantid for the full name short_name='' @@ -283,18 +283,18 @@ def check_instrument_name(old_name,new_name): facilities = config.getFacilities() old_facility = str(config.getFacility()) for facility in facilities: - config.setString('default.facility',facility.name()) - try : - instrument = facility.instrument(new_name) - short_name = instrument.shortName() - full_name = instrument.name() - if len(short_name)>0 : - break - except: - pass + config.setString('default.facility',facility.name()) + try : + instrument = facility.instrument(new_name) + short_name = instrument.shortName() + full_name = instrument.name() + if len(short_name)>0 : + break + except: + pass if len(short_name)==0 : - config.setString('default.facility',old_facility) - raise KeyError(" Can not find/set-up the instrument: "+new_name+' in any supported facility') + config.setString('default.facility',old_facility) + raise KeyError(" Can not find/set-up the instrument: "+new_name+' in any supported facility') new_name = short_name facility = str(config.getFacility()) @@ -306,23 +306,23 @@ def parse_single_name(filename): """ Process single run name into """ filepath,fname = os.path.split(filename) if ':' in fname: - fl,fr=fname.split(':') - path1,ind1,ext1=parse_single_name(fl) - path2,ind2,ext2=parse_single_name(fr) - if ind1>ind2: - raise ValueError('Invalid file number defined using colon : left run number {0} has to be large then right {1}'.format(ind1,ind2)) - number = range(ind1[0],ind2[0]+1) - if len(filepath)>0: - filepath=[filepath]*len(number) - else: - filepath=path1*len(number) - if len(ext2[0])>0: - fext = ext2*len(number) - else: - fext = ext1*len(number) - - return (filepath,number,fext) - + fl,fr=fname.split(':') + path1,ind1,ext1=parse_single_name(fl) + path2,ind2,ext2=parse_single_name(fr) + if ind1>ind2: + raise ValueError('Invalid file number defined using colon : left run number {0} has to be large then right {1}'.format(ind1,ind2)) + number = range(ind1[0],ind2[0]+1) + if len(filepath)>0: + filepath=[filepath]*len(number) + else: + filepath=path1*len(number) + if len(ext2[0])>0: + fext = ext2*len(number) + else: + fext = ext1*len(number) + + return (filepath,number,fext) + fname,fext = os.path.splitext(fname) fnumber = filter(lambda x: x.isdigit(), fname) @@ -331,7 +331,7 @@ def parse_single_name(filename): else: number = int(fnumber) return ([filepath],[number],[fext]) - + def parse_run_file_name(run_string): """ Parses run file name to obtain run number, path if possible, and file extension if any present in the string""" @@ -363,5 +363,5 @@ def parse_run_file_name(run_string): # extensions should be either all the same or all defined return (filepath,filenum,fext) - + diff --git a/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py b/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py index f7e35393991e..fa65b83f4067 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py +++ b/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py @@ -11,11 +11,11 @@ class ReductionWrapper(object): - """ Abstract class provides interface to direct inelastic reduction - allowing it to be run from Mantid, web services, or system tests - using the same interface and the same run file placed in different + """ Abstract class provides interface to direct inelastic reduction + allowing it to be run from Mantid, web services, or system tests + using the same interface and the same run file placed in different locations. - """ + """ class var_holder(object): """ A simple wrapper class to keep web variables""" def __init__(self): @@ -24,46 +24,46 @@ def __init__(self): pass def __init__(self,instrumentName,web_var=None): - """ sets properties defaults for the instrument with Name + """ sets properties defaults for the instrument with Name and define if wrapper runs from web services or not """ # internal variable, indicating if we should try to wait for input files to appear - self._wait_for_file=False + self._wait_for_file=False - # The variables which are set up from web interface or to be exported to + # The variables which are set up from web interface or to be exported to # web interface - if web_var: - self._run_from_web = True - self._wvs = web_var - else: - self._run_from_web = False - self._wvs = ReductionWrapper.var_holder() + if web_var: + self._run_from_web = True + self._wvs = web_var + else: + self._run_from_web = False + self._wvs = ReductionWrapper.var_holder() # Initialize reduced for given instrument - self.reducer = DirectEnergyConversion(instrumentName) + self.reducer = DirectEnergyConversion(instrumentName) - self._validation_fname=None + self._validation_fname=None # def get_validation_file_name(self,ReferenceFile=None): - """ function provides name of the file with mantid - workspace reduced earlier and which should be validated + """ function provides name of the file with mantid + workspace reduced earlier and which should be validated against results of current reduction Should be overloaded to return real file name for particular reduction - """ - if ReferenceFile: - self._validation_fname = ReferenceFile - return self._validation_fname + """ + if ReferenceFile: + self._validation_fname = ReferenceFile + return self._validation_fname @property def wait_for_file(self): """ If this variable set to positive value, this value - is interpreted as time to wait until check for specified run file - if this file have not been find immediately. + is interpreted as time to wait until check for specified run file + if this file have not been find immediately. if this variable is 0 or false and the the file have not been found, reduction will fail - """ + """ return self._wait_for_file @wait_for_file.setter @@ -74,72 +74,72 @@ def wait_for_file(self,value): self._wait_for_file = False # def save_web_variables(self,FileName=None): - """ Method to write simple and advanced properties and help + """ Method to write simple and advanced properties and help information into dictionary, to use by web reduction interface - If no file is provided, reduce_var.py file will be written - to + If no file is provided, reduce_var.py file will be written + to """ if not FileName: FileName = 'reduce_vars.py' - + f=open(FileName,'w') f.write("standard_vars = {\n") str_wrapper = ' ' for key,val in self._wvs.standard_vars.iteritems(): - if isinstance(val,str): - row = "{0}\'{1}\':\'{2}\'".format(str_wrapper,key,val) - else: - row = "{0}\'{1}\':{2}".format(str_wrapper,key,val) - f.write(row) - str_wrapper=',\n ' + if isinstance(val,str): + row = "{0}\'{1}\':\'{2}\'".format(str_wrapper,key,val) + else: + row = "{0}\'{1}\':{2}".format(str_wrapper,key,val) + f.write(row) + str_wrapper=',\n ' f.write("\n}\nadvanced_vars={\n") str_wrapper=' ' for key,val in self._wvs.advanced_vars.iteritems(): - if isinstance(val,str): - row = "{0}\'{1}\':\'{2}\'".format(str_wrapper,key,val) - else: - row = "{0}\'{1}\':{2}".format(str_wrapper,key,val) - f.write(row) - str_wrapper=',\n ' + if isinstance(val,str): + row = "{0}\'{1}\':\'{2}\'".format(str_wrapper,key,val) + else: + row = "{0}\'{1}\':{2}".format(str_wrapper,key,val) + f.write(row) + str_wrapper=',\n ' f.write("\n}\n") f.close() # -# +# def validate_result(self,build_validation=False,Error=1.e-3,ToleranceRelErr=True): - """ Overload this using build_or_validate_result to have possibility to run or validate result """ + """ Overload this using build_or_validate_result to have possibility to run or validate result """ return True def build_or_validate_result(self,sample_run,validationFile,build_validation=False,Error=1.e-3,ToleranceRelErr=True): """ Method validates results of the reduction against reference file provided - by get_validation_file_name() method - + by get_validation_file_name() method + At the moment, get_validation_file_name method should return the name of a file, - where workspace sample reduced workspace with default properties - is stored. - CheckWorkspaceMatch method is applied to verify if current reduced workspace is - equivalent to the workspace, stored in the reference file. + where workspace sample reduced workspace with default properties + is stored. + CheckWorkspaceMatch method is applied to verify if current reduced workspace is + equivalent to the workspace, stored in the reference file. """ if not build_validation: - if validationFile: - if isinstance(validationFile,api.Workspace): - sample = validationFile - validationFile = sample.name() - else: - sample = Load(validationFile) - else: - build_validation=True + if validationFile: + if isinstance(validationFile,api.Workspace): + sample = validationFile + validationFile = sample.name() + else: + sample = Load(validationFile) + else: + build_validation=True # just in case, to be sure current_web_state = self._run_from_web current_wait_state= self.wait_for_file - # disable wait for input and + # disable wait for input and self._run_from_web = False self.wait_for_file = False # @@ -153,9 +153,9 @@ def build_or_validate_result(self,sample_run,validationFile,build_validation=Fal if build_validation: if validationFile: - result_name = os.path.splitext(validationFile)[0] + result_name = os.path.splitext(validationFile)[0] else: - result_name = self.reducer.prop_man.save_file_name + result_name = self.reducer.prop_man.save_file_name self.reducer.prop_man.log("*** Saving validation file with name: {0}.nxs".format(result_name),'notice') SaveNexus(reduced,Filename=result_name+'.nxs') return True,'Created validation file {0}.nxs'.format(result_name) @@ -167,7 +167,7 @@ def build_or_validate_result(self,sample_run,validationFile,build_validation=Fal CheckInstrument=False,ToleranceRelErr=ToleranceRelErr) self.wait_for_file = current_wait_state - self._run_from_web = current_web_state + self._run_from_web = current_web_state if result == 'Success!': return True,'Reference file and reduced workspace are equivalent' else: @@ -176,35 +176,35 @@ def build_or_validate_result(self,sample_run,validationFile,build_validation=Fal @abstractmethod def def_main_properties(self): """ Define properties which considered to be main properties changeable by user - - Should be overwritten by special reduction and decorated with @MainProperties decorator. - Should return dictionary with key are the properties names and values -- the default + Should be overwritten by special reduction and decorated with @MainProperties decorator. + + Should return dictionary with key are the properties names and values -- the default values these properties should have. - """ + """ raise NotImplementedError('def_main_properties has to be implemented') @abstractmethod def def_advanced_properties(self): """ Define properties which considered to be advanced but still changeable by instrument scientist or advanced user - - Should be overwritten by special reduction and decorated with @AdvancedProperties decorator. - Should return dictionary with key are the properties names and values -- the default + Should be overwritten by special reduction and decorated with @AdvancedProperties decorator. + + Should return dictionary with key are the properties names and values -- the default values these properties should have. - """ + """ raise NotImplementedError('def_advanced_properties has to be implemented') def reduce(self,input_file=None,output_directory=None): - """ The method performs all main reduction operations over + """ The method performs all main reduction operations over single run file - - Wrap it into @iliad wrapper to switch input for + + Wrap it into @iliad wrapper to switch input for reduction properties between script and web variables - """ + """ if input_file: - self.reducer.sample_run = input_file + self.reducer.sample_run = input_file timeToWait = self._wait_for_file if timeToWait: @@ -227,7 +227,7 @@ def reduce(self,input_file=None,output_directory=None): def MainProperties(main_prop_definition): """ Decorator stores properties dedicated as main and sets these properties - as input to reduction parameters.""" + as input to reduction parameters.""" def main_prop_wrapper(*args): # execute decorated function prop_dict = main_prop_definition(*args) @@ -243,7 +243,7 @@ def main_prop_wrapper(*args): def AdvancedProperties(adv_prop_definition): """ Decorator stores properties decided to be advanced and sets these properties as input for reduction parameters - """ + """ def advanced_prop_wrapper(*args): prop_dict = adv_prop_definition(*args) #print "in decorator: ",properties @@ -257,7 +257,7 @@ def advanced_prop_wrapper(*args): def iliad(reduce): - """ This decorator wraps around main procedure and switch input from + """ This decorator wraps around main procedure and switch input from web variables to properties or vise versa depending on web variables presence """ @@ -282,39 +282,39 @@ def iliad_wrapper(*args): output_directory=None # add input file folder to data search directory if file has it if input_file and isinstance(input_file,str): - data_path = os.path.dirname(input_file) - if len(data_path)>0: - try: - config.appendDataSearchDir(str(data_path)) - args[1] = os.path.basename(input_file) - except: # if mantid is not available, this should ignore config - pass + data_path = os.path.dirname(input_file) + if len(data_path)>0: + try: + config.appendDataSearchDir(str(data_path)) + args[1] = os.path.basename(input_file) + except: # if mantid is not available, this should ignore config + pass if output_directory: - config['defaultsave.directory'] = output_directory + config['defaultsave.directory'] = output_directory if host._run_from_web: web_vars = dict(host._wvs.standard_vars.items()+host._wvs.advanced_vars.items()) host.reducer.prop_man.set_input_parameters(**web_vars) else: - pass # we should set already set up variables using + pass # we should set already set up variables using + - rez = reduce(*args) - # prohibit returning workspace to web services. + # prohibit returning workspace to web services. if host._run_from_web and not isinstance(rez,str): rez="" - else: - if isinstance(rez,list): + else: + if isinstance(rez,list): # multirep run, just return as it is - return rez - if out_ws_name and rez.name() != out_ws_name : - rez=RenameWorkspace(InputWorkspace=rez,OutputWorkspace=out_ws_name) - + return rez + if out_ws_name and rez.name() != out_ws_name : + rez=RenameWorkspace(InputWorkspace=rez,OutputWorkspace=out_ws_name) + return rez return iliad_wrapper - + if __name__=="__main__": - pass \ No newline at end of file + pass diff --git a/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py b/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py index 9edf8e9a1d86..e403133dc79b 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py +++ b/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py @@ -1,4 +1,4 @@ -""" File contains Descriptors used describe run for direct inelastic reduction """ +""" File contains Descriptors used describe run for direct inelastic reduction """ from mantid.simpleapi import * @@ -18,7 +18,7 @@ class RunDescriptor(PropDescriptor): # class level reference to the property manager _PropMan = None #-------------------------------------------------------------------------------------------------------------------- - def __init__(self,prop_name,DocString=None): + def __init__(self,prop_name,DocString=None): """ """ # Run number self._run_number = None @@ -40,103 +40,103 @@ def __init__(self,prop_name,DocString=None): self.__doc__ = DocString #-------------------------------------------------------------------------------------------------------------------- def __get__(self,instance,owner): - """ return current run number or workspace if it is loaded""" - if not RunDescriptor._PropMan: - RunDescriptor._PropMan = owner - if instance is None: - return self - - if self._ws_name and self._ws_name in mtd: - return mtd[self._ws_name] - else: - return self._run_number + """ return current run number or workspace if it is loaded""" + if not RunDescriptor._PropMan: + RunDescriptor._PropMan = owner + if instance is None: + return self + + if self._ws_name and self._ws_name in mtd: + return mtd[self._ws_name] + else: + return self._run_number #-------------------------------------------------------------------------------------------------------------------- def __set__(self,instance,value): - """ Set up Run number and define workspace name from any source """ + """ Set up Run number and define workspace name from any source """ # - if not RunDescriptor._PropMan: - from PropertyManager import PropertyManager - RunDescriptor._PropMan = PropertyManager + if not RunDescriptor._PropMan: + from PropertyManager import PropertyManager + RunDescriptor._PropMan = PropertyManager - old_ws_name = self._ws_name - clear_fext = True + old_ws_name = self._ws_name + clear_fext = True #end - if value == None: # clear current run number - self._run_number = None - self._ws_name = None - self._ws_cname = '' - self._ws_suffix = '' - # only one RunDescriptor can be summed under current approach. + if value == None: # clear current run number + self._run_number = None + self._ws_name = None + self._ws_cname = '' + self._ws_suffix = '' + # only one RunDescriptor can be summed under current approach. # To disentangle one run descriptor from another -- set up binding - self._bind_to_sum = False - self._clear_old_ws(old_ws_name,self._ws_name,clear_fext) - RunDescriptor._PropMan.sum_runs.clear_sum() - return - if isinstance(value, api.Workspace): + self._bind_to_sum = False + self._clear_old_ws(old_ws_name,self._ws_name,clear_fext) + RunDescriptor._PropMan.sum_runs.clear_sum() + return + if isinstance(value, api.Workspace): #if 'SumOfRuns:' in value.getRun(): # TODO: not implemented #else: - if self._ws_name != value.name(): + if self._ws_name != value.name(): self._set_ws_as_source(value) self._clear_old_ws(old_ws_name,self._ws_name,clear_fext) self._bind_to_sum = False RunDescriptor._PropMan.sum_runs.clear_sum() return - else: # it is just reassigning the same workspace to itself - return - - if isinstance(value,str): # it may be run number as string or it may be a workspace name - if value in mtd: # workspace name - ws = mtd[value] - self.__set__(instance,ws) - return - else: - file_path,run_num,fext = prop_helpers.parse_run_file_name(value) - - if isinstance(run_num,list): - RunDescriptor._PropMan.sum_runs.set_list2add(run_num,file_path,fext) - self._bind_to_sum = True - if instance.sum_runs: - last_run_ind = RunDescriptor._PropMan.sum_runs.get_last_ind2sum() - main_fext = fext[last_run_ind].lower() - self._run_file_path = file_path[last_run_ind].lower() - else: - self.__set__(instance,run_num) - self._run_file_path = file_path - main_fext = fext.lower() - + else: # it is just reassigning the same workspace to itself + return + + if isinstance(value,str): # it may be run number as string or it may be a workspace name + if value in mtd: # workspace name + ws = mtd[value] + self.__set__(instance,ws) + return + else: + file_path,run_num,fext = prop_helpers.parse_run_file_name(value) + + if isinstance(run_num,list): + RunDescriptor._PropMan.sum_runs.set_list2add(run_num,file_path,fext) + self._bind_to_sum = True + if instance.sum_runs: + last_run_ind = RunDescriptor._PropMan.sum_runs.get_last_ind2sum() + main_fext = fext[last_run_ind].lower() + self._run_file_path = file_path[last_run_ind].lower() + else: + self.__set__(instance,run_num) + self._run_file_path = file_path + main_fext = fext.lower() + # - if len(main_fext) > 0: - self._run_ext = main_fext - else: # will be default file extension - self._run_ext = None - clear_fext = False - elif isinstance(value,list): - if len(value) == 1: - self.__set__(instance,value[0]) - return - self._bind_to_sum = True - RunDescriptor._PropMan.sum_runs.set_list2add(value) - if instance.sum_runs: + if len(main_fext) > 0: + self._run_ext = main_fext + else: # will be default file extension + self._run_ext = None + clear_fext = False + elif isinstance(value,list): + if len(value) == 1: + self.__set__(instance,value[0]) + return + self._bind_to_sum = True + RunDescriptor._PropMan.sum_runs.set_list2add(value) + if instance.sum_runs: last_run_ind = RunDescriptor._PropMan.sum_runs.get_last_ind2sum() self._run_number = value[last_run_ind] - else: - self._run_number = value[0] - clear_fext = True - else: - clear_fext = True - self._run_number = int(value) - if self._bind_to_sum and instance and instance.sum_runs: - num2_sum = RunDescriptor._PropMan.sum_runs.set_last_ind2sum(self._run_number) - if num2_sum == 0: - self._bind_to_sum = False - instance.sum_runs = False + else: + self._run_number = value[0] + clear_fext = True + else: + clear_fext = True + self._run_number = int(value) + if self._bind_to_sum and instance and instance.sum_runs: + num2_sum = RunDescriptor._PropMan.sum_runs.set_last_ind2sum(self._run_number) + if num2_sum == 0: + self._bind_to_sum = False + instance.sum_runs = False - self._ws_cname = '' - self._ws_name = None - self._clear_old_ws(old_ws_name,None,clear_fext) + self._ws_cname = '' + self._ws_name = None + self._clear_old_ws(old_ws_name,None,clear_fext) #-------------------------------------------------------------------------------------------------------------------- def run_number(self): """ Return run number regardless of workspace is loaded or not""" @@ -144,7 +144,7 @@ def run_number(self): ws = mtd[self._ws_name] return ws.getRunNumber() else: - return self._run_number + return self._run_number #-------------------------------------------------------------------------------------------------------------------- def is_monws_separate(self): """ """ @@ -169,16 +169,16 @@ def get_run_list(self): else: return [current_run] else: - return [current_run] + return [current_run] #-------------------------------------------------------------------------------------------------------------------- def set_action_suffix(self,suffix=None): - """ method to set part of the workspace name, which indicate some action performed over this workspace - - e.g.: default suffix of a loaded workspace is 'RAW' but we can set it to SPE to show that conversion to + """ method to set part of the workspace name, which indicate some action performed over this workspace + + e.g.: default suffix of a loaded workspace is 'RAW' but we can set it to SPE to show that conversion to energy will be performed for this workspace. - method returns the name of the workspace is will have with this suffix. Algorithms would later - work on the initial workspace and modify it in-place or to produce workspace with new name (depending if one + method returns the name of the workspace is will have with this suffix. Algorithms would later + work on the initial workspace and modify it in-place or to produce workspace with new name (depending if one wants to keep initial workspace) synchronize_ws(ws_pointer) then should synchronize workspace and its name. @@ -193,32 +193,32 @@ def set_action_suffix(self,suffix=None): return self._build_ws_name() #-------------------------------------------------------------------------------------------------------------------- def synchronize_ws(self,workspace=None): - """ Synchronize workspace name (after workspace may have changed due to algorithm) - with internal run holder name. Accounts for the situation when + """ Synchronize workspace name (after workspace may have changed due to algorithm) + with internal run holder name. Accounts for the situation when TODO: This method should be automatically invoked by an algorithm decorator - Until implemented, one have to ensure that it is correctly used together with + Until implemented, one have to ensure that it is correctly used together with set_action_suffix to ensue one can always get expected workspace from its name - outside of a method visibility - """ + outside of a method visibility + """ if not workspace: workspace = mtd[self._ws_name] new_name = self._build_ws_name() old_name = workspace.name() if new_name != old_name: - RenameWorkspace(InputWorkspace=old_name,OutputWorkspace=new_name) + RenameWorkspace(InputWorkspace=old_name,OutputWorkspace=new_name) - old_mon_name = old_name + '_monitors' - new_mon_name = new_name + '_monitors' - if old_mon_name in mtd: - RenameWorkspace(InputWorkspace=old_mon_name,OutputWorkspace=new_mon_name) + old_mon_name = old_name + '_monitors' + new_mon_name = new_name + '_monitors' + if old_mon_name in mtd: + RenameWorkspace(InputWorkspace=old_mon_name,OutputWorkspace=new_mon_name) self._ws_name = new_name #-------------------------------------------------------------------------------------------------------------------- def get_file_ext(self): - """ Method returns current file extension for file to load workspace from + """ Method returns current file extension for file to load workspace from e.g. .raw or .nxs extension - """ + """ if self._run_ext: return self._run_ext else: # return IDF default @@ -237,23 +237,23 @@ def set_file_ext(self,val): #-------------------------------------------------------------------------------------------------------------------- @staticmethod def _check_claibration_source(): - """ if user have not specified calibration as input to the script, + """ if user have not specified calibration as input to the script, try to retrieve calibration stored in file with run properties""" - changed_prop = RunDescriptor._holder.getChangedProperties() - if 'det_cal_file' in changed_prop: - use_workspace_calibration = False - else: - use_workspace_calibration = True - return use_workspace_calibration + changed_prop = RunDescriptor._holder.getChangedProperties() + if 'det_cal_file' in changed_prop: + use_workspace_calibration = False + else: + use_workspace_calibration = True + return use_workspace_calibration #-------------------------------------------------------------------------------------------------------------------- def get_workspace(self): """ Method returns workspace correspondent to current run number(s) and loads this workspace if it has not been loaded Returns Mantid pointer to the workspace, corresponding to this run number - """ + """ if not self._ws_name: - self._ws_name = self._build_ws_name() + self._ws_name = self._build_ws_name() if self._ws_name in mtd: @@ -261,26 +261,26 @@ def get_workspace(self): if ws.run().hasProperty("calibrated"): return ws # already calibrated else: - prefer_ws_calibration = self._check_claibration_source() - self.apply_calibration(ws,RunDescriptor._holder.det_cal_file,prefer_ws_calibration) - return ws + prefer_ws_calibration = self._check_claibration_source() + self.apply_calibration(ws,RunDescriptor._holder.det_cal_file,prefer_ws_calibration) + return ws else: - if self._run_number: - prefer_ws_calibration = self._check_claibration_source() - inst_name = RunDescriptor._holder.short_inst_name - calibration = RunDescriptor._holder.det_cal_file - if self._bind_to_sum and RunDescriptor._holder.sum_runs : # Sum runs - ws = RunDescriptor._PropMan.sum_runs.load_and_sum_runs(inst_name,RunDescriptor._holder.load_monitors_with_workspace) - else: # load current workspace - ws = self.load_run(inst_name, calibration,False, RunDescriptor._holder.load_monitors_with_workspace,prefer_ws_calibration) - - - self.synchronize_ws(ws) - self.apply_calibration(ws,calibration,prefer_ws_calibration) - - return ws - else: - return None + if self._run_number: + prefer_ws_calibration = self._check_claibration_source() + inst_name = RunDescriptor._holder.short_inst_name + calibration = RunDescriptor._holder.det_cal_file + if self._bind_to_sum and RunDescriptor._holder.sum_runs : # Sum runs + ws = RunDescriptor._PropMan.sum_runs.load_and_sum_runs(inst_name,RunDescriptor._holder.load_monitors_with_workspace) + else: # load current workspace + ws = self.load_run(inst_name, calibration,False, RunDescriptor._holder.load_monitors_with_workspace,prefer_ws_calibration) + + + self.synchronize_ws(ws) + self.apply_calibration(ws,calibration,prefer_ws_calibration) + + return ws + else: + return None #-------------------------------------------------------------------------------------------------------------------- def get_ws_clone(self,clone_name='ws_clone'): """ Get unbounded clone of eisting Run workspace """ @@ -303,33 +303,33 @@ def _set_ws_as_source(self,value): #-------------------------------------------------------------------------------------------------------------------- def chop_ws_part(self,origin,tof_range,rebin,chunk_num,n_chunks): - """ chop part of the original workspace and sets it up as new original. - Return the old one """ + """ chop part of the original workspace and sets it up as new original. + Return the old one """ if not(origin): - origin = self.get_workspace() + origin = self.get_workspace() origin_name = origin.name() try: - mon_ws = mtd[origin_name+'_monitors'] + mon_ws = mtd[origin_name+'_monitors'] except: - mon_ws = None + mon_ws = None target_name = '#{0}/{1}#'.format(chunk_num,n_chunks)+origin_name if chunk_num == n_chunks: - RenameWorkspace(InputWorkspace=origin_name,OutputWorkspace=target_name) - if mon_ws: - RenameWorkspace(InputWorkspace=mon_ws,OutputWorkspace=target_name+'_monitors') - origin_name = target_name - origin_invalidated=True + RenameWorkspace(InputWorkspace=origin_name,OutputWorkspace=target_name) + if mon_ws: + RenameWorkspace(InputWorkspace=mon_ws,OutputWorkspace=target_name+'_monitors') + origin_name = target_name + origin_invalidated=True else: - if mon_ws: - CloneWorkspace(InputWorkspace=mon_ws,OutputWorkspace=target_name+'_monitors') - origin_invalidated=False + if mon_ws: + CloneWorkspace(InputWorkspace=mon_ws,OutputWorkspace=target_name+'_monitors') + origin_invalidated=False if rebin: # debug and compatibility mode with old reduction - Rebin(origin_name,OutputWorkspace=target_name,Params=[tof_range[0],tof_range[1],tof_range[2]],PreserveEvents=False) + Rebin(origin_name,OutputWorkspace=target_name,Params=[tof_range[0],tof_range[1],tof_range[2]],PreserveEvents=False) else: - CropWorkspace(origin_name,OutputWorkspace=target_name,XMin=tof_range[0],XMax=tof_range[2]) + CropWorkspace(origin_name,OutputWorkspace=target_name,XMin=tof_range[0],XMax=tof_range[2]) self._set_ws_as_source(mtd[target_name]) if origin_invalidated: @@ -339,7 +339,7 @@ def chop_ws_part(self,origin,tof_range,rebin,chunk_num,n_chunks): #-------------------------------------------------------------------------------------------------------------------- def get_monitors_ws(self,monitor_ID=None): - """ get pointer to a workspace containing monitors. + """ get pointer to a workspace containing monitors. Explores different ways of finding monitor workspace in Mantid and returns the python pointer to the workspace which contains monitors. @@ -360,39 +360,39 @@ def get_monitors_ws(self,monitor_ID=None): mon_ws = self.copy_spectrum2monitors(data_ws,mon_ws,specID) if monitor_ID: - try: - ws_index = mon_ws.getIndexFromSpectrumNumber(monitor_ID) - except: # - mon_ws = None - else: + try: + ws_index = mon_ws.getIndexFromSpectrumNumber(monitor_ID) + except: # + mon_ws = None + else: mon_list = self._holder.get_used_monitors_list() for monID in mon_list: try: ws_ind = mon_ws.getIndexFromSpectrumNumber(int(monID)) except: - mon_ws = None - break + mon_ws = None + break return mon_ws #-------------------------------------------------------------------------------------------------------------------- def get_ws_name(self): """ return workspace name. If ws name is not defined, build it first and set up as the target ws name - """ + """ if self._ws_name: if self._ws_name in mtd: return self._ws_name else: - raise RuntimeError('Getting workspace name {0} for undefined workspace. Run get_workspace first'.format(self._ws_name)) + raise RuntimeError('Getting workspace name {0} for undefined workspace. Run get_workspace first'.format(self._ws_name)) self._ws_name = self._build_ws_name() return self._ws_name #-------------------------------------------------------------------------------------------------------------------- def file_hint(self,run_num_str=None,filePath=None,fileExt=None,**kwargs): """ procedure to provide run file guess name from run properties - + main purpose -- to support customized order of file extensions - """ + """ if not run_num_str: - run_num_str = str(self.run_number()) + run_num_str = str(self.run_number()) inst_name = RunDescriptor._holder.short_inst_name @@ -403,9 +403,9 @@ def file_hint(self,run_num_str=None,filePath=None,fileExt=None,**kwargs): old_ext = self.get_file_ext() else: if fileExt: - old_ext = fileExt + old_ext = fileExt else: - old_ext = self.get_file_ext() + old_ext = self.get_file_ext() hint = inst_name + run_num_str + old_ext if not filePath: @@ -443,32 +443,32 @@ def find_file(self,inst_name=None,run_num=None,filePath=None,fileExt=None,**kwar self._run_file_path = os.path.dirname(fname) return file except RuntimeError: - message = 'Cannot find file matching hint {0} on current search paths ' \ + message = 'Cannot find file matching hint {0} on current search paths ' \ 'for instrument {1}'.format(file_hint,inst_name) - if not ('be_quet' in kwargs): + if not ('be_quet' in kwargs): RunDescriptor._logger(message,'warning') - return 'ERROR:find_file: ' + message + return 'ERROR:find_file: ' + message #-------------------------------------------------------------------------------------------------------------------- def load_file(self,inst_name,ws_name,run_number=None,load_mon_with_workspace=False,filePath=None,fileExt=None,**kwargs): - """ load run for the instrument name provided. If run_numner is None, look for the current run""" - + """ load run for the instrument name provided. If run_numner is None, look for the current run""" + data_file = self.find_file(None,filePath,fileExt,**kwargs) if data_file.find('ERROR') > -1: - self._ws_name = None - raise IOError(data_file) - + self._ws_name = None + raise IOError(data_file) + if load_mon_with_workspace: - mon_load_option = 'Include' + mon_load_option = 'Include' else: - mon_load_option = 'Separate' + mon_load_option = 'Separate' # try: # Hack: LoadEventNexus does not understand Separate at the moment and throws. # And event loader always loads monitors separately - Load(Filename=data_file, OutputWorkspace=ws_name,LoadMonitors = mon_load_option) + Load(Filename=data_file, OutputWorkspace=ws_name,LoadMonitors = mon_load_option) except ValueError: #mon_load_option =str(int(load_mon_with_workspace)) - Load(Filename=data_file, OutputWorkspace=ws_name,LoadMonitors = '1',MonitorsAsEvents='0') + Load(Filename=data_file, OutputWorkspace=ws_name,LoadMonitors = '1',MonitorsAsEvents='0') RunDescriptor._logger("Loaded {0}".format(data_file),'information') @@ -506,17 +506,17 @@ def load_run(self,inst_name, calibration=None, force=False, mon_load_option=Fals return loaded_ws #-------------------------------------------------------------------------------------------------------------------- def apply_calibration(self,loaded_ws,calibration=None,use_ws_calibration=True): - """ If calibration is present, apply it to the workspace - - use_ws_calibration -- if true, retrieve workspace property, which defines + """ If calibration is present, apply it to the workspace + + use_ws_calibration -- if true, retrieve workspace property, which defines calibration option (e.g. det_cal_file used a while ago) and try to use it """ if not (calibration or use_ws_calibration): - return + return if not isinstance(loaded_ws, api.Workspace): - raise RuntimeError(' Calibration can be applied to a workspace only and got object of type {0}'.format(type(loaded_ws))) - + raise RuntimeError(' Calibration can be applied to a workspace only and got object of type {0}'.format(type(loaded_ws))) + if loaded_ws.run().hasProperty("calibrated"): return # already calibrated @@ -532,7 +532,7 @@ def apply_calibration(self,loaded_ws,calibration=None,use_ws_calibration=True): test_name = ws_calibration ws_calibration = FileFinder.getFullPath(ws_calibration) if len(ws_calibration) == 0: - raise RuntimeError('Can not find defined in run {0} calibration file {1}\n'\ + raise RuntimeError('Can not find defined in run {0} calibration file {1}\n'\ 'Define det_cal_file reduction parameter properly'.format(loaded_ws.name(),test_name)) RunDescriptor._logger('*** load_data: Calibrating data using workspace defined calibration file: {0}'.format(ws_calibration),'notice') except KeyError: # no det_cal_file defined in workspace @@ -553,42 +553,42 @@ def apply_calibration(self,loaded_ws,calibration=None,use_ws_calibration=True): #-------------------------------------------------------------------------------------------------------------------- @staticmethod def copy_spectrum2monitors(data_ws,mon_ws,spectraID): - """ + """ this routine copies a spectrum form workspace to monitor workspace and rebins it according to monitor workspace binning @param data_ws -- the event workspace which detector is considered as monitor or Mantid pointer to this workspace - @param mon_ws -- the histogram workspace with monitors where one needs to place the detector's spectra + @param mon_ws -- the histogram workspace with monitors where one needs to place the detector's spectra @param spectraID-- the ID of the spectra to copy. """ - + # ---------------------------- - try: - ws_index = mon_ws.getIndexFromSpectrumNumber(spectraID) + try: + ws_index = mon_ws.getIndexFromSpectrumNumber(spectraID) # Spectra is already in the monitor workspace - return mon_ws - except: - ws_index = data_ws.getIndexFromSpectrumNumber(spectraID) + return mon_ws + except: + ws_index = data_ws.getIndexFromSpectrumNumber(spectraID) # - x_param = mon_ws.readX(0) - bins = [x_param[0],x_param[1] - x_param[0],x_param[-1]] - ExtractSingleSpectrum(InputWorkspace=data_ws,OutputWorkspace='tmp_mon',WorkspaceIndex=ws_index) - Rebin(InputWorkspace='tmp_mon',OutputWorkspace='tmp_mon',Params=bins,PreserveEvents='0') + x_param = mon_ws.readX(0) + bins = [x_param[0],x_param[1] - x_param[0],x_param[-1]] + ExtractSingleSpectrum(InputWorkspace=data_ws,OutputWorkspace='tmp_mon',WorkspaceIndex=ws_index) + Rebin(InputWorkspace='tmp_mon',OutputWorkspace='tmp_mon',Params=bins,PreserveEvents='0') # should be vice versa but Conjoin invalidate ws pointers and hopefully # nothing could happen with workspace during conjoining #AddSampleLog(Workspace=monWS,LogName=done_log_name,LogText=str(ws_index),LogType='Number') - mon_ws_name = mon_ws.getName() - ConjoinWorkspaces(InputWorkspace1=mon_ws,InputWorkspace2='tmp_mon') - mon_ws = mtd[mon_ws_name] + mon_ws_name = mon_ws.getName() + ConjoinWorkspaces(InputWorkspace1=mon_ws,InputWorkspace2='tmp_mon') + mon_ws = mtd[mon_ws_name] - if 'tmp_mon' in mtd: - DeleteWorkspace(WorkspaceName='tmp_mon') - return mon_ws + if 'tmp_mon' in mtd: + DeleteWorkspace(WorkspaceName='tmp_mon') + return mon_ws #-------------------------------------------------------------------------------------------------------------------- def clear_monitors(self): - """ method removes monitor workspace form analysis data service if it is there - + """ method removes monitor workspace form analysis data service if it is there + (assuming it is not needed any more) """ monWS_name = self._ws_name + '_monitors' @@ -607,7 +607,7 @@ def _build_ws_name(self): else: ws_name = '{0}{1}{2}{3}'.format(self._prop_name,self._ws_cname,sum_ext,self._ws_suffix) - return ws_name + return ws_name #-------------------------------------------------------------------------------------------------------------------- @staticmethod def rremove(thestr, trailing): @@ -616,7 +616,7 @@ def rremove(thestr, trailing): return thestr[:-thelen] return thestr def _split_ws_name(self,ws_name): - """ Method to split existing workspace name + """ Method to split existing workspace name into parts, in such a way that _build_name would restore the same name """ # Remove suffix @@ -628,10 +628,10 @@ def _split_ws_name(self,ws_name): name = name.replace(self._prop_name,'',1) try: - part_ind = re.search('#(.+?)#', name).group(0) - name =name.replace(part_ind,'',1) + part_ind = re.search('#(.+?)#', name).group(0) + name =name.replace(part_ind,'',1) except AttributeError: - part_ind='' + part_ind='' if self._run_number: instr_name = self._instr_name() @@ -642,24 +642,24 @@ def _split_ws_name(self,ws_name): self._ws_cname = part_ind+name # def _instr_name(self): - if RunDescriptor._holder: + if RunDescriptor._holder: instr_name = RunDescriptor._holder.short_inst_name - else: + else: instr_name = '_test_instrument' - return instr_name + return instr_name def _clear_old_ws(self,old_ws_name,new_name,clear_fext=False): """ helper method used in __set__. When new data (run or wod) """ if old_ws_name: - if new_name != old_ws_name: + if new_name != old_ws_name: if old_ws_name in mtd: - DeleteWorkspace(old_ws_name) + DeleteWorkspace(old_ws_name) old_mon_ws = old_ws_name + '_monitors' if old_mon_ws in mtd: DeleteWorkspace(old_mon_ws) if clear_fext: - self._run_ext = None - self._run_file_path = '' + self._run_ext = None + self._run_file_path = '' #------------------------------------------------------------------------------------------------------------------------------- @@ -668,7 +668,7 @@ def _clear_old_ws(self,old_ws_name,new_name,clear_fext=False): class RunDescriptorDependent(RunDescriptor): """ Simple RunDescriptor class dependent on another RunDescriptor, providing the host descriptor if current descriptor value is not defined - or usual descriptor functionality if somebody sets current descriptor up + or usual descriptor functionality if somebody sets current descriptor up """ def __init__(self,host_run,ws_preffix,DocString=None): @@ -677,14 +677,14 @@ def __init__(self,host_run,ws_preffix,DocString=None): self._this_run_defined = False def __get__(self,instance,owner=None): - """ return dependent run number which is host run number if this one has not been set or this run number if it was""" - if self._this_run_defined: - if instance is None: - return self - else: + """ return dependent run number which is host run number if this one has not been set or this run number if it was""" + if self._this_run_defined: + if instance is None: + return self + else: return super(RunDescriptorDependent,self).__get__(instance,owner) - else: - return self._host.__get__(instance,owner) + else: + return self._host.__get__(instance,owner) def __set__(self,instance,value): if value is None: @@ -694,7 +694,7 @@ def __set__(self,instance,value): super(RunDescriptorDependent,self).__set__(instance,value) #def __del__(self): - # # destructor removes bounded workspace + # # destructor removes bounded workspace # # Probably better not to at current approach # if self._ws_name in mtd: # DeleteWorkspace(self._ws_name) diff --git a/Code/Mantid/scripts/Inelastic/Direct/__init__.py b/Code/Mantid/scripts/Inelastic/Direct/__init__.py index e798813ca1ff..26487e011f10 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/__init__.py +++ b/Code/Mantid/scripts/Inelastic/Direct/__init__.py @@ -4,8 +4,8 @@ DirectEnergyConversion -- main reduction class PropertyManager -- helper class providing access and functionality for IDF properties ReductionWrapper -- parent class for reduction, After overloading for particular insrument provides common interface for Mantid and web services -RunDescriptor -- Class descripbing a run and instantiated as property of Property manager to specify a +RunDescriptor -- Class descripbing a run and instantiated as property of Property manager to specify a particular kind of run (e.g. sample run, monovan run etc...) """ -__all__=['dgreduce','DirectEnergyConversion','PropertyManager','ReductionWrapper','RunDescriptor'] \ No newline at end of file +__all__=['dgreduce','DirectEnergyConversion','PropertyManager','ReductionWrapper','RunDescriptor'] diff --git a/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py b/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py index 80b41f20c374..67ebb7df6fb5 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py +++ b/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py @@ -36,7 +36,7 @@ def setup(instname=None,reload=False): old_name=Reducer.prop_man.instr_name if old_name.upper()[0:3] == instname.upper()[0:3] : if not reload : - return # has been already defined + return # has been already defined Reducer = DRC.setup_reducer(instname,reload) @@ -137,10 +137,10 @@ def arb_units(wb_run,sample_run,ei_guess,rebin,map_file='default',monovan_run=No if sample_run: Reducer.sample_run = sample_run try: - n,r=funcreturns.lhs_info('both') - wksp_out=r[0] + n,r=funcreturns.lhs_info('both') + wksp_out=r[0] except: - wksp_out = Reducer.prop_man.get_sample_ws_name() + wksp_out = Reducer.prop_man.get_sample_ws_name() # res = Reducer.convert_to_energy(wb_run,sample_run,ei_guess,rebin,map_file,monovan_run,second_wb,**kwargs) # diff --git a/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py b/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py index 10898f95070d..a48b55901abc 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py +++ b/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py @@ -135,18 +135,18 @@ def diagnose(white_int,**kwargs): end_index_name=" to: end" default = True if hasattr(parser, 'print_diag_results') and parser.print_diag_results: - default=True + default=True if 'start_index' in kwargs: - default = False - start_index_name = "from: "+str(kwargs['start_index']) + default = False + start_index_name = "from: "+str(kwargs['start_index']) if 'end_index' in kwargs : - default = False - end_index_name = " to: "+str(kwargs['end_index']) + default = False + end_index_name = " to: "+str(kwargs['end_index']) testName=start_index_name+end_index_name if not default : - testName = " For bank: "+start_index_name+end_index_name + testName = " For bank: "+start_index_name+end_index_name if hasattr(parser, 'print_diag_results') and parser.print_diag_results: print_test_summary(test_results,testName) @@ -271,11 +271,11 @@ def normalise_background(background_int, white_int, second_white_int=None): """ if second_white_int is None: # quetly divide background integral by white beam integral not reporting about possible 0 in wb integral (they will be removed by diag anyway) - background_int = Divide(LHSWorkspace=background_int,RHSWorkspace=white_int,WarnOnZeroDivide='0'); + background_int = Divide(LHSWorkspace=background_int,RHSWorkspace=white_int,WarnOnZeroDivide='0') else: hmean = 2.0*white_int*second_white_int/(white_int+second_white_int) #background_int /= hmean - background_int = Divide(LHSWorkspace=background_int,RHSWorkspace=hmean,WarnOnZeroDivide='0'); + background_int = Divide(LHSWorkspace=background_int,RHSWorkspace=hmean,WarnOnZeroDivide='0') DeleteWorkspace(hmean) #------------------------------------------------------------------------------ @@ -324,11 +324,11 @@ def do_bleed_test(sample_run, max_framerate, ignored_pixels): # Load the sample run if __Reducer__: # Try to use generic loader which would work with files or workspaces alike sample_run = __Reducer__.get_run_descriptor(sample_run) - data_ws = sample_run.get_workspace() # this will load data if necessary + data_ws = sample_run.get_workspace() # this will load data if necessary ws_name = sample_run.get_ws_name()+'_bleed' - else: + else: # may be sample run is already a run descriptor despite __Reducer__ have not been exposed - data_ws = sample_run.get_workspace() # this will load data if necessary + data_ws = sample_run.get_workspace() # this will load data if necessary ws_name = sample_run.get_ws_name()+'_bleed' if max_framerate is None: diff --git a/Code/Mantid/scripts/Inelastic/IndirectBayes.py b/Code/Mantid/scripts/Inelastic/IndirectBayes.py index 90123e79487c..a4fb2aacdacf 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectBayes.py +++ b/Code/Mantid/scripts/Inelastic/IndirectBayes.py @@ -141,8 +141,8 @@ def ReadWidthFile(readWidth,widthFile,numSampleGroups): raise ValueError('Width groups (' +str(numLines) + ') not = Sample (' +str(numSampleGroups) +')') else: # no file: just use constant values - widthY = np.zeros(numSampleGroups) - widthE = np.zeros(numSampleGroups) + widthY = np.zeros(numSampleGroups) + widthE = np.zeros(numSampleGroups) # pad for Fortran call widthY = PadArray(widthY,51) @@ -513,12 +513,12 @@ def C2Fw(prog,sname): axis_names.append('f'+str(nl)+'.f0.'+'Height') x.append(x_data) for j in range(1,nl+1): - axis_names.append('f'+str(nl)+'.f'+str(j)+'.Amplitude') - x.append(x_data) - axis_names.append('f'+str(nl)+'.f'+str(j)+'.FWHM') - x.append(x_data) - axis_names.append('f'+str(nl)+'.f'+str(j)+'.EISF') - x.append(x_data) + axis_names.append('f'+str(nl)+'.f'+str(j)+'.Amplitude') + x.append(x_data) + axis_names.append('f'+str(nl)+'.f'+str(j)+'.FWHM') + x.append(x_data) + axis_names.append('f'+str(nl)+'.f'+str(j)+'.EISF') + x.append(x_data) x = np.asarray(x).flatten() y = np.asarray(y).flatten() diff --git a/Code/Mantid/scripts/Inelastic/IndirectCommon.py b/Code/Mantid/scripts/Inelastic/IndirectCommon.py index 043c2717866c..fc7993f9e4b3 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectCommon.py +++ b/Code/Mantid/scripts/Inelastic/IndirectCommon.py @@ -388,32 +388,32 @@ def plotParameters(ws, *param_names): plotSpectra(ws, name, indicies) def convertToElasticQ(input_ws, output_ws=None): - """ + """ Helper function to convert the spectrum axis of a sample to ElasticQ. @param input_ws - the name of the workspace to convert from @param output_ws - the name to call the converted workspace """ - if output_ws is None: - output_ws = input_ws + if output_ws is None: + output_ws = input_ws - axis = mtd[input_ws].getAxis(1) - if axis.isSpectra(): - e_fixed = getEfixed(input_ws) - ConvertSpectrumAxis(input_ws,Target='ElasticQ',EMode='Indirect',EFixed=e_fixed,OutputWorkspace=output_ws) + axis = mtd[input_ws].getAxis(1) + if axis.isSpectra(): + e_fixed = getEfixed(input_ws) + ConvertSpectrumAxis(input_ws,Target='ElasticQ',EMode='Indirect',EFixed=e_fixed,OutputWorkspace=output_ws) - elif axis.isNumeric(): + elif axis.isNumeric(): #check that units are Momentum Transfer - if axis.getUnit().unitID() != 'MomentumTransfer': - raise RuntimeError('Input must have axis values of Q') + if axis.getUnit().unitID() != 'MomentumTransfer': + raise RuntimeError('Input must have axis values of Q') - CloneWorkspace(input_ws, OutputWorkspace=output_ws) - else: - raise RuntimeError('Input workspace must have either spectra or numeric axis.') + CloneWorkspace(input_ws, OutputWorkspace=output_ws) + else: + raise RuntimeError('Input workspace must have either spectra or numeric axis.') def transposeFitParametersTable(params_table, output_table=None): - """ + """ Transpose the parameter table created from a multi domain Fit. This function will make the output consistent with PlotPeakByLogValue. @@ -421,44 +421,44 @@ def transposeFitParametersTable(params_table, output_table=None): @param output_table - name to call the transposed table. If omitted, the output_table will be the same as the params_table """ - params_table = mtd[params_table] + params_table = mtd[params_table] - table_ws = '__tmp_table_ws' - table_ws = CreateEmptyTableWorkspace(OutputWorkspace=table_ws) + table_ws = '__tmp_table_ws' + table_ws = CreateEmptyTableWorkspace(OutputWorkspace=table_ws) - param_names = params_table.column(0)[:-1] #-1 to remove cost function - param_values = params_table.column(1)[:-1] - param_errors = params_table.column(2)[:-1] + param_names = params_table.column(0)[:-1] #-1 to remove cost function + param_values = params_table.column(1)[:-1] + param_errors = params_table.column(2)[:-1] #find the number of parameters per function - func_index = param_names[0].split('.')[0] - num_params = 0 - for i, name in enumerate(param_names): - if name.split('.')[0] != func_index: - num_params = i - break + func_index = param_names[0].split('.')[0] + num_params = 0 + for i, name in enumerate(param_names): + if name.split('.')[0] != func_index: + num_params = i + break #create columns with parameter names for headers - column_names = ['.'.join(name.split('.')[1:]) for name in param_names[:num_params]] - column_error_names = [name + '_Err' for name in column_names] - column_names = zip(column_names, column_error_names) - table_ws.addColumn('double', 'axis-1') - for name, error_name in column_names: - table_ws.addColumn('double', name) - table_ws.addColumn('double', error_name) + column_names = ['.'.join(name.split('.')[1:]) for name in param_names[:num_params]] + column_error_names = [name + '_Err' for name in column_names] + column_names = zip(column_names, column_error_names) + table_ws.addColumn('double', 'axis-1') + for name, error_name in column_names: + table_ws.addColumn('double', name) + table_ws.addColumn('double', error_name) #output parameter values to table row - for i in xrange(0, params_table.rowCount()-1, num_params): - row_values = param_values[i:i+num_params] - row_errors = param_errors[i:i+num_params] - row = [value for pair in zip(row_values, row_errors) for value in pair] - row = [i/num_params] + row - table_ws.addRow(row) + for i in xrange(0, params_table.rowCount()-1, num_params): + row_values = param_values[i:i+num_params] + row_errors = param_errors[i:i+num_params] + row = [value for pair in zip(row_values, row_errors) for value in pair] + row = [i/num_params] + row + table_ws.addRow(row) - if output_table is None: - output_table = params_table.name() + if output_table is None: + output_table = params_table.name() - RenameWorkspace(table_ws.name(), OutputWorkspace=output_table) + RenameWorkspace(table_ws.name(), OutputWorkspace=output_table) def search_for_fit_params(suffix, table_ws): @@ -472,7 +472,7 @@ def search_for_fit_params(suffix, table_ws): def convertParametersToWorkspace(params_table, x_column, param_names, output_name): - """ + """ Convert a parameter table output by PlotPeakByLogValue to a MatrixWorkspace. This will make a spectrum for each parameter name using the x_column vairable as the @@ -485,57 +485,57 @@ def convertParametersToWorkspace(params_table, x_column, param_names, output_nam """ #search for any parameters in the table with the given parameter names, #ignoring their function index and output them to a workspace - workspace_names = [] - for param_name in param_names: - column_names = search_for_fit_params(param_name, params_table) - column_error_names = search_for_fit_params(param_name+'_Err', params_table) - param_workspaces = [] - for name, error_name in zip(column_names, column_error_names): - ConvertTableToMatrixWorkspace(params_table, x_column, name, error_name, OutputWorkspace=name) - param_workspaces.append(name) - workspace_names.append(param_workspaces) + workspace_names = [] + for param_name in param_names: + column_names = search_for_fit_params(param_name, params_table) + column_error_names = search_for_fit_params(param_name+'_Err', params_table) + param_workspaces = [] + for name, error_name in zip(column_names, column_error_names): + ConvertTableToMatrixWorkspace(params_table, x_column, name, error_name, OutputWorkspace=name) + param_workspaces.append(name) + workspace_names.append(param_workspaces) #transpose list of workspaces, ignoring unequal length of lists #this handles the case where a parameter occurs only once in the whole workspace - workspace_names = map(list, itertools.izip_longest(*workspace_names)) - workspace_names = [filter(None, sublist) for sublist in workspace_names] + workspace_names = map(list, itertools.izip_longest(*workspace_names)) + workspace_names = [filter(None, sublist) for sublist in workspace_names] #join all the parameters for each peak into a single workspace per peak - temp_workspaces = [] - for peak_params in workspace_names: - temp_peak_ws = peak_params[0] - for param_ws in peak_params[1:]: - ConjoinWorkspaces(temp_peak_ws, param_ws, False) - temp_workspaces.append(temp_peak_ws) + temp_workspaces = [] + for peak_params in workspace_names: + temp_peak_ws = peak_params[0] + for param_ws in peak_params[1:]: + ConjoinWorkspaces(temp_peak_ws, param_ws, False) + temp_workspaces.append(temp_peak_ws) #join all peaks into a single workspace - temp_workspace = temp_workspaces[0] - for temp_ws in temp_workspaces[1:]: - ConjoinWorkspaces(temp_workspace, temp_peak_ws, False) + temp_workspace = temp_workspaces[0] + for temp_ws in temp_workspaces[1:]: + ConjoinWorkspaces(temp_workspace, temp_peak_ws, False) - RenameWorkspace(temp_workspace, OutputWorkspace=output_name) + RenameWorkspace(temp_workspace, OutputWorkspace=output_name) #replace axis on workspaces with text axis - axis = TextAxis.create(mtd[output_name].getNumberHistograms()) - workspace_names = [name for sublist in workspace_names for name in sublist] - for i, name in enumerate(workspace_names): - axis.setLabel(i, name) - mtd[output_name].replaceAxis(1, axis) + axis = TextAxis.create(mtd[output_name].getNumberHistograms()) + workspace_names = [name for sublist in workspace_names for name in sublist] + for i, name in enumerate(workspace_names): + axis.setLabel(i, name) + mtd[output_name].replaceAxis(1, axis) def addSampleLogs(ws, sample_logs): - """ + """ Add a dictionary of logs to a workspace. The type of the log is inferred by the type of the value passed to the log. @param ws - workspace to add logs too. @param sample_logs - dictionary of logs to append to the workspace. """ - for key, value in sample_logs.iteritems(): - if isinstance(value, bool): - log_type = 'String' - elif isinstance(value, (int, long, float)): - log_type = 'Number' - else: - log_type = 'String' + for key, value in sample_logs.iteritems(): + if isinstance(value, bool): + log_type = 'String' + elif isinstance(value, (int, long, float)): + log_type = 'Number' + else: + log_type = 'String' - AddSampleLog(Workspace=ws, LogName=key, LogType=log_type, LogText=str(value)) + AddSampleLog(Workspace=ws, LogName=key, LogType=log_type, LogText=str(value)) diff --git a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py index ca7a18289489..35fab8fc8043 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py +++ b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py @@ -160,177 +160,177 @@ def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin def furyfitSeq(inputWS, func, ftype, startx, endx, spec_min=0, spec_max=None, intensities_constrained=False, Save=False, Plot='None'): - StartTime('FuryFit') + StartTime('FuryFit') - fit_type = ftype[:-2] - logger.information('Option: ' + fit_type) - logger.information(func) + fit_type = ftype[:-2] + logger.information('Option: ' + fit_type) + logger.information(func) - tmp_fit_workspace = "__furyfit_fit_ws" - CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx) + tmp_fit_workspace = "__furyfit_fit_ws" + CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx) - num_hist = mtd[inputWS].getNumberHistograms() - if spec_max is None: - spec_max = num_hist - 1 + num_hist = mtd[inputWS].getNumberHistograms() + if spec_max is None: + spec_max = num_hist - 1 # name stem for generated workspace - output_workspace = getWSprefix(inputWS) + 'fury_' + ftype + str(spec_min) + "_to_" + str(spec_max) + output_workspace = getWSprefix(inputWS) + 'fury_' + ftype + str(spec_min) + "_to_" + str(spec_max) - ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) - convertToElasticQ(tmp_fit_workspace) + ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) + convertToElasticQ(tmp_fit_workspace) #build input string for PlotPeakByLogValue - input_str = [tmp_fit_workspace + ',i%d' % i for i in range(spec_min, spec_max + 1)] - input_str = ';'.join(input_str) + input_str = [tmp_fit_workspace + ',i%d' % i for i in range(spec_min, spec_max + 1)] + input_str = ';'.join(input_str) - PlotPeakByLogValue(Input=input_str, OutputWorkspace=output_workspace, Function=func, + PlotPeakByLogValue(Input=input_str, OutputWorkspace=output_workspace, Function=func, StartX=startx, EndX=endx, FitType='Sequential', CreateOutput=True) #remove unsused workspaces - DeleteWorkspace(output_workspace + '_NormalisedCovarianceMatrices') - DeleteWorkspace(output_workspace + '_Parameters') + DeleteWorkspace(output_workspace + '_NormalisedCovarianceMatrices') + DeleteWorkspace(output_workspace + '_Parameters') - fit_group = output_workspace + '_Workspaces' - params_table = output_workspace + '_Parameters' - RenameWorkspace(output_workspace, OutputWorkspace=params_table) + fit_group = output_workspace + '_Workspaces' + params_table = output_workspace + '_Parameters' + RenameWorkspace(output_workspace, OutputWorkspace=params_table) #create *_Result workspace - result_workspace = output_workspace + "_Result" - parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] - convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) + result_workspace = output_workspace + "_Result" + parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] + convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) #set x units to be momentum transfer - axis = mtd[result_workspace].getAxis(0) - axis.setUnit("MomentumTransfer") + axis = mtd[result_workspace].getAxis(0) + axis.setUnit("MomentumTransfer") #process generated workspaces - wsnames = mtd[fit_group].getNames() - params = [startx, endx, fit_type] - for i, ws in enumerate(wsnames): - output_ws = output_workspace + '_%d_Workspace' % i - RenameWorkspace(ws, OutputWorkspace=output_ws) + wsnames = mtd[fit_group].getNames() + params = [startx, endx, fit_type] + for i, ws in enumerate(wsnames): + output_ws = output_workspace + '_%d_Workspace' % i + RenameWorkspace(ws, OutputWorkspace=output_ws) - sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': fit_type, + sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': fit_type, 'intensities_constrained': intensities_constrained, 'beta_constrained': False} - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) - addSampleLogs(fit_group, sample_logs) - addSampleLogs(result_workspace, sample_logs) + addSampleLogs(fit_group, sample_logs) + addSampleLogs(result_workspace, sample_logs) - if Save: - save_workspaces = [result_workspace, fit_group] - furyFitSaveWorkspaces(save_workspaces) + if Save: + save_workspaces = [result_workspace, fit_group] + furyFitSaveWorkspaces(save_workspaces) - if Plot != 'None' : - furyfitPlotSeq(result_workspace, Plot) + if Plot != 'None' : + furyfitPlotSeq(result_workspace, Plot) - EndTime('FuryFit') - return result_workspace + EndTime('FuryFit') + return result_workspace def furyfitMult(inputWS, function, ftype, startx, endx, spec_min=0, spec_max=None, intensities_constrained=False, Save=False, Plot='None'): - StartTime('FuryFit Multi') + StartTime('FuryFit Multi') - nHist = mtd[inputWS].getNumberHistograms() - output_workspace = getWSprefix(inputWS) + 'fury_1Smult_s0_to_' + str(nHist-1) + nHist = mtd[inputWS].getNumberHistograms() + output_workspace = getWSprefix(inputWS) + 'fury_1Smult_s0_to_' + str(nHist-1) - option = ftype[:-2] - logger.information('Option: '+option) - logger.information('Function: '+function) + option = ftype[:-2] + logger.information('Option: '+option) + logger.information('Function: '+function) #prepare input workspace for fitting - tmp_fit_workspace = "__furyfit_fit_ws" - if spec_max is None: - CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx, + tmp_fit_workspace = "__furyfit_fit_ws" + if spec_max is None: + CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx, StartWorkspaceIndex=spec_min) - else: - CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx, + else: + CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx, StartWorkspaceIndex=spec_min, EndWorkspaceIndex=spec_max) - ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) - convertToElasticQ(tmp_fit_workspace) + ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) + convertToElasticQ(tmp_fit_workspace) #fit multi-domian functino to workspace - multi_domain_func, kwargs = createFuryMultiDomainFunction(function, tmp_fit_workspace) - Fit(Function=multi_domain_func, InputWorkspace=tmp_fit_workspace, WorkspaceIndex=0, + multi_domain_func, kwargs = createFuryMultiDomainFunction(function, tmp_fit_workspace) + Fit(Function=multi_domain_func, InputWorkspace=tmp_fit_workspace, WorkspaceIndex=0, Output=output_workspace, CreateOutput=True, **kwargs) - params_table = output_workspace + '_Parameters' - transposeFitParametersTable(params_table) + params_table = output_workspace + '_Parameters' + transposeFitParametersTable(params_table) #set first column of parameter table to be axis values - ax = mtd[tmp_fit_workspace].getAxis(1) - axis_values = ax.extractValues() - for i, value in enumerate(axis_values): - mtd[params_table].setCell('axis-1', i, value) + ax = mtd[tmp_fit_workspace].getAxis(1) + axis_values = ax.extractValues() + for i, value in enumerate(axis_values): + mtd[params_table].setCell('axis-1', i, value) #convert parameters to matrix workspace - result_workspace = output_workspace + "_Result" - parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] - convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) + result_workspace = output_workspace + "_Result" + parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] + convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) #set x units to be momentum transfer - axis = mtd[result_workspace].getAxis(0) - axis.setUnit("MomentumTransfer") + axis = mtd[result_workspace].getAxis(0) + axis.setUnit("MomentumTransfer") - result_workspace = output_workspace + '_Result' - fit_group = output_workspace + '_Workspaces' + result_workspace = output_workspace + '_Result' + fit_group = output_workspace + '_Workspaces' - sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': ftype, + sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': ftype, 'intensities_constrained': intensities_constrained, 'beta_constrained': True} - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) - addSampleLogs(result_workspace, sample_logs) - addSampleLogs(fit_group, sample_logs) + addSampleLogs(result_workspace, sample_logs) + addSampleLogs(fit_group, sample_logs) - DeleteWorkspace(tmp_fit_workspace) + DeleteWorkspace(tmp_fit_workspace) - if Save: - save_workspaces = [result_workspace] - furyFitSaveWorkspaces(save_workspaces) + if Save: + save_workspaces = [result_workspace] + furyFitSaveWorkspaces(save_workspaces) - if Plot != 'None': - furyfitPlotSeq(result_workspace, Plot) + if Plot != 'None': + furyfitPlotSeq(result_workspace, Plot) - EndTime('FuryFit Multi') - return result_workspace + EndTime('FuryFit Multi') + return result_workspace def createFuryMultiDomainFunction(function, input_ws): - multi= 'composite=MultiDomainFunction,NumDeriv=1;' - comp = '(composite=CompositeFunction,$domains=i;' + function + ');' + multi= 'composite=MultiDomainFunction,NumDeriv=1;' + comp = '(composite=CompositeFunction,$domains=i;' + function + ');' - ties = [] - kwargs = {} - num_spectra = mtd[input_ws].getNumberHistograms() - for i in range(0, num_spectra): - multi += comp - kwargs['WorkspaceIndex_' + str(i)] = i + ties = [] + kwargs = {} + num_spectra = mtd[input_ws].getNumberHistograms() + for i in range(0, num_spectra): + multi += comp + kwargs['WorkspaceIndex_' + str(i)] = i - if i > 0: - kwargs['InputWorkspace_' + str(i)] = input_ws + if i > 0: + kwargs['InputWorkspace_' + str(i)] = input_ws #tie beta for every spectrum - tie = 'f%d.f1.Beta=f0.f1.Beta' % i - ties.append(tie) + tie = 'f%d.f1.Beta=f0.f1.Beta' % i + ties.append(tie) - ties = ','.join(ties) - multi += 'ties=(' + ties + ')' + ties = ','.join(ties) + multi += 'ties=(' + ties + ')' - return multi, kwargs + return multi, kwargs def furyFitSaveWorkspaces(save_workspaces): - workdir = getDefaultWorkingDirectory() - for ws in save_workspaces: + workdir = getDefaultWorkingDirectory() + for ws in save_workspaces: #save workspace to default directory - fpath = os.path.join(workdir, ws+'.nxs') - SaveNexusProcessed(InputWorkspace=ws, Filename=fpath) - logger.information(ws + ' output to file : '+fpath) + fpath = os.path.join(workdir, ws+'.nxs') + SaveNexusProcessed(InputWorkspace=ws, Filename=fpath) + logger.information(ws + ' output to file : '+fpath) def furyfitPlotSeq(ws, plot): diff --git a/Code/Mantid/scripts/Inelastic/IndirectMuscat.py b/Code/Mantid/scripts/Inelastic/IndirectMuscat.py index e20601e39e48..379505207530 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectMuscat.py +++ b/Code/Mantid/scripts/Inelastic/IndirectMuscat.py @@ -18,19 +18,19 @@ def CalcW0(nq,dq,disp,coeff): w0 = [] e0 = [] for n in range(0,nq): - q0 = (n+1)*dq - Q.append(q0) - q02 = q0*q0 - Q2.append(q02) - if (disp == 'Poly'): - w = coeff[0]+coeff[1]*q0+coeff[2]*q02+coeff[3]*q0*q02+coeff[4]*q02*q02 - if (disp == 'CE'): - qk = coeff[1]*q0 - w = coeff[0]*(1.0-math.sin(qk)/qk) - if (disp == 'SS'): - w0 = coeff[0]*(1.0-math.exp(coeff[1]*q02)) - w0.append(w*0.001) #convert from mmeV to meV - e0.append(0.0) + q0 = (n+1)*dq + Q.append(q0) + q02 = q0*q0 + Q2.append(q02) + if (disp == 'Poly'): + w = coeff[0]+coeff[1]*q0+coeff[2]*q02+coeff[3]*q0*q02+coeff[4]*q02*q02 + if (disp == 'CE'): + qk = coeff[1]*q0 + w = coeff[0]*(1.0-math.sin(qk)/qk) + if (disp == 'SS'): + w0 = coeff[0]*(1.0-math.exp(coeff[1]*q02)) + w0.append(w*0.001) #convert from mmeV to meV + e0.append(0.0) return Q,w0,e0 def CalcSqw(q0,nw2,nel,dw,w0): @@ -41,66 +41,66 @@ def CalcSqw(q0,nw2,nel,dw,w0): nq = len(q0) Qaxis = '' for i in range(0,nq): - ww0 = w0[i] - for j in range(0,nw2): + ww0 = w0[i] + for j in range(0,nw2): # S(I,J)=S(I,J)+PKHT*W0(I)/(W0(I)**2+W**2) !Lorentzian S(Q,w) - ww = (j-nel)*dw - xSqw.append(ww) #convert to microeV - ss = PKHT*ww0/(ww0**2+ww**2) - ySqw.append(ss) - eSqw.append(0.0) - if i == 0: - Qaxis += str(q0[i]) - else: - Qaxis += ','+str(q0[i]) + ww = (j-nel)*dw + xSqw.append(ww) #convert to microeV + ss = PKHT*ww0/(ww0**2+ww**2) + ySqw.append(ss) + eSqw.append(0.0) + if i == 0: + Qaxis += str(q0[i]) + else: + Qaxis += ','+str(q0[i]) CreateWorkspace(OutputWorkspace='S(Q,w)', DataX=xSqw, DataY=ySqw, DataE=eSqw, Nspec=nq, UnitX='DeltaE', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=Qaxis) def CheckCoeff(disp,coeff): if (disp == 'CE') or (disp == 'SS'): - if coeff[0] < 1e-8: - error = disp + ' coeff 1 is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) - if coeff[1] < 1e-8: - error = disp + ' coeff 2 is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + if coeff[0] < 1e-8: + error = disp + ' coeff 1 is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) + if coeff[1] < 1e-8: + error = disp + ' coeff 2 is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) if (disp == 'Poly'): - cc = coeff[0]+coeff[1]+coeff[2]+coeff[3]+coeff[4] - if cc < 1e-8: - error = 'Poly coeffs all zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + cc = coeff[0]+coeff[1]+coeff[2]+coeff[3]+coeff[4] + if cc < 1e-8: + error = 'Poly coeffs all zero' + logger.notice('ERROR *** '+error) + sys.exit(error) def CheckQw(grid): nq = grid[0] if nq == 0: - error = 'Grid : Number of Q values is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + error = 'Grid : Number of Q values is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) nw = grid[2] if nw == 0: - error = 'Grid : Number of w values is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + error = 'Grid : Number of w values is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) dq = grid[1] if dq < 1e-5: - error = 'Grid : Q increment is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + error = 'Grid : Q increment is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) dw = grid[3]*0.001 if dw < 1e-8: - error = 'Grid : w increment is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + error = 'Grid : w increment is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) return nq,dq,nw,dw def CreateSqw(disp,coeff,grid,Verbose): CheckCoeff(disp,coeff) if Verbose: - logger.notice('Dispersion is '+disp) - logger.notice('Coefficients : '+str(coeff)) + logger.notice('Dispersion is '+disp) + logger.notice('Coefficients : '+str(coeff)) nq,dq,nw,dw = CheckQw(grid) q0,w0,e0 = CalcW0(nq,dq,disp,coeff) CreateWorkspace(OutputWorkspace=disp, DataX=q0, DataY=w0, DataE=e0, @@ -115,77 +115,77 @@ def ReadSqw(sqw,Verbose): axis = mtd[sqw].getAxis(1) Q = [] for i in range(0,nq): - Q.append(float(axis.label(i))) + Q.append(float(axis.label(i))) Q_in = PadArray(Q,500) Sqw_in = [] for n in range(0,nq): - Xw = mtd[sqw].readX(n) # energy array - Ys = mtd[sqw].readY(n) # S(q,w) values - Ys = PadArray(Ys,1000) # pad to Fortran energy size 1000 - Sqw_in.append(Ys) + Xw = mtd[sqw].readX(n) # energy array + Ys = mtd[sqw].readY(n) # S(q,w) values + Ys = PadArray(Ys,1000) # pad to Fortran energy size 1000 + Sqw_in.append(Ys) dw = Xw[2]-Xw[1] if dw < 1e-8: - error = 'Sqw : w increment is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + error = 'Sqw : w increment is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) nel= nw+1 for n in range(0,nw): - if (Xw[n] < dw): - nel = n + if (Xw[n] < dw): + nel = n dq = Q[1]-Q[0] if dq < 1e-5: - error = 'Sqw : Q increment is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + error = 'Sqw : Q increment is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) if Verbose: - logger.notice('Q : '+str(nq)+' points from '+str(Q[0])+' to '+str(Q[nq-1])+' at '+str(dq)) - logger.notice('w : '+str(nw)+' points from '+str(Xw[0])+' to '+str(Xw[nw])+' at '+str(dw) + logger.notice('Q : '+str(nq)+' points from '+str(Q[0])+' to '+str(Q[nq-1])+' at '+str(dq)) + logger.notice('w : '+str(nw)+' points from '+str(Xw[0])+' to '+str(Xw[nw])+' at '+str(dw) +' ; Elastic energy at : '+str(nel)) X0 = [] X0 = PadArray(X0,1000) # zeroes for n in range(nq,500): # pad to Fortran Q size 500 - Sqw_in.append(X0) + Sqw_in.append(X0) return nq,dq,Q_in,nw,dw,nel,Xw,Sqw_in def CheckNeut(neut): # neut = [NRUN1, NRUN2, JRAND, MRAND, NMST] if neut[0] == 0: - error = 'NRUN1 is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'NRUN1 is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) if neut[1] == 0: - error = 'NRUN2 is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'NRUN2 is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) if neut[4] == 0: - error = 'Number scatterings is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'Number scatterings is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) def CheckBeam(beam): # beam = [THICK, WIDTH, HEIGHT, alfa] if beam[0] <1e-5: - error = 'Beam thickness is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'Beam thickness is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) if beam[1] <1e-5: - error = 'Beam width is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'Beam width is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) if beam[2] <1e-5: - error = 'Beam height is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'Beam height is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) def CheckSam(sam): if sam[1] <1e-8: - error = 'Sample density is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'Sample density is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) if (sam[2]+sam[3]) <1e-8: - error = 'Sample total scattering cross-section (scat+abs) is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'Sample total scattering cross-section (scat+abs) is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) def MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): # neut = [NRUN1, NRUN2, JRAND, MRAND, NMST] @@ -203,23 +203,23 @@ def MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): # ijeom = [jeom, Jann] Jann = 1 if geom == 'Flat': - ijeom = [2, Jann] + ijeom = [2, Jann] if geom == 'Cyl': - ijeom = [3, Jann] + ijeom = [3, Jann] # rgeom = [thick, width, height] rgeom = [beam[0], beam[1], beam[2]] nran = [neut[0], neut[1], neut[2], neut[3]] lpt = os.path.join(workdir, sname[:-3]+geom+'_ms.lpt') # path name for lpt file if Verbose: - logger.notice('Detectors/angles : '+str(mang)) - logger.notice('Sample geometry : '+geom) - logger.notice('Sample parameters') - logger.notice(' sigs = '+str(sam[3])+' ; siga = '+str(sam[1])+' ; rho = '+str(sam[0])) - if geom == 'Cyl': - logger.notice(' inner radius = '+str(beam[0])+' ; outer radius = '+str(beam[1])) - if geom == 'Flat': - logger.notice(' thickness = '+str(beam[0])) - logger.notice('Output lptfile : ' + lpt) + logger.notice('Detectors/angles : '+str(mang)) + logger.notice('Sample geometry : '+geom) + logger.notice('Sample parameters') + logger.notice(' sigs = '+str(sam[3])+' ; siga = '+str(sam[1])+' ; rho = '+str(sam[0])) + if geom == 'Cyl': + logger.notice(' inner radius = '+str(beam[0])+' ; outer radius = '+str(beam[1])) + if geom == 'Flat': + logger.notice(' thickness = '+str(beam[0])) + logger.notice('Output lptfile : ' + lpt) llpt = len(lpt) lpt.ljust(140,' ') lsqw = len(sqw) @@ -235,49 +235,49 @@ def MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): Qaxis = '' for m in range(0,mang): # rinstr = [efixed, theta, alfa] - rinstr = [efixed, angle[m], beam[3]] - logger.notice('Detector ' +str(m+1)+ ' at angle ' +str(angle[m])+ ' and Q = ' +str(QQ[m])) + rinstr = [efixed, angle[m], beam[3]] + logger.notice('Detector ' +str(m+1)+ ' at angle ' +str(angle[m])+ ' and Q = ' +str(QQ[m])) # SUBROUTINE MUSCAT_data(IDET,sfile,l_sf,rfile,l_rf,rinstr,nran, # 1 ijeom,rgeom,sam,ims,dqw,Q_in,S_in, # 2 totals,iw,energy,scat1,scatm,RR,S_out) - idet = m+1 - kill,totals,iw,energy,scat1,scatm,RR,Sqw=muscat.muscat_data(idet,lpt,llpt,sqw,lsqw,rinstr,nran, + idet = m+1 + kill,totals,iw,energy,scat1,scatm,RR,Sqw=muscat.muscat_data(idet,lpt,llpt,sqw,lsqw,rinstr,nran, ijeom,rgeom,sam,ims,dqw,Q_in,Sqw_in) - if (kill != 0): - error = 'Muscat error code : '+str(kill) - logger.notice(error) - sys.exit(error) - else: - xEn = energy[:iw] - xEn = np.append(xEn,2*energy[iw-1]-energy[iw-2]) - ySc1 = scat1[:iw] # single scattering energy distribution - yScM = scatm[:iw] # total scattering energy distribution - yRr = RR[:iw] # R-factor energy distribution - if m == 0: - tot1 = np.array(totals[1]) # total single scattering - tot2 = np.array(totals[2]) # total second scattering - tot3 = np.array(totals[3]) # total third scattering - total = np.array(totals[4]) # total all scattering - xMs = xEn - yMsc1 = ySc1 - yMscM = yScM - yMr = yRr - else: - tot1 = np.append(tot1,totals[1]) - tot2 = np.append(tot2,totals[2]) - tot3 = np.append(tot3,totals[3]) - total = np.append(total,totals[4]) - xMs = np.append(xMs,xEn) - yMsc1 = np.append(yMsc1,ySc1) - yMscM = np.append(yMscM,yScM) - yMr = np.append(yMr,yRr) - Qaxis += ',' - Qaxis += str(QQ[m]) + if (kill != 0): + error = 'Muscat error code : '+str(kill) + logger.notice(error) + sys.exit(error) + else: + xEn = energy[:iw] + xEn = np.append(xEn,2*energy[iw-1]-energy[iw-2]) + ySc1 = scat1[:iw] # single scattering energy distribution + yScM = scatm[:iw] # total scattering energy distribution + yRr = RR[:iw] # R-factor energy distribution + if m == 0: + tot1 = np.array(totals[1]) # total single scattering + tot2 = np.array(totals[2]) # total second scattering + tot3 = np.array(totals[3]) # total third scattering + total = np.array(totals[4]) # total all scattering + xMs = xEn + yMsc1 = ySc1 + yMscM = yScM + yMr = yRr + else: + tot1 = np.append(tot1,totals[1]) + tot2 = np.append(tot2,totals[2]) + tot3 = np.append(tot3,totals[3]) + total = np.append(total,totals[4]) + xMs = np.append(xMs,xEn) + yMsc1 = np.append(yMsc1,ySc1) + yMscM = np.append(yMscM,yScM) + yMr = np.append(yMr,yRr) + Qaxis += ',' + Qaxis += str(QQ[m]) # start output of Totals totx = [angle[0]] tote = np.zeros(mang) for m in range(1,mang): - totx = np.append(totx,angle[m]) + totx = np.append(totx,angle[m]) nt = 1 Taxis = 'Scat1' xTot = totx @@ -285,19 +285,19 @@ def MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): eTot = tote spec_list = [nt-1] if nmst > 1: - nt += 1 - spec_list.append(nt-1) - Taxis += ',Scat2' - xTot = np.append(xTot,totx) - yTot = np.append(yTot,tot2) - eTot = np.append(eTot,tote) - if nmst > 2: - nt += 1 - spec_list.append(nt-1) - Taxis += ',Scat3' - xTot = np.append(xTot,totx) - yTot = np.append(yTot,tot3) - eTot = np.append(eTot,tote) + nt += 1 + spec_list.append(nt-1) + Taxis += ',Scat2' + xTot = np.append(xTot,totx) + yTot = np.append(yTot,tot2) + eTot = np.append(eTot,tote) + if nmst > 2: + nt += 1 + spec_list.append(nt-1) + Taxis += ',Scat3' + xTot = np.append(xTot,totx) + yTot = np.append(yTot,tot3) + eTot = np.append(eTot,tote) xTot = np.append(xTot,totx) yTot = np.append(yTot,total) eTot = np.append(eTot,tote) @@ -325,15 +325,15 @@ def MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): GroupWorkspaces(InputWorkspaces=group,OutputWorkspace=msname+'_Scat') # start output if Save: - tot_path = os.path.join(workdir,msname+'_Totals.nxs') - SaveNexusProcessed(InputWorkspace=msname+'_Totals', Filename=tot_path) - scat_path = os.path.join(workdir,msname+'_Scat.nxs') - SaveNexusProcessed(InputWorkspace=msname+'_Scat', Filename=scat_path) - if Verbose: - logger.notice('Output total scattering file : ' + tot_path) - logger.notice('Output MS scattering file : ' + scat_path) + tot_path = os.path.join(workdir,msname+'_Totals.nxs') + SaveNexusProcessed(InputWorkspace=msname+'_Totals', Filename=tot_path) + scat_path = os.path.join(workdir,msname+'_Scat.nxs') + SaveNexusProcessed(InputWorkspace=msname+'_Scat', Filename=scat_path) + if Verbose: + logger.notice('Output total scattering file : ' + tot_path) + logger.notice('Output MS scattering file : ' + scat_path) if Plot: - plotMuscat(msname,spec_list,Plot) + plotMuscat(msname,spec_list,Plot) def MuscatFuncStart(sname,geom,neut,beam,sam,grid,disp,coeff,kr1,Verbose,Plot,Save): StartTime('Muscat Function') @@ -344,8 +344,8 @@ def MuscatFuncStart(sname,geom,neut,beam,sam,grid,disp,coeff,kr1,Verbose,Plot,Sa sqw = 'S(Q,w)' CreateSqw(disp,coeff,grid,Verbose) if Verbose: - logger.notice('Sample run : '+spath) - logger.notice('S(Q,w) from : '+disp) + logger.notice('Sample run : '+spath) + logger.notice('S(Q,w) from : '+disp) MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save) EndTime('Muscat Function') @@ -359,13 +359,13 @@ def MuscatDataStart(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): qpath = os.path.join(workdir, sqw+'.nxs') # path name for S(Q,w) nxs file LoadNexusProcessed(FileName=qpath, OutputWorkspace=sqw) if Verbose: - logger.notice('Sample run : '+spath) - logger.notice('S(Q,w) file : '+qpath) + logger.notice('Sample run : '+spath) + logger.notice('S(Q,w) file : '+qpath) MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save) EndTime('Muscat Data') def plotMuscat(inWS,spec_list,Plot): if (Plot == 'Totals' or Plot == 'All'): - tot_plot=mp.plotSpectrum(inWS+'_Totals',spec_list) + tot_plot=mp.plotSpectrum(inWS+'_Totals',spec_list) if (Plot == 'Scat1' or Plot == 'All'): - mp.importMatrixWorkspace(inWS+'_1').plotGraph2D() + mp.importMatrixWorkspace(inWS+'_1').plotGraph2D() diff --git a/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py b/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py index 40e79d977176..761a14e289ee 100644 --- a/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py +++ b/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py @@ -119,11 +119,11 @@ def _load_single_file(self, filename, output_ws): basis_mask_filename = os.path.join(config.getString('maskFiles.directory') , basis_mask) if os.path.isfile(basis_mask_filename): - LoadMask(Instrument="BASIS", OutputWorkspace="__basis_mask", + LoadMask(Instrument="BASIS", OutputWorkspace="__basis_mask", InputFile=basis_mask_filename) - MaskDetectors(Workspace=output_ws, MaskedWorkspace="__basis_mask") + MaskDetectors(Workspace=output_ws, MaskedWorkspace="__basis_mask") else: - logger.notice("Couldn't find specified mask file : " + str(basis_mask_filename)) + logger.notice("Couldn't find specified mask file : " + str(basis_mask_filename)) if self._parameter_file != None: LoadParameterFile(Workspace=output_ws,Filename= self._parameter_file) @@ -824,7 +824,7 @@ def _group_data(self, workspace): for i in range(0, nhist): if i not in self._masking_detectors: wslist.append(i) - GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, + GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, WorkspaceIndexList=wslist, Behaviour='Average') else: # We may have either a workspace name or a mapping file name here @@ -852,10 +852,10 @@ def _group_data(self, workspace): # Run GroupDetectors with a workspace if we have one # Otherwise try to run it with a mapping file if grouping_workspace is not None: - GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, CopyGroupingFromWorkspace=grouping_workspace, + GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, CopyGroupingFromWorkspace=grouping_workspace, Behaviour='Average') elif os.path.isfile(grouping_filename): - GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, MapFile=grouping_filename, + GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, MapFile=grouping_filename, Behaviour='Average') return workspace diff --git a/Code/Mantid/scripts/Inelastic/msg_reducer.py b/Code/Mantid/scripts/Inelastic/msg_reducer.py index 2f06d44cee44..e240f2929907 100644 --- a/Code/Mantid/scripts/Inelastic/msg_reducer.py +++ b/Code/Mantid/scripts/Inelastic/msg_reducer.py @@ -42,7 +42,7 @@ def pre_process(self): loadData.set_parameter_file(self._parameter_file) loadData.set_extra_load_opts(self._extra_load_opts) loadData.execute(self, None) - + if loadData.contains_event_data and (self._rebin_string is None or self._rebin_string is ''): logger.warning('Reductins of event data without rebinning may give bad data!') @@ -111,7 +111,7 @@ def set_parameter_file(self, file_name): for directory in config.getInstrumentDirectories(): if os.path.isfile(os.path.join(directory, file_name)): self._parameter_file = os.path.join(directory, file_name) - return + return def set_rebin_string(self, rebin): """Sets the rebin string to be used with the Rebin algorithm. diff --git a/Code/Mantid/scripts/Interface/compile_refm_ui.py b/Code/Mantid/scripts/Interface/compile_refm_ui.py index f73ec768ea6f..6d730cffcce1 100755 --- a/Code/Mantid/scripts/Interface/compile_refm_ui.py +++ b/Code/Mantid/scripts/Interface/compile_refm_ui.py @@ -15,4 +15,4 @@ compile_ui("ui/reflectometer/refl_stitching.ui") except: - print "Could not compile resource file" \ No newline at end of file + print "Could not compile resource file" diff --git a/Code/Mantid/scripts/Interface/compile_sans_ui.py b/Code/Mantid/scripts/Interface/compile_sans_ui.py index 1a7b3f1b7367..d7a8e65a946f 100644 --- a/Code/Mantid/scripts/Interface/compile_sans_ui.py +++ b/Code/Mantid/scripts/Interface/compile_sans_ui.py @@ -29,4 +29,4 @@ os.system("pyuic4 -o ui/ui_data_catalog.py ui/data_catalog.ui") os.system("pyuic4 -o ui/ui_stitcher.py ui/stitcher.ui") except: - print "Could not compile resource file" \ No newline at end of file + print "Could not compile resource file" diff --git a/Code/Mantid/scripts/Interface/reduction_application.py b/Code/Mantid/scripts/Interface/reduction_application.py index 79bb187d52a0..817cbe20fbc0 100644 --- a/Code/Mantid/scripts/Interface/reduction_application.py +++ b/Code/Mantid/scripts/Interface/reduction_application.py @@ -91,7 +91,7 @@ def __init__(self, instrument=None, instrument_list=None): self._compute_resources = ['Fermi'] if IS_IN_MANTIDPLOT \ and hasattr(ConfigService.Instance().getFacility(), "computeResources"): - self._compute_resources = ConfigService.Instance().getFacility().computeResources() + self._compute_resources = ConfigService.Instance().getFacility().computeResources() # Internal flag for clearing all settings and restarting the application self._clear_and_restart = False diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py index cd18ffcf104d..6c7ed3e36314 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py @@ -27,7 +27,7 @@ def __init__(self, name="VULCAN", facility="SNS"): """ Initialization """ super(DiffractionReductionScripter, self).__init__(name=name, facility=facility) - + print "[diffraction_reduction_script] Facility = %s, Instrument = %s" % (self.facility_name, self.instrument_name) return diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_utils.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_utils.py index 360c9ad69c72..c74a606fe121 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_utils.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_utils.py @@ -53,7 +53,7 @@ def get_parameter(self, name): if val[0] == "None" : return None elif type_name == "int" : - val = self._instrument.getIntParameter(name) + val = self._instrument.getIntParameter(name) else : return default try: diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/data_cat.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/data_cat.py index 387831efd38d..efe57b2e28cb 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/data_cat.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/data_cat.py @@ -175,7 +175,7 @@ def __init__(self, replace_db=True): self.db = None try: - self._create_db(db_path, replace_db) + self._create_db(db_path, replace_db) except: print "DataCatalog: Could not access local data catalog\n%s" % sys.exc_value diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py index 9311c309a351..69bf588ea991 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py @@ -113,4 +113,4 @@ class DataCatalog(BaseCatalog): data_set_cls = EQSANSDataSet def __init__(self, replace_db=False): - super(DataCatalog, self).__init__(replace_db) \ No newline at end of file + super(DataCatalog, self).__init__(replace_db) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_script.py index 1371b7028761..0354545a3284 100755 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_script.py @@ -55,4 +55,4 @@ def from_setup_info(self, xml_str): """ self.reset() super(DataSets, self).from_setup_info(xml_str) - self.background.from_setup_info(xml_str) \ No newline at end of file + self.background.from_setup_info(xml_str) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_options_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_options_script.py index 2eaf8c2d5191..77425493d07e 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_options_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_options_script.py @@ -31,10 +31,10 @@ class ReductionOptions(BaseOptions): # Perform EQSANS TOF correction perform_TOF_correction = True - + # Turn off the wedges n_wedges = 0 - + # Turn off log binning alignment with decades align_log_with_decades = False diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_catalog.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_catalog.py index 216e9ec3c250..dbb7fd0a4d7e 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_catalog.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_catalog.py @@ -94,4 +94,4 @@ class DataCatalog(BaseCatalog): data_set_cls = HFIRDataSet def __init__(self, replace_db=False): - super(DataCatalog, self).__init__(replace_db) \ No newline at end of file + super(DataCatalog, self).__init__(replace_db) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py index 76ef9527bc49..41d57b666ce3 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py @@ -40,12 +40,12 @@ class ReductionOptions(BaseScriptElement): log_binning = False align_log_with_decades = True error_weighting = False - + # Wedges n_wedges = 2 wedge_angle = 30.0 wedge_offset = 0.0 - + # Mask side masked_side = None @@ -126,13 +126,13 @@ def to_script(self): if self.align_log_with_decades: script += ", align_log_with_decades=%s" % str(self.align_log_with_decades) if self.error_weighting: script += ", error_weighting=%s" % str(self.error_weighting) script += ")\n" - + # If we align we decades, use more points for I(qx,qy) n_xy_bins = self.n_q_bins if self.log_binning and self.align_log_with_decades: n_xy_bins = int(3*self.n_q_bins) script += "IQxQy(nbins=%g)\n" % n_xy_bins - + if self.n_wedges>0: script += "SetWedges(number_of_wedges=%g, wedge_angle=%g, wedge_offset=%g)\n" % (self.n_wedges, self.wedge_angle, self.wedge_offset) @@ -198,7 +198,7 @@ def to_xml(self): xml += " %g\n" % self.n_wedges xml += " %g\n" % self.wedge_angle xml += " %g\n" % self.wedge_offset - + xml += " %d\n" % self.normalization # Output directory @@ -212,7 +212,7 @@ def to_xml(self): xml += " %g\n" % self.bottom xml += " %g\n" % self.left xml += " %g\n" % self.right - + xml += " %s\n" % str(self.masked_side) xml += " \n" @@ -452,7 +452,7 @@ def reset(self): self.log_binning = ReductionOptions.log_binning self.align_log_with_decades = ReductionOptions.align_log_with_decades self.error_weighting = ReductionOptions.error_weighting - + self.n_wedges = ReductionOptions.n_wedges self.wedge_angle = ReductionOptions.wedge_angle self.wedge_offset = ReductionOptions.wedge_offset diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py index f8105395e8d8..ea4b764e7f2a 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py @@ -383,14 +383,14 @@ def weightedMean(self, data_array, error_array): sz = len(data_array) # calculate the numerator of mean - dataNum = 0; + dataNum = 0 for i in range(sz): if not (data_array[i] == 0): tmpFactor = float(data_array[i]) / float((pow(error_array[i],2))) dataNum += tmpFactor # calculate denominator - dataDen = 0; + dataDen = 0 for i in range(sz): if not (error_array[i] == 0): tmpFactor = 1./float((pow(error_array[i],2))) @@ -444,7 +444,7 @@ def _average_y_of_same_x_(self): for j in range(len(data_y_i)): if data_y[j]>0 and data_y_i[j]>0: - [data_y[j], data_e[j]] = self.weightedMean([data_y[j], data_y_i[j]], [data_e[j], data_e_i[j]]); + [data_y[j], data_e[j]] = self.weightedMean([data_y[j], data_y_i[j]], [data_e[j], data_e_i[j]]) elif (data_y[j] == 0) and (data_y_i[j]>0): data_y[j] = data_y_i[j] data_e[j] = data_e_i[j] @@ -973,7 +973,7 @@ def _plot_count_vs_y(self, is_peak=True): For REFM, this is X For REFL, this is Y """ - + # run_number = self._summary.data_run_number_edit.text() # f = FileFinder.findRuns("%s%s" % (self.instrument_name, str(run_number)))[0] # @@ -1122,12 +1122,12 @@ def _plot_data_count_vs_tof_2d(self): #mantidplot.app.connect(mantidplot.app.mantidUI, QtCore.SIGNAL("python_peak_back_tof_range_update(double,double,double,double,double,double)"), call_back) #mantidplot.app.connect(mantidplot.app.RefDetectorViewer, QtCore.SIGNAL("python_peak_back_tof_range_update(double,double,double,double,double,double)"), call_back) - peak_min = int(self._summary.data_peak_from_pixel.text()); - peak_max = int(self._summary.data_peak_to_pixel.text()); - back_min = int(self._summary.data_background_from_pixel1.text()); - back_max = int(self._summary.data_background_to_pixel1.text()); - tof_min = int(self._summary.data_from_tof.text()); - tof_max = int(self._summary.data_to_tof.text()); + peak_min = int(self._summary.data_peak_from_pixel.text()) + peak_max = int(self._summary.data_peak_to_pixel.text()) + back_min = int(self._summary.data_background_from_pixel1.text()) + back_max = int(self._summary.data_background_to_pixel1.text()) + tof_min = int(self._summary.data_from_tof.text()) + tof_max = int(self._summary.data_to_tof.text()) import mantidqtpython self.ref_det_view = mantidqtpython.MantidQt.RefDetectorViewer.RefMatrixWSImageView(ws_output_base, peak_min, peak_max, back_min, back_max, tof_min, tof_max) @@ -1136,12 +1136,12 @@ def _plot_data_count_vs_tof_2d(self): def call_back(self, peakmin, peakmax, backmin, backmax, tofmin, tofmax): - self._summary.data_peak_from_pixel.setText("%-d" % int(peakmin)) - self._summary.data_peak_to_pixel.setText("%-d" % int(peakmax)) - self._summary.data_background_from_pixel1.setText("%-d" % int(backmin)) - self._summary.data_background_to_pixel1.setText("%-d" % int(backmax)) - self._summary.data_from_tof.setText("%-d" % int(tofmin)) - self._summary.data_to_tof.setText("%-d" % int(tofmax)) + self._summary.data_peak_from_pixel.setText("%-d" % int(peakmin)) + self._summary.data_peak_to_pixel.setText("%-d" % int(peakmax)) + self._summary.data_background_from_pixel1.setText("%-d" % int(backmin)) + self._summary.data_background_to_pixel1.setText("%-d" % int(backmax)) + self._summary.data_from_tof.setText("%-d" % int(tofmin)) + self._summary.data_to_tof.setText("%-d" % int(tofmax)) def _norm_count_vs_y(self): diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py index 062c0497128a..182eafe93435 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py @@ -964,12 +964,12 @@ def _plot_data_count_vs_tof_2d(self): #mantidplot.app.connect(mantidplot.app.mantidUI, QtCore.SIGNAL("python_peak_back_tof_range_update(double,double,double,double,double,double)"), call_back) #mantidplot.app.connect(mantidplot.app.RefDetectorViewer, QtCore.SIGNAL("python_peak_back_tof_range_update(double,double,double,double,double,double)"), call_back) - peak_min = int(self._summary.data_peak_from_pixel.text()); - peak_max = int(self._summary.data_peak_to_pixel.text()); - back_min = int(self._summary.data_background_from_pixel1.text()); - back_max = int(self._summary.data_background_to_pixel1.text()); - tof_min = int(self._summary.data_from_tof.text()); - tof_max = int(self._summary.data_to_tof.text()); + peak_min = int(self._summary.data_peak_from_pixel.text()) + peak_max = int(self._summary.data_peak_to_pixel.text()) + back_min = int(self._summary.data_background_from_pixel1.text()) + back_max = int(self._summary.data_background_to_pixel1.text()) + tof_min = int(self._summary.data_from_tof.text()) + tof_max = int(self._summary.data_to_tof.text()) import mantidqtpython self.ref_det_view = mantidqtpython.MantidQt.RefDetectorViewer.RefMatrixWSImageView(ws_output_base_ff+'_2D', peak_min, peak_max, back_min, back_max, tof_min, tof_max) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py index 1a8ef047e21c..a60f556c2c2f 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py @@ -120,7 +120,7 @@ def initialize_content(self): self.connect(self._summary.log_binning_radio, QtCore.SIGNAL("clicked(bool)"), self._summary.align_check.setEnabled) self._summary.scale_edit.setText("1") - + self._summary.n_wedges_edit.setText("2") self._summary.wedge_angle_edit.setText("30") self._summary.wedge_offset_edit.setText("0") @@ -150,7 +150,7 @@ def initialize_content(self): self._summary.mask_side_none_radio.hide() self._summary.mask_side_front_radio.hide() self._summary.mask_side_back_radio.hide() - + if not self._in_mantidplot: self._summary.dark_plot_button.hide() self._summary.scale_data_plot_button.hide() @@ -349,18 +349,18 @@ def set_state(self, state): self._summary.align_check.setEnabled(state.log_binning) self._summary.align_check.setChecked(state.align_log_with_decades) self._summary.error_weighting_check.setChecked(state.error_weighting) - + self._summary.n_wedges_edit.setText(str(state.n_wedges)) self._summary.wedge_angle_edit.setText(str(state.wedge_angle)) self._summary.wedge_offset_edit.setText(str(state.wedge_offset)) - + # Mask self._summary.mask_edit.setText(str(state.mask_file)) self._summary.mask_check.setChecked(state.use_mask_file) self._mask_checked(state.use_mask_file) self._masked_detectors = state.detector_ids self.mask_reload = True - + if state.masked_side == 'Front': self._summary.mask_side_front_radio.setChecked(True) elif state.masked_side == 'Back': @@ -440,7 +440,7 @@ def get_state(self): m.masked_side = 'Back' else: m.masked_side = None - + # Mask detector IDs m.use_mask_file = self._summary.mask_check.isChecked() m.mask_file = unicode(self._summary.mask_edit.text()) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_sample_data.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_sample_data.py index ff890705a4e9..9370179713b7 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_sample_data.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_sample_data.py @@ -172,7 +172,7 @@ def get_state(self): return m def _sample_scatt_plot(self): - self.show_instrument(unicode(self._content.sample_scatt_edit.text())) + self.show_instrument(unicode(self._content.sample_scatt_edit.text())) def _sample_scatt_browse(self): fname = self.data_browse_dialog() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py index 9ec8166fc03d..0bfeaae8a135 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py @@ -162,13 +162,13 @@ def _get_catalog(self): self._content.data_set_table.resizeColumnsToContents() def _browse_directory(self): - dir = QtGui.QFileDialog.getExistingDirectory(self, "Open Directory", + dir = QtGui.QFileDialog.getExistingDirectory(self, "Open Directory", self._settings.data_path) - if dir: + if dir: # Store the location of the loaded file - self._settings.data_path = str(dir) - self._content.directory_edit.setText(dir) - self._update_content() + self._settings.data_path = str(dir) + self._content.directory_edit.setText(dir) + self._update_content() def set_state(self, state): """ @@ -180,4 +180,4 @@ def set_state(self, state): self._update_content(False) def get_state(self): - return Catalog() \ No newline at end of file + return Catalog() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/stitcher.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/stitcher.py index ff8927473391..2b3e26f44914 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/stitcher.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/stitcher.py @@ -512,4 +512,4 @@ def get_state(self): """ Return dummy state """ - return StitcherState() \ No newline at end of file + return StitcherState() diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_choose_col.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_choose_col.py index 7a027ee6777e..73a0a4aa64bd 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_choose_col.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_choose_col.py @@ -37,4 +37,4 @@ def on_listColumns_itemChanged(self, item): def on_buttonsColumns_Clicked(self, button): if self.buttonsColumns.button(QtGui.QDialogButtonBox.RestoreDefaults) == button: for i in range(self.listColumns.count()): - self.listColumns.item(i).setCheckState(2) \ No newline at end of file + self.listColumns.item(i).setCheckState(2) diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py index 99b3c7da943e..5e8aabb610e7 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py @@ -93,17 +93,17 @@ def __init__(self): settings.endGroup() settings.beginGroup(self.__generic_settings) - + self.__alg_migrate = settings.value(self.__alg_migration_key, True, type=bool) if self.__alg_migrate: self.__alg_use = True # We will use the algorithms by default rather than the quick scripts self.__alg_migrate = False # Never do this again. We only want to reset once. else: self.__alg_use = settings.value(self.__ads_use_key, True, type=bool) - + self.__icat_download = settings.value(self.__icat_download_key, False, type=bool) self.__group_tof_workspaces = settings.value(self.__group_tof_workspaces_key, True, type=bool) - + settings.setValue(self.__ads_use_key, self.__alg_use) settings.setValue(self.__icat_download_key, self.__icat_download) settings.setValue(self.__group_tof_workspaces_key, self.__group_tof_workspaces) @@ -127,15 +127,15 @@ def _save_check(self): """ msgBox = QtGui.QMessageBox() msgBox.setText("The table has been modified. Do you want to save your changes?") - + accept_btn = QtGui.QPushButton('Accept') cancel_btn = QtGui.QPushButton('Cancel') discard_btn = QtGui.QPushButton('Discard') - + msgBox.addButton(accept_btn, QtGui.QMessageBox.AcceptRole) msgBox.addButton(cancel_btn, QtGui.QMessageBox.RejectRole) msgBox.addButton(discard_btn, QtGui.QMessageBox.NoRole) - + msgBox.setIcon(QtGui.QMessageBox.Question) msgBox.setDefaultButton(accept_btn) msgBox.setEscapeButton(cancel_btn) @@ -149,7 +149,7 @@ def _save_check(self): ret = QtGui.QMessageBox.RejectRole else: ret = QtGui.QMessageBox.NoRole - + return ret, saved def closeEvent(self, event): @@ -166,7 +166,7 @@ def closeEvent(self, event): elif ret == QtGui.QMessageBox.NoRole: self.mod_flag = False event.accept() - + def _instrument_selected(self, instrument): """ Change the default instrument to the selected one @@ -717,7 +717,7 @@ def _process(self): #If we're given a group workspace, we can just run it on the first member of the group instead thetaRun = loadedRun if isinstance(thetaRun, WorkspaceGroup): - thetaRun = thetaRun[0] + thetaRun = thetaRun[0] dqq, two_theta = CalculateResolution(Workspace = thetaRun, TwoTheta = two_theta) #Put the calculated resolution into the table @@ -783,7 +783,7 @@ def _process(self): #Scale each run if self.tableMain.item(row, self.scale_col).text(): Scale(InputWorkspace=wksp[i], OutputWorkspace=wksp[i], Factor=1 / float(self.tableMain.item(row, self.scale_col).text())) - + if self.__checked_row_stiched(row): if (len(runno) == 1): logger.notice("Nothing to combine for processing row : " + str(row)) @@ -803,8 +803,8 @@ def _process(self): Qmax = max(w2.readX(0)) wcomb = combineDataMulti(wksp, outputwksp, overlapLow, overlapHigh, Qmin, Qmax, -dqq, 1, keep=True) - - + + # Enable the plot button plotbutton = self.tableMain.cellWidget(row, self.plot_col).children()[1] plotbutton.setProperty('runno',runno) @@ -896,7 +896,7 @@ def _plot(self, plotbutton): if not getWorkspace(outputwksp, report_error=False): # Stitching has not been done as part of processing, so we need to do it here. wcomb = combineDataMulti(wkspBinned, outputwksp, overlapLow, overlapHigh, Qmin, Qmax, -dqq, 1, keep=True) - + Qmin = min(getWorkspace(outputwksp).readX(0)) Qmax = max(getWorkspace(outputwksp).readX(0)) if canMantidPlot: @@ -1198,8 +1198,8 @@ def _options_dialog(self): Shows the dialog for setting options regarding live data """ try: - - dialog_controller = refl_options.ReflOptions(def_method = self.live_method, def_freq = self.live_freq, + + dialog_controller = refl_options.ReflOptions(def_method = self.live_method, def_freq = self.live_freq, def_alg_use = self.__alg_use, def_icat_download=self.__icat_download, def_group_tof_workspaces = self.__group_tof_workspaces) if dialog_controller.exec_(): diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui_run.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui_run.py index 484e52c3dfab..acb98704976e 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui_run.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui_run.py @@ -8,4 +8,4 @@ ui = refl_gui.ReflGui() ui.setupUi(MainWindow) MainWindow.show() - sys.exit(app.exec_()) \ No newline at end of file + sys.exit(app.exec_()) diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py index da837f4513dd..d5b9d9732923 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py @@ -76,7 +76,7 @@ def groupTOFWorkspaces(self): def frequency(self): return self.__frequency - + def useAlg(self): return self.__alg_use diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py index f7d4a857e09f..86d774ee8f90 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py @@ -17,7 +17,7 @@ class Ui_SaveWindow(object): def __init__(self): - self.__has_mount_point = True; + self.__has_mount_point = True self.__instrument = config['default.instrument'].strip().upper() @@ -26,7 +26,7 @@ def __init__(self): self.__mountpoint = usersettings.get_named_setting("DataMountPoint") except KeyError: print "DataMountPoint is missing from the config.xml file." - self.__has_mount_point = False; + self.__has_mount_point = False def setupUi(self, SaveWindow): self.SavePath="" diff --git a/Code/Mantid/scripts/LargeScaleStructures/EQSANS_geometry.py b/Code/Mantid/scripts/LargeScaleStructures/EQSANS_geometry.py index ad61eeed9c47..11c91894edc1 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/EQSANS_geometry.py +++ b/Code/Mantid/scripts/LargeScaleStructures/EQSANS_geometry.py @@ -94,4 +94,4 @@ def create_geometry(file_name=None, tube_width=TUBE_WIDTH, tube_length=TUBE_SIZE det.writeGeom(xml_outfile) if __name__ == "__main__": - create_geometry() \ No newline at end of file + create_geometry() diff --git a/Code/Mantid/scripts/LargeScaleStructures/REF_L_geometry.py b/Code/Mantid/scripts/LargeScaleStructures/REF_L_geometry.py index 45b8018c8691..f60a886bf4ca 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/REF_L_geometry.py +++ b/Code/Mantid/scripts/LargeScaleStructures/REF_L_geometry.py @@ -100,4 +100,4 @@ def create_geometry(file_name=None, pixel_width=None, pixel_height=None): if __name__ == "__main__": create_geometry() - #create_grouping() \ No newline at end of file + #create_grouping() diff --git a/Code/Mantid/scripts/LargeScaleStructures/ReflectometerCors.py b/Code/Mantid/scripts/LargeScaleStructures/ReflectometerCors.py index f81bdb8f1c58..8de9fd47cf73 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/ReflectometerCors.py +++ b/Code/Mantid/scripts/LargeScaleStructures/ReflectometerCors.py @@ -1,65 +1,65 @@ from mantid.simpleapi import * def heliumDetectorEff(workspace): - ''' Calculate the corrected Helium detector values. ''' + ''' Calculate the corrected Helium detector values. ''' - ac= 6.022169e23 # Avogadro's constant mol-1 - vm= 2.24136e4 # Molar volume of gas cm3 mol-1 - gp= 10.0 # Gas pressure (atms) - gsig0= 5333.0e-24 # Gas cross section at LAM0 cm2 - gt= 2.5 # Gas path length cm - lam0= 1.8 # Characteristic wavelength + ac= 6.022169e23 # Avogadro's constant mol-1 + vm= 2.24136e4 # Molar volume of gas cm3 mol-1 + gp= 10.0 # Gas pressure (atms) + gsig0= 5333.0e-24 # Gas cross section at LAM0 cm2 + gt= 2.5 # Gas path length cm + lam0= 1.8 # Characteristic wavelength - gn= ac*gp/vm # Number density of gas - sgn= gn*gsig0*gt/lam0 # Exponential term for gas + gn= ac*gp/vm # Number density of gas + sgn= gn*gsig0*gt/lam0 # Exponential term for gas - OneMinusExponentialCor(InputWorkspace=workspace,OutputWorkspace=workspace,C=str(sgn),Operation="Divide") + OneMinusExponentialCor(InputWorkspace=workspace,OutputWorkspace=workspace,C=str(sgn),Operation="Divide") - wt= 60.014 # Molecular weight Ni-Cu g mol-1 - rho= 8.00 # Density Ni-Cu g cm-3 - ct= 0.05 # Monel (Ni-Cu) wall thickness cm - wsig0= 4.522e-24 # Wall cross section at LAM0 cm2 + wt= 60.014 # Molecular weight Ni-Cu g mol-1 + rho= 8.00 # Density Ni-Cu g cm-3 + ct= 0.05 # Monel (Ni-Cu) wall thickness cm + wsig0= 4.522e-24 # Wall cross section at LAM0 cm2 - wn= ac*rho/wt # Number density of wall - swn= wn*wsig0*ct/lam0 # Exponential term for wall + wn= ac*rho/wt # Number density of wall + swn= wn*wsig0*ct/lam0 # Exponential term for wall - ExponentialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,C1=str(swn),Operation="Divide") + ExponentialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,C1=str(swn),Operation="Divide") # simple polynomial correction based on a D2O spectrum taken at 1.5 deg - PolynomialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,Coefficients="-1.3697,0.8602,-0.7839,0.2866,-0.0447,0.0025") - return + PolynomialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,Coefficients="-1.3697,0.8602,-0.7839,0.2866,-0.0447,0.0025") + return def monitor2Eff(workspace): - ''' Calculate the corrected monitor2 values. ''' + ''' Calculate the corrected monitor2 values. ''' # expon= unt*(1-exp(-8.3047 * zz * x_mean )) # yout[i]= yin[i]*(1.0-expon) / expon # eout[i]= ein[i]*(1.0-expon) / expon # The above correction is equivalent to: (1/unt - 1) + e^(-8.3047*zz*x) # ------------------------------ # ( 1 - e^(-8.3047*zz*x) ) - unt=0.24 # 0.05 # ratio of scintillator to total area - zz = 0.6 #0.03 # thickness(cm) of scintillator - c1 = 0.7112*zz #8.3047*zz + unt=0.24 # 0.05 # ratio of scintillator to total area + zz = 0.6 #0.03 # thickness(cm) of scintillator + c1 = 0.7112*zz #8.3047*zz - ExponentialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,C1=str(c1),Operation="Multiply") - shift = (1.0/unt)-1.0 - CreateSingleValuedWorkspace(OutputWorkspace="shift",DataValue=str(shift),ErrorValue="0.0") - Plus(LHSWorkspace=workspace,RHSWorkspace="shift",OutputWorkspace=workspace) - mtd.remove("shift") - OneMinusExponentialCor(InputWorkspace=workspace,OutputWorkspace=workspace,C=str(c1)) + ExponentialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,C1=str(c1),Operation="Multiply") + shift = (1.0/unt)-1.0 + CreateSingleValuedWorkspace(OutputWorkspace="shift",DataValue=str(shift),ErrorValue="0.0") + Plus(LHSWorkspace=workspace,RHSWorkspace="shift",OutputWorkspace=workspace) + mtd.remove("shift") + OneMinusExponentialCor(InputWorkspace=workspace,OutputWorkspace=workspace,C=str(c1)) - return + return def main(): - '''This main routine. It is executed on if the script is run directly, not if it is imported.''' - LoadRawDialog(OutputWorkspace="ws",SpectrumMin="1",SpectrumMax="1") - ConvertUnits(InputWorkspace="ws",OutputWorkspace="ws",Target="Wavelength",AlignBins="1") - heliumDetectorEff("ws") - monitor2Eff("ws") - print "Done!" + '''This main routine. It is executed on if the script is run directly, not if it is imported.''' + LoadRawDialog(OutputWorkspace="ws",SpectrumMin="1",SpectrumMax="1") + ConvertUnits(InputWorkspace="ws",OutputWorkspace="ws",Target="Wavelength",AlignBins="1") + heliumDetectorEff("ws") + monitor2Eff("ws") + print "Done!" if __name__ == '__main__': - main() + main() diff --git a/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py b/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py index df87ed791fa8..1d68dcbc7ad6 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py +++ b/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py @@ -76,10 +76,10 @@ def addModerator(self, distance): """ source = self._append_child("component", self._root, type="moderator") try: - distance = float(distance) - if distance > 0: - distance *= -1.0 - self._append_child("location", source, z=distance) + distance = float(distance) + if distance > 0: + distance *= -1.0 + self._append_child("location", source, z=distance) except: print "PROBLEM with addModerator" @@ -198,7 +198,7 @@ def addDetector(self, x, y, z, rot_x, rot_y, rot_z, name, comp_type, usepolar=No if usepolar is not None: self.addLocationPolar(comp_element, x, y, z) else: - self.addLocation(comp_element, x, y, z, rot_x, rot_y, rot_z) + self.addLocation(comp_element, x, y, z, rot_x, rot_y, rot_z) def addSingleDetector(self, root, x, y, z, rot_x, rot_y, rot_z, name=None, id=None, usepolar=None): diff --git a/Code/Mantid/scripts/ORNL_SANS.py b/Code/Mantid/scripts/ORNL_SANS.py index 885aadc6e708..b26c507a6d61 100644 --- a/Code/Mantid/scripts/ORNL_SANS.py +++ b/Code/Mantid/scripts/ORNL_SANS.py @@ -6,4 +6,4 @@ reducer = ReductionGUI(instrument_list=["BIOSANS", "GPSANS", "EQSANS"]) if reducer.setup_layout(load_last=True): - reducer.show() \ No newline at end of file + reducer.show() diff --git a/Code/Mantid/scripts/PyChop.py b/Code/Mantid/scripts/PyChop.py index d98e547ebd8c..e349285143ae 100644 --- a/Code/Mantid/scripts/PyChop.py +++ b/Code/Mantid/scripts/PyChop.py @@ -7,9 +7,9 @@ def qapp(): if QtGui.QApplication.instance(): - app = QtGui.QApplication.instance() + app = QtGui.QApplication.instance() else: - app = QtGui.QApplication(sys.argv) + app = QtGui.QApplication(sys.argv) return app app = qapp() @@ -19,4 +19,4 @@ def qapp(): else: Resolution = PyChopGUI.MainWindow() Resolution.show() -app.exec_() \ No newline at end of file +app.exec_() diff --git a/Code/Mantid/scripts/PyChop/PyChop.py b/Code/Mantid/scripts/PyChop/PyChop.py index f01b80fe0f8f..9c9874475f83 100644 --- a/Code/Mantid/scripts/PyChop/PyChop.py +++ b/Code/Mantid/scripts/PyChop/PyChop.py @@ -3,9 +3,9 @@ import numpy from mantid.simpleapi import * try: - from mantidplot import * + from mantidplot import * except ImportError: - pass + pass ''' chop(inst,ei,chop_type,frequency): python implementation of CHOP ver 1.0 @@ -193,39 +193,39 @@ def calculate(ei,frequency,**kwargs): if instname=='maps' or instname=='map' or instname=='MAP'or instname=='MAPS': #For MAPS - x0 = 10.1000 - xa = 8.1100 - x1 = 1.9000 - x2 = 6.0000 - wa_mm = 70.130 - ha_mm = 70.130 - wa = ha_mm / 1000.00 - ha = ha_mm / 1000.00 + x0 = 10.1000 + xa = 8.1100 + x1 = 1.9000 + x2 = 6.0000 + wa_mm = 70.130 + ha_mm = 70.130 + wa = ha_mm / 1000.00 + ha = ha_mm / 1000.00 # chopper details # now some moderator details # for 300K H2O - s=numpy.zeros(6) - s[1] = 38.60 - s[2] = 0.52260 - s[3] = 0.00 - s[4] = 0.00 - s[5] = 0.00 - th_deg = 32.00 - imod = 2 - mod_type = 'AP' + s=numpy.zeros(6) + s[1] = 38.60 + s[2] = 0.52260 + s[3] = 0.00 + s[4] = 0.00 + s[5] = 0.00 + th_deg = 32.00 + imod = 2 + mod_type = 'AP' # sample details - sx_mm = 2.00 - sy_mm = 50.00 - sz_mm = 50.00 - isam = 0 - gam_deg = 0.00 - ia = 0 - ix = 0 + sx_mm = 2.00 + sy_mm = 50.00 + sz_mm = 50.00 + isam = 0 + gam_deg = 0.00 + ia = 0 + ix = 0 # detector details - idet = 1 - dd_mm = 250 - tbin_us = 0.00 + idet = 1 + dd_mm = 250 + tbin_us = 0.00 #chop_par,titledata=setchoptype(instname,chop_type) # end of maps parameters @@ -788,7 +788,7 @@ def achop(ei,omega): return area def frange(limit1, limit2 = None, increment = 1.): - """ + """ Range function that accepts floats (and integers). Usage: @@ -799,10 +799,10 @@ def frange(limit1, limit2 = None, increment = 1.): The returned value is an iterator. Use list(frange) for a list. """ - if limit2 is None: - limit2, limit1 = limit1, 0. - else: - limit1 = float(limit1) + if limit2 is None: + limit2, limit1 = limit1, 0. + else: + limit1 = float(limit1) - count = int(math.ceil(limit2 - limit1)/increment) - return (limit1 + n*increment for n in range(count)) + count = int(math.ceil(limit2 - limit1)/increment) + return (limit1 + n*increment for n in range(count)) diff --git a/Code/Mantid/scripts/PyChop/PyChopGUI.py b/Code/Mantid/scripts/PyChop/PyChopGUI.py index 463e066e20b3..67c4801132ef 100644 --- a/Code/Mantid/scripts/PyChop/PyChopGUI.py +++ b/Code/Mantid/scripts/PyChop/PyChopGUI.py @@ -40,9 +40,9 @@ def set_inst(self,name): self.inst=name config['default.instrument']=name if len(self.chop)>0: - message,err = PyChop.setchoptype(self.inst,self.chop) - if err>0: - self.chop='' + message,err = PyChop.setchoptype(self.inst,self.chop) + if err>0: + self.chop='' def set_chop(self,chop_type): message,err = PyChop.setchoptype(self.inst,chop_type) diff --git a/Code/Mantid/scripts/PyChop/fluxGUI.py b/Code/Mantid/scripts/PyChop/fluxGUI.py index c2e6dc39c391..989aff9fd9bd 100644 --- a/Code/Mantid/scripts/PyChop/fluxGUI.py +++ b/Code/Mantid/scripts/PyChop/fluxGUI.py @@ -29,7 +29,7 @@ def __init__(self, parent=None): QtCore.QObject.connect(self.ui.actionMAPS,QtCore.SIGNAL("triggered()"), lambda : self.otherInstrumentSelected('MAP')) - self.graph=None; + self.graph=None self.loadData() @@ -56,7 +56,7 @@ def loadData(self): self.res_energies = array.array( 'f', [0.2, 0.4, 0.6, 0.8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40] ) self.frequencies = np.arange(30,310,10) - self.ei=""; + self.ei="" self.ei_min = 0.2 # max(min(self.flux_energies),min(self.res_energies)) self.ei_max = 40. #min(max(self.flux_energies),max(self.res_energies)) @@ -108,8 +108,8 @@ def interpolate_data(self,data_matrix,energies): return result def letSelected(self): - QtGui.QMessageBox.warning(self, "Currently You have to switch gui to select another instrument") - self.ui.actionLET.setChecked(True) + QtGui.QMessageBox.warning(self, "Currently You have to switch gui to select another instrument") + self.ui.actionLET.setChecked(True) def otherInstrumentSelected(self,INAME): reply = QtGui.QMessageBox.question(self, 'Selecting : '+INAME, "Do you want to switch GUI?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) @@ -133,7 +133,7 @@ def calculate(self): self.ei = float (self.ei) if self.ei< self.ei_min or self.ei > self.ei_max: - self.ei=""; + self.ei="" QtGui.QMessageBox.warning(self, "LETFlux", "Energy out of range.\n Please, Provide value between "+str(self.ei_min)+" and "+str(self.ei_max)+" meV \n") else: self.setUpTable() @@ -142,7 +142,7 @@ def calculate(self): self.ui.list.insertItem(0,string) string_title = 'Frequency(Hz) Flux(n/s/cm^2) Resolution[ueV]' self.ui.list.insertItem(1,string_title) - t=self.t; + t=self.t for i in xrange(0, len(self.frequencies)): string1 = str(self.frequencies[i])+' '+ "%e" % t.cell(2,i+1)+' '+ "%e"% t.cell(3,i+1) self.ui.list.insertItem(2+i,string1) @@ -171,7 +171,7 @@ def plotData(self): self.graph = newGraph("Flux and Resolution",2,1,2) - l1 = self.graph.layer(1); + l1 = self.graph.layer(1) l1.setAntialiasing() l1.setTitle("Flux") l1.setAxisTitle(Layer.Bottom, "Frequency [Hz]") @@ -179,7 +179,7 @@ def plotData(self): l1.showGrid() # self.graphFlux.insertCurve(self.t, "Flux/Frequency_2", Layer.Scatter) # legend = self.graphFlux.newLegend(str(self.ei)) - l2 = self.graph.layer(2); + l2 = self.graph.layer(2) l2.setAntialiasing() l2.setTitle("Resolution") l2.setAxisTitle(Layer.Bottom, "Frequency [Hz]") @@ -188,9 +188,9 @@ def plotData(self): # self.graphRes.insertCurve(self.t, "Resolution/Frequency_2", Layer.Scatter) l2.showGrid() - self.addPlot(); + self.addPlot() - self.raise_(); + self.raise_() self.show() return self @@ -199,7 +199,7 @@ def addPlot(self): """ Adds plot to an existing graph """ if self.graph==None: - self.plotData(); + self.plotData() else: self.calculate() if self.ei == "": diff --git a/Code/Mantid/scripts/REFL_Reduction.py b/Code/Mantid/scripts/REFL_Reduction.py index b811a3f8f53e..ef1b36bd3c63 100644 --- a/Code/Mantid/scripts/REFL_Reduction.py +++ b/Code/Mantid/scripts/REFL_Reduction.py @@ -6,4 +6,4 @@ reducer = ReductionGUI(instrument="REFL", instrument_list=["REFL"]) if reducer.setup_layout(load_last=True): - reducer.show() \ No newline at end of file + reducer.show() diff --git a/Code/Mantid/scripts/REFL_SF_Calculator.py b/Code/Mantid/scripts/REFL_SF_Calculator.py index 839f8d3b21b9..eb094088327c 100644 --- a/Code/Mantid/scripts/REFL_SF_Calculator.py +++ b/Code/Mantid/scripts/REFL_SF_Calculator.py @@ -6,4 +6,4 @@ reducer = ReductionGUI(instrument="REFLSF", instrument_list=["REFLSF"]) if reducer.setup_layout(load_last=True): - reducer.show() \ No newline at end of file + reducer.show() diff --git a/Code/Mantid/scripts/REFM_Reduction.py b/Code/Mantid/scripts/REFM_Reduction.py index 42aa147ac080..f56996b14c9b 100644 --- a/Code/Mantid/scripts/REFM_Reduction.py +++ b/Code/Mantid/scripts/REFM_Reduction.py @@ -6,4 +6,4 @@ reducer = ReductionGUI(instrument="REFM", instrument_list=["REFM"]) if reducer.setup_layout(load_last=True): - reducer.show() \ No newline at end of file + reducer.show() diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/combineMulti.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/combineMulti.py index 037f88995b45..81467796e337 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/combineMulti.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/combineMulti.py @@ -20,37 +20,37 @@ def combineDataMulti(wksp_list,output_wksp,beg_overlap,end_overlap,Qmin,Qmax,bin # check if overlaps have correct number of entries defaultoverlaps = False if type(beg_overlap) != list: - beg_overlap = [beg_overlap] + beg_overlap = [beg_overlap] if type(end_overlap) != list: - end_overlap = [end_overlap] + end_overlap = [end_overlap] if len(wksp_list) != len(beg_overlap): - print "Using default values!" - defaultoverlaps = True + print "Using default values!" + defaultoverlaps = True #copy first workspace into temporary wksp 'currentSum' currentSum = CloneWorkspace(InputWorkspace=wksp_list[0]) print "Length: ",len(wksp_list), wksp_list for i in range(0,len(wksp_list)-1): - w1=currentSum - w2=getWorkspace(wksp_list[i+1]) # TODO: distinguishing between a group and a individual workspace is unnecessary for an algorithm. But custom group behavior WILL be required. - if defaultoverlaps: - overlapLow = w2.readX(0)[0] - overlapHigh = 0.5*max(w1.readX(0)) - else: - overlapLow = beg_overlap[i+1] - overlapHigh = end_overlap[i] - print "Iteration",i - currentSum, scale_factor = stitch2(currentSum, mtd[wksp_list[i+1]], currentSum.name(), overlapLow, overlapHigh, Qmin, Qmax, binning, scale_high) + w1=currentSum + w2=getWorkspace(wksp_list[i+1]) # TODO: distinguishing between a group and a individual workspace is unnecessary for an algorithm. But custom group behavior WILL be required. + if defaultoverlaps: + overlapLow = w2.readX(0)[0] + overlapHigh = 0.5*max(w1.readX(0)) + else: + overlapLow = beg_overlap[i+1] + overlapHigh = end_overlap[i] + print "Iteration",i + currentSum, scale_factor = stitch2(currentSum, mtd[wksp_list[i+1]], currentSum.name(), overlapLow, overlapHigh, Qmin, Qmax, binning, scale_high) RenameWorkspace(InputWorkspace=currentSum.name(),OutputWorkspace=output_wksp) # Remove any existing workspaces from the workspace list. if not keep: - names = mtd.getObjectNames() - for ws in wksp_list: - candidate = ws - if candidate in names: - DeleteWorkspace(candidate) + names = mtd.getObjectNames() + for ws in wksp_list: + candidate = ws + if candidate in names: + DeleteWorkspace(candidate) return mtd[output_wksp] @@ -70,10 +70,10 @@ def stitch2(ws1, ws2, output_ws_name, begoverlap,endoverlap,Qmin,Qmax,binning,sc scalefactor: Use the manual scaling factor provided if > 0 """ if scalefactor > 0.0: - manual_scalefactor = True + manual_scalefactor = True else: - manual_scalefactor = False - scalefactor = 1.0 + manual_scalefactor = False + scalefactor = 1.0 # Interally use the Stitch1D algorithm. outputs = Stitch1D(LHSWorkspace=ws1, RHSWorkspace=ws2, OutputWorkspace=output_ws_name, StartOverlap=begoverlap, EndOverlap=endoverlap, @@ -99,10 +99,10 @@ def combine2(wksp1,wksp2,outputwksp,begoverlap,endoverlap,Qmin,Qmax,binning,scal scalefactor: Use the manual scaling factor provided if > 0 """ if scalefactor > 0.0: - manual_scalefactor = True + manual_scalefactor = True else: - manual_scalefactor = False - scalefactor = 1.0 + manual_scalefactor = False + scalefactor = 1.0 # Interally use the Stitch1D algorithm. outputs = Stitch1D(LHSWorkspace=mtd[wksp1], RHSWorkspace=mtd[wksp2], OutputWorkspace=outputwksp, StartOverlap=begoverlap, EndOverlap=endoverlap, @@ -118,9 +118,9 @@ def getWorkspace(wksp): Get the workspace if it is not a group workspace. If it is a group workspace, get the first period. """ if isinstance(mtd[wksp], WorkspaceGroup): - wout = mtd[wksp][0] + wout = mtd[wksp][0] else: - wout = mtd[wksp] + wout = mtd[wksp] return wout diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py index 2f724574dee3..5507b75bff15 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py @@ -51,7 +51,7 @@ def to_workspace(cls, candidate, ws_prefix="_"): msi.Load(Filename=candidate, OutputWorkspace=ws_name) _workspace = mantid.api.AnalysisDataService.retrieve(ws_name) else: - raise ValueError("Unknown source item %s" % candidate) + raise ValueError("Unknown source item %s" % candidate) return _workspace def get_workspace_from_list(self, index): diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py index c3b43430dd0d..f2fac19542b9 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py @@ -1,16 +1,16 @@ from math import * try: - from mantid.simpleapi import * # New API + from mantid.simpleapi import * # New API except ImportError: - pass + pass #import qti as qti import numpy as n def addRuns(runlist,wname): - mtd.deleteWorkspace(str(wname)) - output=str(wname) - if runlist[0] != "0": + mtd.deleteWorkspace(str(wname)) + output=str(wname) + if runlist[0] != "0": #nzeros=8-len(str(runlist[0])) #fpad="" #for i in range(nzeros): @@ -24,20 +24,20 @@ def addRuns(runlist,wname): #fname=fname.lower() ##fname=str.replace(fname,'.nxs','.raw') #Load(fname,output) - Load(str(runlist[0]),output) - else: - #dae="ndx"+mtd.settings['default.instrument'].lower() - dae="ndxoffspec" - LoadDAE(DAEname=dae,OutputWorkspace=output,SpectrumMin="1") - if(mtd[output].isGroup()): - for k in mtd[output].getNames(): - mtd[k].setYUnit('Counts') + Load(str(runlist[0]),output) else: - mtd[output].setYUnit('Counts') + #dae="ndx"+mtd.settings['default.instrument'].lower() + dae="ndxoffspec" + LoadDAE(DAEname=dae,OutputWorkspace=output,SpectrumMin="1") + if(mtd[output].isGroup()): + for k in mtd[output].getNames(): + mtd[k].setYUnit('Counts') + else: + mtd[output].setYUnit('Counts') - if len(runlist) > 1: - for i in range(1,len(runlist)): - if runlist[i] != "0": + if len(runlist) > 1: + for i in range(1,len(runlist)): + if runlist[i] != "0": #nzeros=8-len(str(runlist[i])) #fpad="" #for j in range(nzeros): @@ -51,20 +51,20 @@ def addRuns(runlist,wname): #fname=fname.lower() ##fname=str.replace(fname,'.nxs','.raw') #Load(fname,"wtemp") - Load(str(runlist[i]),"wtemp") - else: + Load(str(runlist[i]),"wtemp") + else: #dae="ndx"+mtd.settings['default.instrument'].lower() - dae="ndxoffspec" - LoadDAE(DAEname=dae,OutputWorkspace="wtemp",SpectrumMin="1") - if(mtd['wtemp'].isGroup()): - for k in mtd['wtemp'].getNames(): - mtd[k].setYUnit('Counts') - else: - mtd[output].setYUnit('Counts') - Plus(output,"wtemp",output) - mtd.deleteWorkspace("wtemp") + dae="ndxoffspec" + LoadDAE(DAEname=dae,OutputWorkspace="wtemp",SpectrumMin="1") + if(mtd['wtemp'].isGroup()): + for k in mtd['wtemp'].getNames(): + mtd[k].setYUnit('Counts') + else: + mtd[output].setYUnit('Counts') + Plus(output,"wtemp",output) + mtd.deleteWorkspace("wtemp") - mtd.sendLogMessage("addRuns Completed") + mtd.sendLogMessage("addRuns Completed") ''' parse a text string of the format "1-6:2+8+9,10+11+12+13-19:3,20-24" @@ -132,15 +132,15 @@ def floodnorm(wkspName,floodfile): # # pixel by pixel efficiency correction for the linear detector # - floodloaded=0 - a1=mtd.getWorkspaceNames() - for i in range(len(a1)): - if a1[i] == "ld240flood": - floodloaded=1 - if floodloaded == 0: - LoadNexusProcessed(Filename=floodfile,OutputWorkspace="ld240flood") - - Divide(wkspName,"ld240flood",wkspName) + floodloaded=0 + a1=mtd.getWorkspaceNames() + for i in range(len(a1)): + if a1[i] == "ld240flood": + floodloaded=1 + if floodloaded == 0: + LoadNexusProcessed(Filename=floodfile,OutputWorkspace="ld240flood") + + Divide(wkspName,"ld240flood",wkspName) # # Plot a bunch of workspaces as 2D maps # using the supplied limits and log scale settings @@ -264,8 +264,8 @@ def removeoutlayer(wksp): for j in range(len(x)-1): y=a1.readY(i)[j] if (y<2): - a1.dataY(i)[j]=0.0; - a1.dataE(i)[j]=0.0; + a1.dataY(i)[j]=0.0 + a1.dataE(i)[j]=0.0 def nrSESANSFn(runList,nameList,P0runList,P0nameList,minSpec,maxSpec,upPeriod,downPeriod,existingP0,SEConstants,gparams,convertToSEL,lnPOverLam,diagnostics="0",removeoutlayer="0",floodfile="none",): nlist=parseNameList(nameList) diff --git a/Code/Mantid/scripts/SANS/ISISCommandInterface.py b/Code/Mantid/scripts/SANS/ISISCommandInterface.py index f3cd45cac67a..d7c2bbee8be0 100644 --- a/Code/Mantid/scripts/SANS/ISISCommandInterface.py +++ b/Code/Mantid/scripts/SANS/ISISCommandInterface.py @@ -452,9 +452,9 @@ def WavRangeReduction(wav_start=None, wav_end=None, full_trans_wav=None, name_su if merge_flag: retWSname_merged = retWSname_rear if retWSname_merged.count('rear') == 1: - retWSname_merged = retWSname_merged.replace('rear', 'merged') + retWSname_merged = retWSname_merged.replace('rear', 'merged') else: - retWSname_merged = retWSname_merged + "_merged" + retWSname_merged = retWSname_merged + "_merged" Nf = mtd[retWSname_front+"_sumOfNormFactors"] Nr = mtd[retWSname_rear+"_sumOfNormFactors"] @@ -574,26 +574,26 @@ def _fitRescaleAndShift(rAnds, frontData, rearData): if rAnds.qRangeUserSelected: Fit(InputWorkspace=rearData, Function='name=TabulatedFunction, Workspace="'+str(frontData)+'"' - +";name=FlatBackground", + +";name=FlatBackground", Ties='f0.Scaling='+str(rAnds.scale)+',f0.Shift=0.0', Output="__fitRescaleAndShift", StartX=rAnds.qMin, EndX=rAnds.qMax) else: Fit(InputWorkspace=rearData, Function='name=TabulatedFunction, Workspace="'+str(frontData)+'"' - +";name=FlatBackground", + +";name=FlatBackground", Ties='f0.Scaling='+str(rAnds.scale)+',f0.Shift=0.0', Output="__fitRescaleAndShift") elif rAnds.fitShift==False: if rAnds.qRangeUserSelected: Fit(InputWorkspace=rearData, Function='name=TabulatedFunction, Workspace="'+str(frontData)+'"' - +";name=FlatBackground", + +";name=FlatBackground", Ties='f1.A0='+str(rAnds.shift*rAnds.scale)+',f0.Shift=0.0', Output="__fitRescaleAndShift", StartX=rAnds.qMin, EndX=rAnds.qMax) else: Fit(InputWorkspace=rearData, Function='name=TabulatedFunction, Workspace="'+str(frontData)+'"' - +";name=FlatBackground", + +";name=FlatBackground", Ties='f1.A0='+str(rAnds.shift*rAnds.scale)+',f0.Shift=0.0', Output="__fitRescaleAndShift") else: diff --git a/Code/Mantid/scripts/SANS/SANSUtility.py b/Code/Mantid/scripts/SANS/SANSUtility.py index e66369da9fdc..48fb6cef0dd2 100644 --- a/Code/Mantid/scripts/SANS/SANSUtility.py +++ b/Code/Mantid/scripts/SANS/SANSUtility.py @@ -143,9 +143,9 @@ def spectrumBlock(base, ylow, xlow, ydim, xdim, det_dimension, orientation): max_row = base + (y+1)*det_dimension - 1 min_row = base + (y)*det_dimension for x in range(0,xdim): - std_i = start_spec + x + (y*det_dimension) - diff_s = std_i - min_row - output += str(max_row - diff_s) + ',' + std_i = start_spec + x + (y*det_dimension) + diff_s = std_i - min_row + output += str(max_row - diff_s) + ',' return output.rstrip(",") @@ -618,28 +618,28 @@ def ScaleByVolume(inputWS, scalefactor, geomid, width, height, thickness): @deprecated def StripEndZeroes(workspace, flag_value = 0.0): - result_ws = mtd[workspace] - y_vals = result_ws.readY(0) - length = len(y_vals) + result_ws = mtd[workspace] + y_vals = result_ws.readY(0) + length = len(y_vals) # Find the first non-zero value - start = 0 - for i in range(0, length): - if ( y_vals[i] != flag_value ): - start = i - break + start = 0 + for i in range(0, length): + if ( y_vals[i] != flag_value ): + start = i + break # Now find the last non-zero value - stop = 0 - length -= 1 - for j in range(length, 0,-1): - if ( y_vals[j] != flag_value ): - stop = j - break + stop = 0 + length -= 1 + for j in range(length, 0,-1): + if ( y_vals[j] != flag_value ): + stop = j + break # Find the appropriate X values and call CropWorkspace - x_vals = result_ws.readX(0) - startX = x_vals[start] + x_vals = result_ws.readX(0) + startX = x_vals[start] # Make sure we're inside the bin that we want to crop - endX = 1.001*x_vals[stop + 1] - CropWorkspace(InputWorkspace=workspace,OutputWorkspace=workspace,XMin=startX,XMax=endX) + endX = 1.001*x_vals[stop + 1] + CropWorkspace(InputWorkspace=workspace,OutputWorkspace=workspace,XMin=startX,XMax=endX) @deprecated class Orientation(object): diff --git a/Code/Mantid/scripts/SANS/SANSadd2.py b/Code/Mantid/scripts/SANS/SANSadd2.py index 910687eb533e..6f9fbb481586 100644 --- a/Code/Mantid/scripts/SANS/SANSadd2.py +++ b/Code/Mantid/scripts/SANS/SANSadd2.py @@ -7,54 +7,76 @@ _NO_INDIVIDUAL_PERIODS = -1 def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add','.RAW'), lowMem=False, binning='Monitors'): - if inst.upper() == "SANS2DTUBES": - inst = "SANS2D" + if inst.upper() == "SANS2DTUBES": + inst = "SANS2D" #check if there is at least one file in the list - if len(runs) < 1 : return + if len(runs) < 1 : return - if not defType.startswith('.') : defType = '.'+defType + if not defType.startswith('.') : defType = '.'+defType #these input arguments need to be arrays of strings, enforce this - if type(runs) == str : runs = (runs, ) - if type(rawTypes) == str : rawTypes = (rawTypes, ) + if type(runs) == str : runs = (runs, ) + if type(rawTypes) == str : rawTypes = (rawTypes, ) - if lowMem: - lowMem = _can_load_periods(runs, defType, rawTypes) - if lowMem: - period = 1 - else: - period = _NO_INDIVIDUAL_PERIODS + if lowMem: + lowMem = _can_load_periods(runs, defType, rawTypes) + if lowMem: + period = 1 + else: + period = _NO_INDIVIDUAL_PERIODS - userEntry = runs[0] + userEntry = runs[0] - while(True): + while(True): - isFirstDataSetEvent = False + isFirstDataSetEvent = False #we need to catch all exceptions to ensure that a dialog box is raised with the error - try : - lastPath, lastFile, logFile, num_periods, isFirstDataSetEvent = _loadWS( + try : + lastPath, lastFile, logFile, num_periods, isFirstDataSetEvent = _loadWS( userEntry, defType, inst, 'AddFilesSumTempory', rawTypes, period) # if event data prevent loop over periods makes no sense - if isFirstDataSetEvent: - period = _NO_INDIVIDUAL_PERIODS - - if inst.upper() != 'SANS2D' and isFirstDataSetEvent: - error = 'Adding event data not supported for ' + inst + ' for now' - print error - logger.notice(error) - for workspaceName in ('AddFilesSumTempory','AddFilesSumTempory_monitors'): - if workspaceName in mtd: - DeleteWorkspace(workspaceName) - return "" - - for i in range(len(runs)-1): - userEntry = runs[i+1] - lastPath, lastFile, logFile, dummy, isDataSetEvent = _loadWS( + if isFirstDataSetEvent: + period = _NO_INDIVIDUAL_PERIODS + + if inst.upper() != 'SANS2D' and isFirstDataSetEvent: + error = 'Adding event data not supported for ' + inst + ' for now' + print error + logger.notice(error) + for workspaceName in ('AddFilesSumTempory','AddFilesSumTempory_monitors'): + if workspaceName in mtd: + DeleteWorkspace(workspaceName) + return "" + + for i in range(len(runs)-1): + userEntry = runs[i+1] + lastPath, lastFile, logFile, dummy, isDataSetEvent = _loadWS( userEntry, defType, inst,'AddFilesNewTempory', rawTypes, period) - if isDataSetEvent != isFirstDataSetEvent: - error = 'Datasets added must be either ALL histogram data or ALL event data' + if isDataSetEvent != isFirstDataSetEvent: + error = 'Datasets added must be either ALL histogram data or ALL event data' + print error + logger.notice(error) + for workspaceName in ('AddFilesSumTempory','AddFilesNewTempory'): + if workspaceName in mtd: + DeleteWorkspace(workspaceName) + return "" + + Plus(LHSWorkspace='AddFilesSumTempory',RHSWorkspace= 'AddFilesNewTempory',OutputWorkspace= 'AddFilesSumTempory') + if isFirstDataSetEvent: + Plus(LHSWorkspace='AddFilesSumTempory_monitors',RHSWorkspace= 'AddFilesNewTempory_monitors',OutputWorkspace= 'AddFilesSumTempory_monitors') + DeleteWorkspace("AddFilesNewTempory") + if isFirstDataSetEvent: + DeleteWorkspace("AddFilesNewTempory_monitors") + + except ValueError as e: + error = 'Error opening file ' + userEntry+': ' + str(e) + print error + logger.notice(error) + if 'AddFilesSumTempory' in mtd : DeleteWorkspace('AddFilesSumTempory') + return "" + except Exception as e: + error = 'Error finding files: ' + str(e) print error logger.notice(error) for workspaceName in ('AddFilesSumTempory','AddFilesNewTempory'): @@ -62,221 +84,199 @@ def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add' DeleteWorkspace(workspaceName) return "" - Plus(LHSWorkspace='AddFilesSumTempory',RHSWorkspace= 'AddFilesNewTempory',OutputWorkspace= 'AddFilesSumTempory') - if isFirstDataSetEvent: - Plus(LHSWorkspace='AddFilesSumTempory_monitors',RHSWorkspace= 'AddFilesNewTempory_monitors',OutputWorkspace= 'AddFilesSumTempory_monitors') - DeleteWorkspace("AddFilesNewTempory") - if isFirstDataSetEvent: - DeleteWorkspace("AddFilesNewTempory_monitors") - - except ValueError as e: - error = 'Error opening file ' + userEntry+': ' + str(e) - print error - logger.notice(error) - if 'AddFilesSumTempory' in mtd : DeleteWorkspace('AddFilesSumTempory') - return "" - except Exception as e: - error = 'Error finding files: ' + str(e) - print error - logger.notice(error) - for workspaceName in ('AddFilesSumTempory','AddFilesNewTempory'): - if workspaceName in mtd: - DeleteWorkspace(workspaceName) - return "" - # in case of event file force it into a histogram workspace - if isFirstDataSetEvent: - wsInMonitor = mtd['AddFilesSumTempory_monitors'] - if binning == 'Monitors': - monX = wsInMonitor.dataX(0) - binning = str(monX[0]) - binGap = monX[1] - monX[0] - binning = binning + "," + str(binGap) - for j in range(2,len(monX)): - nextBinGap = monX[j] - monX[j-1] - if nextBinGap != binGap: - binGap = nextBinGap - binning = binning + "," + str(monX[j-1]) + "," + str(binGap) - binning = binning + "," + str(monX[len(monX)-1]) - - logger.notice(binning) - Rebin(InputWorkspace='AddFilesSumTempory',OutputWorkspace='AddFilesSumTempory_Rebin',Params= binning, PreserveEvents=False) + if isFirstDataSetEvent: + wsInMonitor = mtd['AddFilesSumTempory_monitors'] + if binning == 'Monitors': + monX = wsInMonitor.dataX(0) + binning = str(monX[0]) + binGap = monX[1] - monX[0] + binning = binning + "," + str(binGap) + for j in range(2,len(monX)): + nextBinGap = monX[j] - monX[j-1] + if nextBinGap != binGap: + binGap = nextBinGap + binning = binning + "," + str(monX[j-1]) + "," + str(binGap) + binning = binning + "," + str(monX[len(monX)-1]) + + logger.notice(binning) + Rebin(InputWorkspace='AddFilesSumTempory',OutputWorkspace='AddFilesSumTempory_Rebin',Params= binning, PreserveEvents=False) # loading the nexus file using LoadNexus is necessary because it has some metadata # that is not in LoadEventNexus. This must be fixed. - filename, ext = _makeFilename(runs[0], defType, inst) - LoadNexus(Filename=filename, OutputWorkspace='AddFilesSumTempory', SpectrumMax=wsInMonitor.getNumberHistograms()) + filename, ext = _makeFilename(runs[0], defType, inst) + LoadNexus(Filename=filename, OutputWorkspace='AddFilesSumTempory', SpectrumMax=wsInMonitor.getNumberHistograms()) # User may have selected a binning which is different from the default - Rebin(InputWorkspace='AddFilesSumTempory',OutputWorkspace='AddFilesSumTempory',Params= binning) + Rebin(InputWorkspace='AddFilesSumTempory',OutputWorkspace='AddFilesSumTempory',Params= binning) # For now the monitor binning must be the same as the detector binning # since otherwise both cannot exist in the same output histogram file - Rebin(InputWorkspace='AddFilesSumTempory_monitors',OutputWorkspace='AddFilesSumTempory_monitors',Params= binning) + Rebin(InputWorkspace='AddFilesSumTempory_monitors',OutputWorkspace='AddFilesSumTempory_monitors',Params= binning) - wsInMonitor = mtd['AddFilesSumTempory_monitors'] - wsOut = mtd['AddFilesSumTempory'] - wsInDetector = mtd['AddFilesSumTempory_Rebin'] + wsInMonitor = mtd['AddFilesSumTempory_monitors'] + wsOut = mtd['AddFilesSumTempory'] + wsInDetector = mtd['AddFilesSumTempory_Rebin'] - mon_n = wsInMonitor.getNumberHistograms() - for i in range(mon_n): - wsOut.setY(i,wsInMonitor.dataY(i)) - wsOut.setE(i,wsInMonitor.dataE(i)) - ConjoinWorkspaces(wsOut, wsInDetector, CheckOverlapping=True) + mon_n = wsInMonitor.getNumberHistograms() + for i in range(mon_n): + wsOut.setY(i,wsInMonitor.dataY(i)) + wsOut.setE(i,wsInMonitor.dataE(i)) + ConjoinWorkspaces(wsOut, wsInDetector, CheckOverlapping=True) - if 'AddFilesSumTempory_Rebin' in mtd : DeleteWorkspace('AddFilesSumTempory_Rebin') + if 'AddFilesSumTempory_Rebin' in mtd : DeleteWorkspace('AddFilesSumTempory_Rebin') - lastFile = os.path.splitext(lastFile)[0] + lastFile = os.path.splitext(lastFile)[0] # now save the added file - outFile = lastFile+'-add.'+'nxs' - logger.notice('writing file: '+outFile) - if period == 1 or period == _NO_INDIVIDUAL_PERIODS: + outFile = lastFile+'-add.'+'nxs' + logger.notice('writing file: '+outFile) + if period == 1 or period == _NO_INDIVIDUAL_PERIODS: #replace the file the first time around - SaveNexusProcessed(InputWorkspace="AddFilesSumTempory", + SaveNexusProcessed(InputWorkspace="AddFilesSumTempory", Filename=outFile, Append=False) - else: + else: #then append - SaveNexusProcessed("AddFilesSumTempory", outFile, Append=True) + SaveNexusProcessed("AddFilesSumTempory", outFile, Append=True) - DeleteWorkspace("AddFilesSumTempory") - if isFirstDataSetEvent: + DeleteWorkspace("AddFilesSumTempory") + if isFirstDataSetEvent: DeleteWorkspace("AddFilesSumTempory_monitors") - if period == num_periods: - break + if period == num_periods: + break - if period == _NO_INDIVIDUAL_PERIODS: - break - else: - period += 1 + if period == _NO_INDIVIDUAL_PERIODS: + break + else: + period += 1 #this adds the path to the filename - path,base = os.path.split(outFile) - if path == '' or base not in os.listdir(path): - path = config['defaultsave.directory'] + path - assert(base in os.listdir(path)) - pathout = path - if logFile: - _copyLog(lastPath, logFile, pathout) + path,base = os.path.split(outFile) + if path == '' or base not in os.listdir(path): + path = config['defaultsave.directory'] + path + assert(base in os.listdir(path)) + pathout = path + if logFile: + _copyLog(lastPath, logFile, pathout) - return 'The following file has been created:\n'+outFile + return 'The following file has been created:\n'+outFile def _can_load_periods(runs, defType, rawTypes): - """ + """ Searches through the supplied list of run file names and returns False if some appear to be raw files else True """ - for i in runs: - dummy, ext = os.path.splitext(i) - if ext == '': ext = defType - if _isType(ext, rawTypes): - return False + for i in runs: + dummy, ext = os.path.splitext(i) + if ext == '': ext = defType + if _isType(ext, rawTypes): + return False #no raw files were found, assume we can specify the period number for each - return True + return True def _makeFilename(entry, ext, inst) : - """ + """ If entry not already a valid filename make it into one """ - try : - runNum = int(entry) #the user entered something that translates to a run number, convert it to a file - filename=inst+_padZero(runNum, inst)+ext - except ValueError : #we don't have a run number, assume it's a valid filename - filename = entry - dummy, ext = os.path.splitext(filename) + try : + runNum = int(entry) #the user entered something that translates to a run number, convert it to a file + filename=inst+_padZero(runNum, inst)+ext + except ValueError : #we don't have a run number, assume it's a valid filename + filename = entry + dummy, ext = os.path.splitext(filename) - return filename, ext + return filename, ext def _loadWS(entry, ext, inst, wsName, rawTypes, period=_NO_INDIVIDUAL_PERIODS) : - filename, ext = _makeFilename(entry, ext, inst) + filename, ext = _makeFilename(entry, ext, inst) - logger.notice('reading file: '+filename) + logger.notice('reading file: '+filename) - if period != _NO_INDIVIDUAL_PERIODS: + if period != _NO_INDIVIDUAL_PERIODS: #load just a single period - outWs = Load(Filename=filename, OutputWorkspace=wsName, EntryNumber=period) - else: - outWs = Load(Filename=filename,OutputWorkspace=wsName) + outWs = Load(Filename=filename, OutputWorkspace=wsName, EntryNumber=period) + else: + outWs = Load(Filename=filename,OutputWorkspace=wsName) - props = outWs.getHistory().lastAlgorithm() + props = outWs.getHistory().lastAlgorithm() - isDataSetEvent = False - wsDataSet = mtd[wsName] - if hasattr(wsDataSet, 'getNumberEvents'): - isDataSetEvent = True + isDataSetEvent = False + wsDataSet = mtd[wsName] + if hasattr(wsDataSet, 'getNumberEvents'): + isDataSetEvent = True - if isDataSetEvent: - LoadEventNexus(Filename=filename,OutputWorkspace=wsName, LoadMonitors=True) - runDetails = mtd[wsName].getRun() - timeArray = runDetails.getLogData("proton_charge").times + if isDataSetEvent: + LoadEventNexus(Filename=filename,OutputWorkspace=wsName, LoadMonitors=True) + runDetails = mtd[wsName].getRun() + timeArray = runDetails.getLogData("proton_charge").times # There should never be a time increment in the proton charge larger than say "two weeks" # SANS2D currently is run at 10 frames per second. This may be increated to 5Hz # (step of 0.2 sec). Although time between frames may be larger due to having the SMP veto switched on, # but hopefully not longer than two weeks! - for i in range(len(timeArray)-1): + for i in range(len(timeArray)-1): # cal time dif in seconds - timeDif = (timeArray[i+1].total_nanoseconds()-timeArray[i].total_nanoseconds())*1e-9 - if timeDif > 172800: - sanslog.warning('Time increments in the proton charge log of ' + filename + ' are suspicious large.' + + timeDif = (timeArray[i+1].total_nanoseconds()-timeArray[i].total_nanoseconds())*1e-9 + if timeDif > 172800: + sanslog.warning('Time increments in the proton charge log of ' + filename + ' are suspicious large.' + ' For example a time difference of ' + str(timeDif) + " seconds has been observed.") - break + break - path = props.getPropertyValue('FileName') - path, fName = os.path.split(path) - if path.find('/') == -1: + path = props.getPropertyValue('FileName') + path, fName = os.path.split(path) + if path.find('/') == -1: #looks like we're on a windows system, convert the directory separators - path = path.replace('\\', '/') + path = path.replace('\\', '/') - if _isType(ext, rawTypes): - LoadSampleDetailsFromRaw(InputWorkspace=wsName,Filename= path+'/'+fName) + if _isType(ext, rawTypes): + LoadSampleDetailsFromRaw(InputWorkspace=wsName,Filename= path+'/'+fName) - logFile = None + logFile = None #change below when logs in Nexus files work file types of .raw need their log files to be copied too - if True:#_isType(ext, rawTypes): - logFile = os.path.splitext(fName)[0]+'.log' + if True:#_isType(ext, rawTypes): + logFile = os.path.splitext(fName)[0]+'.log' - try: - samp = mtd[wsName].getRun() - numPeriods = samp.getLogData('nperiods').value - except: + try: + samp = mtd[wsName].getRun() + numPeriods = samp.getLogData('nperiods').value + except: #assume the run file didn't support multi-period data and so there is only one period - numPeriods = 1 + numPeriods = 1 - return path, fName, logFile, numPeriods, isDataSetEvent + return path, fName, logFile, numPeriods, isDataSetEvent def _padZero(runNum, inst): - numDigits = config.getInstrument(inst).zeroPadding(0) - run = str(runNum).zfill(numDigits) - return run + numDigits = config.getInstrument(inst).zeroPadding(0) + run = str(runNum).zfill(numDigits) + return run ########################################## # returns true if ext is in the tuple allTypes, ext # is intended to be a file extension and allTypes a # list of allowed extensions. '*' at the end is supported def _isType(ext, allTypes): - for oneType in allTypes: - oneType = str(oneType) - if oneType.endswith('*') : - oneType = oneType[0:len(oneType)-1] - if ext.startswith(oneType) : - return True - else : - if ext == oneType : - return True - return False + for oneType in allTypes: + oneType = str(oneType) + if oneType.endswith('*') : + oneType = oneType[0:len(oneType)-1] + if ext.startswith(oneType) : + return True + else : + if ext == oneType : + return True + return False def _copyLog(lastPath, logFile, pathout): - try : - logFile = os.path.join(lastPath, logFile) - if os.path.exists(logFile): - copyfile(logFile, os.path.join(pathout, os.path.basename(logFile))) - else: - logger.notice("Could not find log file %s" % logFile) - except Exception, reason: - error = 'Error copying log file ' + logFile + ' to directory ' + pathout+'\n' - print error - logger.notice(error) + try : + logFile = os.path.join(lastPath, logFile) + if os.path.exists(logFile): + copyfile(logFile, os.path.join(pathout, os.path.basename(logFile))) + else: + logger.notice("Could not find log file %s" % logFile) + except Exception, reason: + error = 'Error copying log file ' + logFile + ' to directory ' + pathout+'\n' + print error + logger.notice(error) if __name__ == '__main__': diff --git a/Code/Mantid/scripts/SANS/isis_reducer.py b/Code/Mantid/scripts/SANS/isis_reducer.py index a5c5389ab84f..b81d902301fe 100644 --- a/Code/Mantid/scripts/SANS/isis_reducer.py +++ b/Code/Mantid/scripts/SANS/isis_reducer.py @@ -313,7 +313,7 @@ def get_out_ws_name(self, show_period=True): name += '_' + self.to_Q.output_type name += '_' + self.to_wavelen.get_range() if self.to_Q.get_output_type() == "1D": - name += self.mask.get_phi_limits_tag() + name += self.mask.get_phi_limits_tag() if self.getNumSlices() > 0: limits = self.getCurrSliceLimit() @@ -421,7 +421,7 @@ def run_from_raw(self): return self._reduce(init=False, post=True) def set_Q_output_type(self, out_type): - self.to_Q.set_output_type(out_type) + self.to_Q.set_output_type(out_type) def pre_process(self): """ @@ -566,9 +566,9 @@ def set_beam_finder(self, finder, det_bank='rear'): """ if issubclass(finder.__class__, isis_reduction_steps.BaseBeamFinder) or finder is None: if det_bank == 'front': - self._front_beam_finder = finder + self._front_beam_finder = finder else: - self._beam_finder = finder + self._beam_finder = finder else: raise RuntimeError, "Reducer.set_beam_finder expects an object of class ReductionStep" diff --git a/Code/Mantid/scripts/SANS/isis_reduction_steps.py b/Code/Mantid/scripts/SANS/isis_reduction_steps.py index 13ec11a10297..c56ae0991fe4 100644 --- a/Code/Mantid/scripts/SANS/isis_reduction_steps.py +++ b/Code/Mantid/scripts/SANS/isis_reduction_steps.py @@ -717,7 +717,7 @@ def parse_instruction(self, instName, details): else: _issueWarning('Unrecognized masking line "' + details + '"') else: - _issueWarning('Unrecognized masking line "' + details + '"') + _issueWarning('Unrecognized masking line "' + details + '"') def add_mask_string(self, mask_string, detect): if detect.upper() == 'FRONT' or detect.upper() == 'HAB': @@ -858,9 +858,9 @@ def get_phi_limits_tag(self): @return 'Phi'low'_'high if it has been set """ if self.mask_phi and self._lim_phi_xml != '' and (abs(self.phi_max - self.phi_min) != 180.0): - return 'Phi'+str(self.phi_min)+'_'+str(self.phi_max) + return 'Phi'+str(self.phi_min)+'_'+str(self.phi_max) else: - return '' + return '' def set_phi_limit(self, phimin, phimax, phimirror, override=True): ''' @@ -1695,7 +1695,7 @@ def set_gravity(self, flag, override=True): self._grav_set = True if (not self._grav_set) or override: - self._use_gravity = bool(flag) + self._use_gravity = bool(flag) else: msg = "User file can't override previous gravity setting, do gravity correction remains " + str(self._use_gravity) print msg @@ -1992,26 +1992,26 @@ def read_line(self, line, reducer): # SET CENTRE/HAB X Y main_str_pos = upper_line.find('MAIN') hab_str_pos = upper_line.find('HAB') - x_pos = 0.0; - y_pos = 0.0; + x_pos = 0.0 + y_pos = 0.0 if (main_str_pos > 0): - values = upper_line[main_str_pos+5:].split() #remov the SET CENTRE/MAIN - x_pos = float(values[0])/1000.0 - y_pos = float(values[1])/1000.0 + values = upper_line[main_str_pos+5:].split() #remov the SET CENTRE/MAIN + x_pos = float(values[0])/1000.0 + y_pos = float(values[1])/1000.0 elif (hab_str_pos > 0): - values = upper_line[hab_str_pos+4:].split() # remove the SET CENTRE/HAB - print ' convert values ',values - x_pos = float(values[0])/1000.0 - y_pos = float(values[1])/1000.0 + values = upper_line[hab_str_pos+4:].split() # remove the SET CENTRE/HAB + print ' convert values ',values + x_pos = float(values[0])/1000.0 + y_pos = float(values[1])/1000.0 else: - values = upper_line.split() - x_pos = float(values[2])/1000.0 - y_pos = float(values[3])/1000.0 + values = upper_line.split() + x_pos = float(values[2])/1000.0 + y_pos = float(values[3])/1000.0 if (hab_str_pos > 0): - print 'Front values = ',x_pos,y_pos - reducer.set_beam_finder(BaseBeamFinder(x_pos, y_pos),'front') + print 'Front values = ',x_pos,y_pos + reducer.set_beam_finder(BaseBeamFinder(x_pos, y_pos),'front') else: - reducer.set_beam_finder(BaseBeamFinder(x_pos, y_pos)) + reducer.set_beam_finder(BaseBeamFinder(x_pos, y_pos)) elif upper_line.startswith('SET SCALES'): values = upper_line.split() @@ -2077,9 +2077,9 @@ def read_line(self, line, reducer): reducer.transmission_calculator.loq_removePromptPeakMax = float(params[2]) else: if reducer.instrument.name() == 'LOQ': - _issueWarning('Incorrectly formatted FIT/MONITOR line, %s, line ignored' % upper_line) + _issueWarning('Incorrectly formatted FIT/MONITOR line, %s, line ignored' % upper_line) else: - _issueWarning('FIT/MONITOR line specific to LOQ instrument. Line ignored') + _issueWarning('FIT/MONITOR line specific to LOQ instrument. Line ignored') elif upper_line == 'SANS2D' or upper_line == 'LOQ': self._check_instrument(upper_line, reducer) @@ -2532,9 +2532,9 @@ def _read_calibfile_line(self, arguments, reducer): path2file = parts[1] try: - file_path, suggested_name = getFileAndName(path2file) - __calibrationWs = Load(file_path, OutputWorkspace=suggested_name) - reducer.instrument.setCalibrationWorkspace(__calibrationWs) + file_path, suggested_name = getFileAndName(path2file) + __calibrationWs = Load(file_path, OutputWorkspace=suggested_name) + reducer.instrument.setCalibrationWorkspace(__calibrationWs) except: # If we throw a runtime here, then we cannot execute 'Load Data'. raise RuntimeError("Invalid input for tube calibration file (" + path2file + " ).\n" \ diff --git a/Code/Mantid/scripts/SCD_Reduction/ReduceDictionary.py b/Code/Mantid/scripts/SCD_Reduction/ReduceDictionary.py index 63749321d7d5..1997b44f22ec 100644 --- a/Code/Mantid/scripts/SCD_Reduction/ReduceDictionary.py +++ b/Code/Mantid/scripts/SCD_Reduction/ReduceDictionary.py @@ -14,44 +14,44 @@ # def LoadDictionary( *filenames, **kwargs ): # create a dictionary to load into - params_dictionary = kwargs.get("existing", {}) + params_dictionary = kwargs.get("existing", {}) # create a list of run numbers - run_nums = params_dictionary.get("run_nums", []) + run_nums = params_dictionary.get("run_nums", []) - file = open(filenames[0]) - for line in file: - line = line.strip(); - line = line.rstrip(); - if (not line.startswith('#')) and len(line) > 2: - words = line.split() + file = open(filenames[0]) + for line in file: + line = line.strip() + line = line.rstrip() + if (not line.startswith('#')) and len(line) > 2: + words = line.split() # error check the number of values - if len(words) < 2: - print "Syntax Error On Line: " + line + if len(words) < 2: + print "Syntax Error On Line: " + line # set the value - else: - (key, value) = words[0:2] + else: + (key, value) = words[0:2] # fix up special values - if value.lower() == "none": - value = None - elif value.lower() == "true": - value = True - elif value.lower() == "false": - value = False + if value.lower() == "none": + value = None + elif value.lower() == "true": + value = True + elif value.lower() == "false": + value = False # set the values - if key == "run_nums": - run_nums.extend(ParseRunList(value)) - else: - params_dictionary[key] = value + if key == "run_nums": + run_nums.extend(ParseRunList(value)) + else: + params_dictionary[key] = value - params_dictionary["run_nums"]=run_nums + params_dictionary["run_nums"]=run_nums # it isn't awesome without recursion - if len(filenames) > 1: - return LoadDictionary(*filenames[1:], existing=params_dictionary) - else: - return params_dictionary; + if len(filenames) > 1: + return LoadDictionary(*filenames[1:], existing=params_dictionary) + else: + return params_dictionary # # Return a list of run numbers from a string containing a comma separated @@ -59,17 +59,17 @@ def LoadDictionary( *filenames, **kwargs ): # with a colon separator. # def ParseRunList( run_string ): - run_list = [] - groups = run_string.split(",") - for group in groups: - runs = group.split(":") - if len(runs) == 1: - run_list.append( runs[0] ) - else: - first = int(runs[0]) - last = int(runs[1]) - for run in range(first, last+1): - run_list.append(str(run)) + run_list = [] + groups = run_string.split(",") + for group in groups: + runs = group.split(":") + if len(runs) == 1: + run_list.append( runs[0] ) + else: + first = int(runs[0]) + last = int(runs[1]) + for run in range(first, last+1): + run_list.append(str(run)) - return run_list + return run_list diff --git a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py index 68db7ee58d43..4ba4a06d53fb 100644 --- a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py +++ b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py @@ -54,8 +54,8 @@ # Get the config file name and the run number to process from the command line # if (len(sys.argv) < 3): - print "You MUST give the config file name(s) and run number on the command line" - exit(0) + print "You MUST give the config file name(s) and run number on the command line" + exit(0) config_files = sys.argv[1:-1] run = sys.argv[-1] @@ -125,18 +125,18 @@ # short_filename = "%s_%s_event.nxs" % (instrument_name, str(run)) if data_directory is not None: - full_name = data_directory + "/" + short_filename + full_name = data_directory + "/" + short_filename else: - candidates = FileFinder.findRuns(short_filename) - full_name = "" - for item in candidates: - if os.path.exists(item): - full_name = str(item) - - if not full_name.endswith('nxs'): - print "Exiting since the data_directory was not specified and" - print "findnexus failed for event NeXus file: " + instrument_name + " " + str(run) - exit(0) + candidates = FileFinder.findRuns(short_filename) + full_name = "" + for item in candidates: + if os.path.exists(item): + full_name = str(item) + + if not full_name.endswith('nxs'): + print "Exiting since the data_directory was not specified and" + print "findnexus failed for event NeXus file: " + instrument_name + " " + str(run) + exit(0) print "\nProcessing File: " + full_name + " ......\n" @@ -157,11 +157,11 @@ # can not be None. TOPAZ has one calibration file, but SNAP may have two. # if (calibration_file_1 is not None ) or (calibration_file_2 is not None): - if (calibration_file_1 is None ): - calibration_file_1 = "" - if (calibration_file_2 is None ): - calibration_file_2 = "" - LoadIsawDetCal( event_ws, + if (calibration_file_1 is None ): + calibration_file_1 = "" + if (calibration_file_2 is None ): + calibration_file_2 = "" + LoadIsawDetCal( event_ws, Filename=calibration_file_1, Filename2=calibration_file_2 ) monitor_ws = LoadNexusMonitors( Filename=full_name ) @@ -196,19 +196,19 @@ # Read or find UB for the run if read_UB: # Read orientation matrix from file - LoadIsawUB(InputWorkspace=peaks_ws, Filename=UB_filename) - if optimize_UB: + LoadIsawUB(InputWorkspace=peaks_ws, Filename=UB_filename) + if optimize_UB: # Optimize the specifiec UB for better peak prediction - uc_a = peaks_ws.sample().getOrientedLattice().a() - uc_b = peaks_ws.sample().getOrientedLattice().b() - uc_c = peaks_ws.sample().getOrientedLattice().c() - uc_alpha = peaks_ws.sample().getOrientedLattice().alpha() - uc_beta = peaks_ws.sample().getOrientedLattice().beta() - uc_gamma = peaks_ws.sample().getOrientedLattice().gamma() - FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance) + uc_a = peaks_ws.sample().getOrientedLattice().a() + uc_b = peaks_ws.sample().getOrientedLattice().b() + uc_c = peaks_ws.sample().getOrientedLattice().c() + uc_alpha = peaks_ws.sample().getOrientedLattice().alpha() + uc_beta = peaks_ws.sample().getOrientedLattice().beta() + uc_gamma = peaks_ws.sample().getOrientedLattice().gamma() + FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance) else: # Find a Niggli UB matrix that indexes the peaks in this run - FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance ) + FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance ) IndexPeaks( PeaksWorkspace=peaks_ws, Tolerance=tolerance) @@ -227,27 +227,27 @@ # PeakIntegration algorithm. # if integrate_predicted_peaks: - print "PREDICTING peaks to integrate...." - peaks_ws = PredictPeaks( InputWorkspace=peaks_ws, + print "PREDICTING peaks to integrate...." + peaks_ws = PredictPeaks( InputWorkspace=peaks_ws, WavelengthMin=min_pred_wl, WavelengthMax=max_pred_wl, MinDSpacing=min_pred_dspacing, MaxDSpacing=max_pred_dspacing, ReflectionCondition='Primitive' ) else: - print "Only integrating FOUND peaks ...." + print "Only integrating FOUND peaks ...." # # Set the monitor counts for all the peaks that will be integrated # num_peaks = peaks_ws.getNumberPeaks() for i in range(num_peaks): - peak = peaks_ws.getPeak(i) - if use_monitor_counts: - peak.setMonitorCount( monitor_count ) - else: - peak.setMonitorCount( proton_charge ) + peak = peaks_ws.getPeak(i) + if use_monitor_counts: + peak.setMonitorCount( monitor_count ) + else: + peak.setMonitorCount( proton_charge ) if use_monitor_counts: - print '\n*** Beam monitor counts used for scaling.' + print '\n*** Beam monitor counts used for scaling.' else: - print '\n*** Proton charge x 1000 used for scaling.\n' + print '\n*** Proton charge x 1000 used for scaling.\n' if use_sphere_integration: # @@ -256,12 +256,12 @@ # workspace to do raw integration (we don't need high resolution or # LorentzCorrection to do the raw sphere integration ) # - MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D", + MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D", dEAnalysisMode="Elastic", QConversionScales="Q in A^-1", LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals, SplitInto='2', SplitThreshold='500',MaxRecursionDepth='10' ) - peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=peak_radius, + peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=peak_radius, CoordinatesToUse="Q (sample frame)", BackgroundOuterRadius=bkg_outer_radius, BackgroundInnerRadius=bkg_inner_radius, @@ -274,12 +274,12 @@ # workspace to do raw integration (we don't need high resolution or # LorentzCorrection to do the raw sphere integration ) # - MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D", + MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D", dEAnalysisMode="Elastic", QConversionScales="Q in A^-1", LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals, SplitInto='2', SplitThreshold='500',MaxRecursionDepth='10' ) - peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=peak_radius, + peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=peak_radius, CoordinatesToUse="Q (sample frame)", BackgroundOuterRadius=bkg_outer_radius, BackgroundInnerRadius=bkg_inner_radius, @@ -291,15 +291,15 @@ ProfileFunction=cylinder_profile_fit) elif use_fit_peaks_integration: - event_ws = Rebin( InputWorkspace=event_ws, + event_ws = Rebin( InputWorkspace=event_ws, Params=rebin_params, PreserveEvents=preserve_events ) - peaks_ws = PeakIntegration( InPeaksWorkspace=peaks_ws, InputWorkspace=event_ws, + peaks_ws = PeakIntegration( InPeaksWorkspace=peaks_ws, InputWorkspace=event_ws, IkedaCarpenterTOF=use_ikeda_carpenter, MatchingRunNo=True, NBadEdgePixels=n_bad_edge_pixels ) elif use_ellipse_integration: - peaks_ws= IntegrateEllipsoids( InputWorkspace=event_ws, PeaksWorkspace = peaks_ws, + peaks_ws= IntegrateEllipsoids( InputWorkspace=event_ws, PeaksWorkspace = peaks_ws, RegionRadius = ellipse_region_radius, SpecifySize = ellipse_size_specified, PeakSize = peak_radius, @@ -307,13 +307,13 @@ BackgroundInnerSize = bkg_inner_radius ) elif use_cylindrical_integration: - profiles_filename = output_directory + "/" + instrument_name + '_' + run + '.profiles' - MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D", + profiles_filename = output_directory + "/" + instrument_name + '_' + run + '.profiles' + MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D", dEAnalysisMode="Elastic", QConversionScales="Q in A^-1", LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals, SplitInto='2', SplitThreshold='500',MaxRecursionDepth='10' ) - peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=cylinder_radius, + peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=cylinder_radius, CoordinatesToUse="Q (sample frame)", Cylinder='1', CylinderLength = cylinder_length, PercentBackground = '20', ProfileFunction = 'NoFit', @@ -331,25 +331,25 @@ # Print warning if user is trying to integrate using the cylindrical method and transorm the cell if use_cylindrical_integration: - if (not cell_type is None) or (not centering is None): - print "WARNING: Cylindrical profiles are NOT transformed!!!" + if (not cell_type is None) or (not centering is None): + print "WARNING: Cylindrical profiles are NOT transformed!!!" # # If requested, also switch to the specified conventional cell and save the # corresponding matrix and integrate file # else: - if (not cell_type is None) and (not centering is None) : - run_conventional_matrix_file = output_directory + "/" + run + "_" + \ + if (not cell_type is None) and (not centering is None) : + run_conventional_matrix_file = output_directory + "/" + run + "_" + \ cell_type + "_" + centering + ".mat" - run_conventional_integrate_file = output_directory + "/" + run + "_" + \ + run_conventional_integrate_file = output_directory + "/" + run + "_" + \ cell_type + "_" + centering + ".integrate" - SelectCellOfType( PeaksWorkspace=peaks_ws, + SelectCellOfType( PeaksWorkspace=peaks_ws, CellType=cell_type, Centering=centering, AllowPermutations=allow_perm, Apply=True, Tolerance=tolerance ) - SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, + SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=run_conventional_integrate_file ) - SaveIsawUB( InputWorkspace=peaks_ws, Filename=run_conventional_matrix_file ) + SaveIsawUB( InputWorkspace=peaks_ws, Filename=run_conventional_matrix_file ) end_time = time.time() print '\nReduced run ' + str(run) + ' in ' + str(end_time - start_time) + ' sec' diff --git a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py index 94f90ff2aede..c9526a94b1e5 100644 --- a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py +++ b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py @@ -54,14 +54,14 @@ # a thread that starts a command line process to reduce one run. # class ProcessThread ( threading.Thread ): - command = "" + command = "" - def setCommand( self, command="" ): - self.command = command + def setCommand( self, command="" ): + self.command = command - def run ( self ): - print 'STARTING PROCESS: ' + self.command - os.system( self.command ) + def run ( self ): + print 'STARTING PROCESS: ' + self.command + os.system( self.command ) # ------------------------------------------------------------------------- @@ -69,8 +69,8 @@ def run ( self ): # Get the config file name from the command line # if (len(sys.argv) < 2): - print "You MUST give the config file name on the command line" - exit(0) + print "You MUST give the config file name on the command line" + exit(0) config_files = sys.argv[1:] @@ -105,7 +105,7 @@ def run ( self ): # determine what python executable to launch new jobs with python = sys.executable if python is None: # not all platforms define this variable - python = 'python' + python = 'python' # # Make the list of separate process commands. If a slurm queue name @@ -115,14 +115,14 @@ def run ( self ): list=[] index = 0 for r_num in run_nums: - list.append( ProcessThread() ) - cmd = '%s %s %s %s' % (python, reduce_one_run_script, " ".join(config_files), str(r_num)) - if slurm_queue_name is not None: - console_file = output_directory + "/" + str(r_num) + "_output.txt" - cmd = 'srun -p ' + slurm_queue_name + \ + list.append( ProcessThread() ) + cmd = '%s %s %s %s' % (python, reduce_one_run_script, " ".join(config_files), str(r_num)) + if slurm_queue_name is not None: + console_file = output_directory + "/" + str(r_num) + "_output.txt" + cmd = 'srun -p ' + slurm_queue_name + \ ' --cpus-per-task=3 -J ReduceSCD_Parallel.py -o ' + console_file + ' ' + cmd - list[index].setCommand( cmd ) - index = index + 1 + list[index].setCommand( cmd ) + index = index + 1 # # Now create and start a thread for each command to run the commands in parallel, @@ -131,17 +131,17 @@ def run ( self ): all_done = False active_list=[] while not all_done: - if ( len(list) > 0 and len(active_list) < max_processes ): - thread = list[0] - list.remove(thread) - active_list.append( thread ) - thread.start() - time.sleep(2) - for thread in active_list: - if not thread.isAlive(): - active_list.remove( thread ) - if len(list) == 0 and len(active_list) == 0 : - all_done = True + if ( len(list) > 0 and len(active_list) < max_processes ): + thread = list[0] + list.remove(thread) + active_list.append( thread ) + thread.start() + time.sleep(2) + for thread in active_list: + if not thread.isAlive(): + active_list.remove( thread ) + if len(list) == 0 and len(active_list) == 0 : + all_done = True print "\n**************************************************************************************" print "************** Completed Individual Runs, Starting to Combine Results ****************" @@ -157,104 +157,104 @@ def run ( self ): first_time = True if not use_cylindrical_integration: - for r_num in run_nums: - one_run_file = output_directory + '/' + str(r_num) + '_Niggli.integrate' - peaks_ws = LoadIsawPeaks( Filename=one_run_file ) - if first_time: - if UseFirstLattice and not read_UB: + for r_num in run_nums: + one_run_file = output_directory + '/' + str(r_num) + '_Niggli.integrate' + peaks_ws = LoadIsawPeaks( Filename=one_run_file ) + if first_time: + if UseFirstLattice and not read_UB: # Find a UB (using FFT) for the first run to use in the FindUBUsingLatticeParameters - FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance ) - uc_a = peaks_ws.sample().getOrientedLattice().a() - uc_b = peaks_ws.sample().getOrientedLattice().b() - uc_c = peaks_ws.sample().getOrientedLattice().c() - uc_alpha = peaks_ws.sample().getOrientedLattice().alpha() - uc_beta = peaks_ws.sample().getOrientedLattice().beta() - uc_gamma = peaks_ws.sample().getOrientedLattice().gamma() - SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=niggli_integrate_file ) - - first_time = False - else: - SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=True, Filename=niggli_integrate_file ) + FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance ) + uc_a = peaks_ws.sample().getOrientedLattice().a() + uc_b = peaks_ws.sample().getOrientedLattice().b() + uc_c = peaks_ws.sample().getOrientedLattice().c() + uc_alpha = peaks_ws.sample().getOrientedLattice().alpha() + uc_beta = peaks_ws.sample().getOrientedLattice().beta() + uc_gamma = peaks_ws.sample().getOrientedLattice().gamma() + SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=niggli_integrate_file ) + + first_time = False + else: + SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=True, Filename=niggli_integrate_file ) # # Load the combined file and re-index all of the peaks together. # Save them back to the combined Niggli file (Or selcted UB file if in use...) # - peaks_ws = LoadIsawPeaks( Filename=niggli_integrate_file ) + peaks_ws = LoadIsawPeaks( Filename=niggli_integrate_file ) # # Find a Niggli UB matrix that indexes the peaks in this run # Load UB instead of Using FFT #Index peaks using UB from UB of initial orientation run/or combined runs from first iteration of crystal orientation refinement - if read_UB: - LoadIsawUB(InputWorkspace=peaks_ws, Filename=UB_filename) - if UseFirstLattice: + if read_UB: + LoadIsawUB(InputWorkspace=peaks_ws, Filename=UB_filename) + if UseFirstLattice: # Find UB using lattice parameters from the specified file - uc_a = peaks_ws.sample().getOrientedLattice().a() - uc_b = peaks_ws.sample().getOrientedLattice().b() - uc_c = peaks_ws.sample().getOrientedLattice().c() - uc_alpha = peaks_ws.sample().getOrientedLattice().alpha() - uc_beta = peaks_ws.sample().getOrientedLattice().beta() - uc_gamma = peaks_ws.sample().getOrientedLattice().gamma() - FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance) + uc_a = peaks_ws.sample().getOrientedLattice().a() + uc_b = peaks_ws.sample().getOrientedLattice().b() + uc_c = peaks_ws.sample().getOrientedLattice().c() + uc_alpha = peaks_ws.sample().getOrientedLattice().alpha() + uc_beta = peaks_ws.sample().getOrientedLattice().beta() + uc_gamma = peaks_ws.sample().getOrientedLattice().gamma() + FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance) #OptimizeCrystalPlacement(PeaksWorkspace=peaks_ws,ModifiedPeaksWorkspace=peaks_ws,FitInfoTable='CrystalPlacement_info',MaxIndexingError=tolerance) - elif UseFirstLattice and not read_UB: + elif UseFirstLattice and not read_UB: # Find UB using lattice parameters using the FFT results from first run if no UB file is specified - FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance) - else: - FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance ) + FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance) + else: + FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance ) - IndexPeaks( PeaksWorkspace=peaks_ws, Tolerance=tolerance ) - SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=niggli_integrate_file ) - SaveIsawUB( InputWorkspace=peaks_ws, Filename=niggli_matrix_file ) + IndexPeaks( PeaksWorkspace=peaks_ws, Tolerance=tolerance ) + SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=niggli_integrate_file ) + SaveIsawUB( InputWorkspace=peaks_ws, Filename=niggli_matrix_file ) # # If requested, also switch to the specified conventional cell and save the # corresponding matrix and integrate file # if not use_cylindrical_integration: - if (not cell_type is None) and (not centering is None) : - conv_name = output_directory + "/" + exp_name + "_" + cell_type + "_" + centering - conventional_integrate_file = conv_name + ".integrate" - conventional_matrix_file = conv_name + ".mat" + if (not cell_type is None) and (not centering is None) : + conv_name = output_directory + "/" + exp_name + "_" + cell_type + "_" + centering + conventional_integrate_file = conv_name + ".integrate" + conventional_matrix_file = conv_name + ".mat" - SelectCellOfType( PeaksWorkspace=peaks_ws, CellType=cell_type, Centering=centering, + SelectCellOfType( PeaksWorkspace=peaks_ws, CellType=cell_type, Centering=centering, AllowPermutations=allow_perm, Apply=True, Tolerance=tolerance ) - SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=conventional_integrate_file ) - SaveIsawUB( InputWorkspace=peaks_ws, Filename=conventional_matrix_file ) + SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=conventional_integrate_file ) + SaveIsawUB( InputWorkspace=peaks_ws, Filename=conventional_matrix_file ) if use_cylindrical_integration: - if (not cell_type is None) or (not centering is None): - print "WARNING: Cylindrical profiles are NOT transformed!!!" + if (not cell_type is None) or (not centering is None): + print "WARNING: Cylindrical profiles are NOT transformed!!!" # Combine *.profiles files - filename = output_directory + '/' + exp_name + '.profiles' - output = open( filename, 'w' ) + filename = output_directory + '/' + exp_name + '.profiles' + output = open( filename, 'w' ) # Read and write the first run profile file with header. - r_num = run_nums[0] - filename = output_directory + '/' + instrument_name + '_' + r_num + '.profiles' - input = open( filename, 'r' ) - file_all_lines = input.read() - output.write(file_all_lines) - input.close() - os.remove(filename) + r_num = run_nums[0] + filename = output_directory + '/' + instrument_name + '_' + r_num + '.profiles' + input = open( filename, 'r' ) + file_all_lines = input.read() + output.write(file_all_lines) + input.close() + os.remove(filename) # Read and write the rest of the runs without the header. - for r_num in run_nums[1:]: - filename = output_directory + '/' + instrument_name + '_' + r_num + '.profiles' - input = open(filename, 'r') - for line in input: - if line[0] == '0': break - output.write(line) - for line in input: - output.write(line) - input.close() - os.remove(filename) + for r_num in run_nums[1:]: + filename = output_directory + '/' + instrument_name + '_' + r_num + '.profiles' + input = open(filename, 'r') + for line in input: + if line[0] == '0': break + output.write(line) + for line in input: + output.write(line) + input.close() + os.remove(filename) # Remove *.integrate file(s) ONLY USED FOR CYLINDRICAL INTEGRATION! - for file in os.listdir(output_directory): - if file.endswith('.integrate'): - os.remove(file) + for file in os.listdir(output_directory): + if file.endswith('.integrate'): + os.remove(file) end_time = time.time() diff --git a/Code/Mantid/scripts/TofConverter.py b/Code/Mantid/scripts/TofConverter.py index 8c395cb911a9..4cee4a0aa5d9 100644 --- a/Code/Mantid/scripts/TofConverter.py +++ b/Code/Mantid/scripts/TofConverter.py @@ -4,12 +4,12 @@ def qapp(): if QtGui.QApplication.instance(): - app = QtGui.QApplication.instance() + app = QtGui.QApplication.instance() else: - app = QtGui.QApplication(sys.argv) + app = QtGui.QApplication(sys.argv) return app app = qapp() reducer = converterGUI.MainWindow()#the main ui class in this file is called MainWindow reducer.show() -app.exec_() \ No newline at end of file +app.exec_() diff --git a/Code/Mantid/scripts/Vates/Inelastic_Workflow.py b/Code/Mantid/scripts/Vates/Inelastic_Workflow.py index 618a36358ae6..de2512098123 100644 --- a/Code/Mantid/scripts/Vates/Inelastic_Workflow.py +++ b/Code/Mantid/scripts/Vates/Inelastic_Workflow.py @@ -4,7 +4,7 @@ #Load an SQW file and internally convert to a Multidimensional event workspace (MDEW) if not mtd.doesExist(ws_in): - LoadSQW(filename, OutputWorkspace=ws_in) + LoadSQW(filename, OutputWorkspace=ws_in) #Bin the workspace in an axis aligned manner. Creates a Histogrammed MD workspace. BinMD(InputWorkspace=ws_in,OutputWorkspace='binned_axis_aligned',AxisAligned=True, diff --git a/Code/Mantid/scripts/Vates/SXD_NaCl.py b/Code/Mantid/scripts/Vates/SXD_NaCl.py index fe550dfa0d75..15f343be3c33 100644 --- a/Code/Mantid/scripts/Vates/SXD_NaCl.py +++ b/Code/Mantid/scripts/Vates/SXD_NaCl.py @@ -39,24 +39,24 @@ def reportUnitCell(peaks_ws): # find the Niggli cell correctly, with all angle 60 degrees, and all sides 3.99 # if use_fft: - FindUBUsingFFT(PeaksWorkspace=peaks_qLab, MinD='3', MaxD='5',Tolerance=0.08) - print '\nNiggli cell found from FindUBUsingFFT:' + FindUBUsingFFT(PeaksWorkspace=peaks_qLab, MinD='3', MaxD='5',Tolerance=0.08) + print '\nNiggli cell found from FindUBUsingFFT:' if use_cubic_lat_par: - FindUBUsingLatticeParameters(PeaksWorkspace=peaks_qLab, a=5.6402,b=5.6402,c=5.6402,alpha=90,beta=90,gamma=90,NumInitial=25,Tolerance=0.12) - print '\nCubic cell found directly from FindUBUsingLatticeParameters' + FindUBUsingLatticeParameters(PeaksWorkspace=peaks_qLab, a=5.6402,b=5.6402,c=5.6402,alpha=90,beta=90,gamma=90,NumInitial=25,Tolerance=0.12) + print '\nCubic cell found directly from FindUBUsingLatticeParameters' if use_Niggli_lat_par: - FindUBUsingLatticeParameters(PeaksWorkspace=peaks_qLab, a=3.9882,b=3.9882,c=3.9882,alpha=60,beta=60,gamma=60,NumInitial=25,Tolerance=0.12) - print '\nNiggli cell found from FindUBUsingLatticeParameters:' + FindUBUsingLatticeParameters(PeaksWorkspace=peaks_qLab, a=3.9882,b=3.9882,c=3.9882,alpha=60,beta=60,gamma=60,NumInitial=25,Tolerance=0.12) + print '\nNiggli cell found from FindUBUsingLatticeParameters:' reportUnitCell(peaks_qLab) IndexPeaks(PeaksWorkspace=peaks_qLab,Tolerance=0.12,RoundHKLs=1) if use_fft or use_Niggli_lat_par: - ShowPossibleCells(PeaksWorkspace=peaks_qLab,MaxScalarError='0.5') - SelectCellOfType(PeaksWorkspace=peaks_qLab, CellType='Cubic', Centering='F', Apply=True) + ShowPossibleCells(PeaksWorkspace=peaks_qLab,MaxScalarError='0.5') + SelectCellOfType(PeaksWorkspace=peaks_qLab, CellType='Cubic', Centering='F', Apply=True) peaks_qLab_Integrated = IntegratePeaksMD(InputWorkspace=QLab, PeaksWorkspace=peaks_qLab, PeakRadius=0.2, BackgroundInnerRadius=0.3, BackgroundOuterRadius=0.4) diff --git a/Code/Mantid/scripts/migrate1to2.py b/Code/Mantid/scripts/migrate1to2.py index a0b7f81909ff..c710b7253946 100644 --- a/Code/Mantid/scripts/migrate1to2.py +++ b/Code/Mantid/scripts/migrate1to2.py @@ -6,4 +6,4 @@ import sys -sys.exit(main.main(sys.argv[1:])) \ No newline at end of file +sys.exit(main.main(sys.argv[1:])) diff --git a/Code/Mantid/scripts/reduction/instrument.py b/Code/Mantid/scripts/reduction/instrument.py index 28aeb890e6a3..3fb42264f30e 100644 --- a/Code/Mantid/scripts/reduction/instrument.py +++ b/Code/Mantid/scripts/reduction/instrument.py @@ -40,9 +40,9 @@ def load_instrument(self): """ wrksp = '__'+self._NAME+'instrument_definition' if not AnalysisDataService.doesExist(wrksp): - api.CreateWorkspace(OutputWorkspace=wrksp,DataX="1",DataY="1",DataE="1") + api.CreateWorkspace(OutputWorkspace=wrksp,DataX="1",DataY="1",DataE="1") #read the information about the instrument that stored in its xml - api.LoadInstrument(Workspace=wrksp, InstrumentName=self._NAME) + api.LoadInstrument(Workspace=wrksp, InstrumentName=self._NAME) return AnalysisDataService.retrieve(wrksp).getInstrument() diff --git a/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py b/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py index 636b843bc708..16a0e2baba2d 100644 --- a/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py +++ b/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py @@ -104,7 +104,7 @@ def _load_entry(entry, ws, title=""): else: geo_base_file_x = "REFL_Detector_Grouping_Sum_X.xml" geo_base_file_y = "REFL_Detector_Grouping_Sum_Y.xml" - + if is_pixel_y: grouping_file = os.path.join(instr_dir, "Grouping", geo_base_file_x) diff --git a/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py b/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py index 0e37f61ed629..21993d251ff0 100644 --- a/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py +++ b/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py @@ -82,7 +82,7 @@ def getSheight(mt, index): else: tag = 'S1VHeight' value = mt_run.getProperty(tag).value - + return value[0] def getS1h(mt=None): @@ -437,7 +437,7 @@ def convertWorkspaceToQ(ws_data, a = y_range[y] _tmp_y_axis = mt1.readY(int(a))[:] - _y_axis[int(y), :] = _tmp_y_axis; + _y_axis[int(y), :] = _tmp_y_axis _tmp_y_error_axis = mt1.readE(int(a))[:] _y_error_axis[int(y),:] = _tmp_y_error_axis @@ -503,19 +503,19 @@ def angleUnitConversion(value, from_units='degree', to_units='rad'): """ if (from_units == to_units): - return value; + return value - from_factor = 1; + from_factor = 1 #convert everything into rad if (from_units == 'degree'): - from_factor = 1.745329252e-2; - value_rad = from_factor * value; + from_factor = 1.745329252e-2 + value_rad = from_factor * value if (to_units == 'rad'): - return value_rad; + return value_rad else: - to_factor = 57.2957795; - return to_factor * value_rad; + to_factor = 57.2957795 + return to_factor * value_rad def convertToThetaVsLambda(_tof_axis, _pixel_axis, @@ -840,7 +840,7 @@ def applySF(InputWorkspace, print '--> Data S2H: {0:2f}'.format(s2h_value) print '--> Data S1W: {0:2f}'.format(s1w_value) print '--> Data S2W: {0:2f}'.format(s2w_value) - + print 'mERDDEEEEDEDEED' for i in range(nbr_row): @@ -1005,7 +1005,7 @@ def rebinNeXus(inputWorkspace, params, type): print '--> rebin ', type ws_histo_data = Rebin(InputWorkspace=inputWorkspace, Params=params, - PreserveEvents=True); + PreserveEvents=True) return ws_histo_data def cropTOF(inputWorkspace, min, max, type): @@ -1170,7 +1170,7 @@ def weightedMean(data_array, error_array, error_0): sz = len(data_array) # calculate the numerator of mean - dataNum = 0; + dataNum = 0 for i in range(sz): if (error_array[i] == 0): error_array[i] = error_0 @@ -1179,7 +1179,7 @@ def weightedMean(data_array, error_array, error_0): dataNum += tmpFactor # calculate denominator - dataDen = 0; + dataDen = 0 for i in range(sz): if (error_array[i] == 0): error_array[i] = error_0 @@ -1334,7 +1334,7 @@ def ouput_ascii_file(file_name, sz_x_axis = len(x_axis) for i in range(sz_x_axis-1): - f.write(str(x_axis[i]) + "," + str(y_axis[i]) + "," + str(y_error_axis[i]) + "\n"); + f.write(str(x_axis[i]) + "," + str(y_axis[i]) + "," + str(y_error_axis[i]) + "\n") f.close @@ -1957,8 +1957,8 @@ def cropAxisToOnlyNonzeroElements(q_rebin, dataPeakRange): x_axis = q_rebin.readX(0)[:] sz = x_axis.shape[0]-1 - index_first_non_zero_value = sz; - index_last_non_zero_value = 0; + index_first_non_zero_value = sz + index_last_non_zero_value = 0 for x in range(nbrPixel): _pixel_axis = q_rebin.readY(x)[:] @@ -2043,7 +2043,7 @@ def cleanupData1D(final_data_y_axis, final_data_y_error_axis): sz = final_data_y_axis.shape nbrTof = sz[0] - notYetRemoved = True; + notYetRemoved = True for t in range(nbrTof): @@ -2076,15 +2076,15 @@ def cleanupData1D(final_data_y_axis, final_data_y_error_axis): return [final_data_y_axis, final_data_y_error_axis] def isNexusTakeAfterRefDate(nexus_date): - ''' + ''' This function parses the output.date and returns true if this date is after the ref date ''' - nexus_date_acquistion = nexus_date.split('T')[0] - - if nexus_date_acquistion > ref_date: - return True - else: - return False + nexus_date_acquistion = nexus_date.split('T')[0] + + if nexus_date_acquistion > ref_date: + return True + else: + return False diff --git a/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py b/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py index 8b44f00236db..f6bf12837a0a 100644 --- a/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py +++ b/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py @@ -540,7 +540,7 @@ def set_gravity(self, flag, override=True): self._grav_set = True if (not self._grav_set) or override: - self._use_gravity = bool(flag) + self._use_gravity = bool(flag) else: msg = "User file can't override previous gravity setting, do gravity correction remains " + str(self._use_gravity) print msg diff --git a/Code/Tools/Pylint/pylint.cfg b/Code/Tools/Pylint/pylint.cfg index e3675ca90a4e..45bc53816b56 100644 --- a/Code/Tools/Pylint/pylint.cfg +++ b/Code/Tools/Pylint/pylint.cfg @@ -81,7 +81,7 @@ comment=no [FORMAT] # Maximum number of characters on a single line. -max-line-length=100 +max-line-length=140 # Maximum number of lines in a module max-module-lines=1000 @@ -213,16 +213,16 @@ max-args=5 ignored-argument-names=_.* # Maximum number of locals for function / method body -max-locals=15 +max-locals=25 # Maximum number of return / yield for function / method body max-returns=6 # Maximum number of branch for function / method body -max-branchs=12 +max-branchs=25 # Maximum number of statements in function / method body -max-statements=50 +max-statements=150 # Maximum number of parents for a class (see R0901). max-parents=7 From 327fcf1a9c292f98b4de96c47735c57550d1e88c Mon Sep 17 00:00:00 2001 From: Andrei Savici Date: Wed, 18 Feb 2015 17:47:12 -0500 Subject: [PATCH 288/414] Fix some indentation. Refs #10945 --- .../scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py index 9d4bec946929..cc784399c72a 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py @@ -68,7 +68,7 @@ def CalibrateWish( run_per_panel_list): # copy data from the current panel to the whole_instrument for i in range(tube_set.getNumTubes()): for spec_num in tube_set.getTube(i): - whole_instrument.setY(spec_num,ws.dataY(spec_num)) + whole_instrument.setY(spec_num,ws.dataY(spec_num)) # calibrate the whole_instrument with the last calibrated panel which has the calibration accumulation # of all the others @@ -79,6 +79,6 @@ def CalibrateWish( run_per_panel_list): if __name__ == "__main__": - # this file is found on cycle_11_1 + # this file is found on cycle_11_1 run_per_panel_list = [ (17706, 'panel01'), (17705, 'panel02'), (17701, 'panel03'), (17702, 'panel04'), (17695, 'panel05')] CalibrateWish(run_per_panel_list) From 9be647abe2cf8232062b415ec50daecb7b944b80 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Thu, 19 Feb 2015 08:37:04 +0000 Subject: [PATCH 289/414] Re #9556 Removing more dead code --- Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp index c69970ae783c..4b7bae69801a 100644 --- a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -105,9 +105,6 @@ void DynamicKuboToyabe::function1D(double* out, const double* xValues, const siz } // Non-zero external field else{ - //for (size_t i = 0; i < nData; i++) { - // out[i] = A*HKT(xValues[i],G,F); - //} throw std::runtime_error("HKT() not implemented yet"); } } From 7fdedb08f933f9cdf0fa2ab3e6b67d32847bafff Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Thu, 19 Feb 2015 09:19:38 +0000 Subject: [PATCH 290/414] Add a systemtests.bat script for driving system test jobs. Refs #10870 --- Code/Mantid/Build/Jenkins/systemtests | 2 + Code/Mantid/Build/Jenkins/systemtests.bat | 66 +++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100755 Code/Mantid/Build/Jenkins/systemtests.bat diff --git a/Code/Mantid/Build/Jenkins/systemtests b/Code/Mantid/Build/Jenkins/systemtests index 5ced2d5bd7dc..16f29a98e56b 100755 --- a/Code/Mantid/Build/Jenkins/systemtests +++ b/Code/Mantid/Build/Jenkins/systemtests @@ -46,6 +46,8 @@ cd $WORKSPACE/build ############################################################################### if [[ ! -e $WORKSPACE/build/CMakeCache.txt ]]; then $SCL_ON_RHEL6 "cmake -DMANTID_DATA_STORE=${MANTID_DATA_STORE} -DDATA_TARGETS_ONLY=ON ../Code/Mantid" +else + $SCL_ON_RHEL6 "cmake ." fi ############################################################################### diff --git a/Code/Mantid/Build/Jenkins/systemtests.bat b/Code/Mantid/Build/Jenkins/systemtests.bat new file mode 100755 index 000000000000..3c2f3e003568 --- /dev/null +++ b/Code/Mantid/Build/Jenkins/systemtests.bat @@ -0,0 +1,66 @@ +setlocal enbaleextensions enabledelayedexpansion +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: WINDOWS SCRIPT TO DRIVE THE SYSTEM TESTS OF MANTID +:: +:: Notes: +:: +:: WORKSPACE, JOB_NAME & NODE_LABEL are environment variables that +:: are set by Jenkins. The last one corresponds to any labels set on a slave. +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Print out the versions of things we are using +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +set CMAKE_BIN_DIR=C:\Program Files (x86)\CMake 2.8\bin +"%CMAKE_BIN_DIR%\cmake" --version +echo %sha1% + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Set up the location for local object store outside of the build and source +:: tree, which can be shared by multiple builds. +:: It defaults to a MantidExternalData directory within the USERPROFILE +:: directory. It can be overridden by setting the MANTID_DATA_STORE environment +:: variable. +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +if NOT DEFINED MANTID_DATA_STORE ( + set MANTID_DATA_STORE=%USERPROFILE%\MantidExternalData +) + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Setup the build directory +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +md %WORKSPACE%\build +cd %WORKSPACE%\build + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: CMake configuration if it has not already been configured. +:: We use the special flag that only creates the targets for the data +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +if not EXIST %WORKSPACE%\build\CMakeCache.txt ( + "%CMAKE_BIN_DIR%\cmake" -DMANTID_DATA_STORE=!MANTID_DATA_STORE! -DDATA_TARGETS_ONLY=ON ..\Code\Mantid +) else ( + :: This ensures that any new data files are picked up by the cmake globbing + "%CMAKE_BIN_DIR%\cmake" . +) + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Build step +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +"%CMAKE_BIN_DIR%\cmake" --build . -- StandardTestData +"%CMAKE_BIN_DIR%\cmake" --build . -- SystemTestData + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Run the tests +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Remove any Mantid.user.properties file +set USERPROPS=C:\MantidInstall\bin\Mantid.user.properties +del /Q %USERPROPS% +:: Turn off usage reports and instrument downloading for the mantid call +:: that creates the properties file +echo UpdateInstrumentDefinitions.OnStartup = 0 > %USERPROPS% +echo usagereports.enabled = 0 >> %USERPROPS% + +:: Run +set PKGDIR=%WORKSPACE%\build +python %WORKSPACE%\Code\Mantid\Testing\SystemTests\scripts\InstallerTests.py -o -d %PKGDIR% + From b88d144d88310870799e192e038902ccd8a3c6e3 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Thu, 19 Feb 2015 09:20:25 +0000 Subject: [PATCH 291/414] refs #11056. Fix IPeak::setQLabFrame defaults issue. --- Code/Mantid/Framework/Crystal/test/IndexSXPeaksTest.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/Crystal/test/IndexSXPeaksTest.h b/Code/Mantid/Framework/Crystal/test/IndexSXPeaksTest.h index b8c4ca4a2166..a69316a8dc7d 100644 --- a/Code/Mantid/Framework/Crystal/test/IndexSXPeaksTest.h +++ b/Code/Mantid/Framework/Crystal/test/IndexSXPeaksTest.h @@ -120,7 +120,7 @@ class IndexSXPeaksTest : public CxxTest::TestSuite { IPeak& peak = m_masterPeaks->getPeak(i); Mantid::Kernel::V3D v(1, 0, 0); - peak.setQSampleFrame(v); // Overwrite all Q samples to be co-linear. + peak.setQSampleFrame(v, boost::optional()); // Overwrite all Q samples to be co-linear. } TS_ASSERT_THROWS(doTest(6, "1, 2, 3, 4, 5, 6", 14.131, 19.247, 8.606, 90.0, 105.071, 90.0), std::runtime_error); From de6037d8fd8335b7cbe6a19a26063445ca43640b Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Thu, 19 Feb 2015 09:20:37 +0000 Subject: [PATCH 292/414] Fix a doctest output to work cross platform. On windows the numpy shape array was printed as (100L, 100L), which caused the string comparison to fail. Refs #10870 --- Code/Mantid/docs/source/algorithms/MDNormDirectSC-v1.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/docs/source/algorithms/MDNormDirectSC-v1.rst b/Code/Mantid/docs/source/algorithms/MDNormDirectSC-v1.rst index 3044493549f1..d59635e54692 100644 --- a/Code/Mantid/docs/source/algorithms/MDNormDirectSC-v1.rst +++ b/Code/Mantid/docs/source/algorithms/MDNormDirectSC-v1.rst @@ -63,8 +63,9 @@ Usage AlignedDim0="[H,0,0],-0.2,1.6,100", AlignedDim1="DeltaE,-1.5,3.,100", ) - normalized=histoData/histoNorm - print "The normalization workspace shape is "+str(histoNorm.getSignalArray().shape) + normalized=histoData/histoNorm + histoShape=histoNorm.getSignalArray().shape + print "The normalization workspace shape is (%d, %d)" % histoShape print "Out of those elements, "+str(nonzero(histoNorm.getSignalArray())[0].size)+" are nonzero" .. testoutput:: MDNormDirectSCExample From 70ada56493efa09c91819f04f7cc571b498ddb4e Mon Sep 17 00:00:00 2001 From: Roman Tolchenov Date: Thu, 19 Feb 2015 09:36:54 +0000 Subject: [PATCH 293/414] Re #11115. Fixed the tests. --- .../CurveFitting/test/GaussianTest.h | 113 +++--------------- 1 file changed, 14 insertions(+), 99 deletions(-) diff --git a/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h b/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h index 760c5712f462..db5fbe75d89e 100644 --- a/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h @@ -295,85 +295,7 @@ class GaussianTest : public CxxTest::TestSuite } - void t11estAgainstPeak2FallbackToSimplex() - { - // create peak2 mock data to test against - std::string wsName = "GaussHRP38692MockData"; - int histogramNumber = 1; - int timechannels = 41; - Workspace_sptr ws = WorkspaceFactory::Instance().create("Workspace2D",histogramNumber,timechannels,timechannels); - Workspace2D_sptr ws2D = boost::dynamic_pointer_cast(ws); - Mantid::MantidVec& x = ws2D->dataX(0); // x-values (time-of-flight) - Mantid::MantidVec& y = ws2D->dataY(0); // y-values (counts) - Mantid::MantidVec& e = ws2D->dataE(0); // error values of counts - getHRP38692Peak2Data(x, y, e); - - //put this workspace in the data service - TS_ASSERT_THROWS_NOTHING(AnalysisDataService::Instance().add(wsName, ws2D)); - - // Initialise algorithm - Fit alg; - TS_ASSERT_THROWS_NOTHING(alg.initialize()); - TS_ASSERT( alg.isInitialized() ); - - // create function you want to fit against - CompositeFunction_sptr fnWithBk( new CompositeFunction() ); - - boost::shared_ptr bk( new LinearBackground() ); - bk->initialize(); - - bk->setParameter("A0",0.0); - bk->setParameter("A1",0.0); - bk->tie("A1","0"); - - BoundaryConstraint* bc_b = new BoundaryConstraint(bk.get(),"A0",0, 20.0); - bk->addConstraint(bc_b); - - // set up Gaussian fitting function - boost::shared_ptr fn( new Gaussian() ); - fn->initialize(); - - fn->setParameter("Height",200.0); - fn->setParameter("PeakCentre",79450.0); - fn->setParameter("Sigma",300.0); - - // add constraint to function - BoundaryConstraint* bc3 = new BoundaryConstraint(fn.get(),"Sigma",20, 100.0); - fn->addConstraint(bc3); - - fnWithBk->addFunction(bk); - fnWithBk->addFunction(fn); - - alg.setProperty("Function",fnWithBk); - // Set which spectrum to fit against and initial starting values - alg.setPropertyValue("InputWorkspace", wsName); - alg.setPropertyValue("StartX","79300"); - alg.setPropertyValue("EndX","79600"); - - - // execute fit - TS_ASSERT_THROWS_NOTHING( - TS_ASSERT( alg.execute() ) - ) - TS_ASSERT( alg.isExecuted() ); - - // test the output from fit is what you expect - double dummy = alg.getProperty("OutputChi2overDoF"); - TS_ASSERT_DELTA( dummy, 0.0,0.1); - - IFunction_sptr out = alg.getProperty("Function"); - IPeakFunction *pk = dynamic_cast(dynamic_cast(out.get())->getFunction(1).get()); - TS_ASSERT_DELTA( pk->height(), 249.3187 ,0.01); - TS_ASSERT_DELTA( pk->centre(), 79430 ,0.1); - TS_ASSERT_DELTA( pk->getParameter("Sigma"), 25.3066 ,0.01); - TS_ASSERT_DELTA( out->getParameter("f0.A0"), 7.8643 ,0.001); - TS_ASSERT_DELTA( out->getParameter("f0.A1"), 0.0 ,0.01); - - AnalysisDataService::Instance().remove(wsName); - } - - - void xtestAgainstMockData() + void testAgainstMockData() { // create mock data to test against std::string wsName = "GaussMockData"; @@ -404,6 +326,7 @@ class GaussianTest : public CxxTest::TestSuite alg2.setPropertyValue("WorkspaceIndex","0"); alg2.setPropertyValue("StartX","0"); alg2.setPropertyValue("EndX","20"); + alg2.setPropertyValue("Minimizer","Levenberg-MarquardtMD"); // execute fit TS_ASSERT_THROWS_NOTHING( @@ -411,18 +334,15 @@ class GaussianTest : public CxxTest::TestSuite ) TS_ASSERT( alg2.isExecuted() ); - std::string minimizer = alg2.getProperty("Minimizer"); - TS_ASSERT( minimizer.compare("Levenberg-Marquardt") == 0 ); - // test the output from fit is what you expect double dummy = alg2.getProperty("OutputChi2overDoF"); TS_ASSERT_DELTA( dummy, 0.035,0.01); IFunction_sptr out = alg2.getProperty("Function"); IPeakFunction *pk = dynamic_cast(out.get()); - TS_ASSERT_DELTA( pk->height(), 97.9728 ,0.0001); - TS_ASSERT_DELTA( pk->centre(), 11.2194 ,0.0001); - TS_ASSERT_DELTA( pk->fwhm(), 2.6181 ,0.0001); + TS_ASSERT_DELTA( pk->height(), 97.8036 ,0.0001); + TS_ASSERT_DELTA( pk->centre(), 11.2356 ,0.0001); + TS_ASSERT_DELTA( pk->fwhm(), 2.6237 ,0.0001); } @@ -492,7 +412,7 @@ class GaussianTest : public CxxTest::TestSuite // and used a starting of Sigma = 100. // Note that the no constraint simplex with Sigma = 300 also does not locate // the correct minimum but not as badly as levenberg-marquardt - void t11estAgainstHRPD_DatasetWithConstraintsSimplex() + void testAgainstHRPD_DatasetWithConstraintsSimplex() { // create peak2 mock data to test against std::string wsName = "GaussHRP38692MockData"; @@ -500,7 +420,7 @@ class GaussianTest : public CxxTest::TestSuite int timechannels = 41; Workspace_sptr ws = WorkspaceFactory::Instance().create("Workspace2D",histogramNumber,timechannels,timechannels); Workspace2D_sptr ws2D = boost::dynamic_pointer_cast(ws); - Mantid::MantidVec& x = ws2D->dataX(0); // x-values (time-of-flight) + Mantid::MantidVec& x = ws2D->dataX(0); // x-values (time-of-flight) Mantid::MantidVec& y = ws2D->dataY(0); // y-values (counts) Mantid::MantidVec& e = ws2D->dataE(0); // error values of counts getHRP38692Peak2Data(x, y, e); @@ -536,21 +456,16 @@ class GaussianTest : public CxxTest::TestSuite fn->setParameter("Sigma",10.0); // add constraint to function - //BoundaryConstraint* bc1 = new BoundaryConstraint(fn,"Height",100, 300.0); - //BoundaryConstraint* bc2 = new BoundaryConstraint(fn,"PeakCentre",79200, 79700.0); BoundaryConstraint* bc3 = new BoundaryConstraint(fn.get(),"Sigma",20, 100.0); - //fn->addConstraint(bc1); - //fn->addConstraint(bc2); fn->addConstraint(bc3); fnWithBk->addFunction(bk); fnWithBk->addFunction(fn); - //alg.setPropertyValue("Function",*fnWithBk); - alg.setProperty("Function",fnWithBk); + alg.setProperty("Function",boost::dynamic_pointer_cast(fnWithBk)); // Set which spectrum to fit against and initial starting values - alg.setPropertyValue("InputWorkspace",wsName); + alg.setProperty("InputWorkspace",ws); alg.setPropertyValue("StartX","79300"); alg.setPropertyValue("EndX","79600"); alg.setPropertyValue("Minimizer","Simplex"); @@ -566,16 +481,16 @@ class GaussianTest : public CxxTest::TestSuite // test the output from fit is what you expect double dummy = alg.getProperty("OutputChi2overDoF"); - TS_ASSERT_DELTA( dummy, 5.1604,1); + TS_ASSERT_DELTA( dummy, 2.5911,1); IFunction_sptr fun = alg.getProperty("Function"); TS_ASSERT(fun); IFunction_sptr out = alg.getProperty("Function"); - TS_ASSERT_DELTA( out->getParameter("f1.Height"), 216.419 ,1); - TS_ASSERT_DELTA( out->getParameter("f1.PeakCentre"), 79430.1 ,1); - TS_ASSERT_DELTA( out->getParameter("f1.Sigma"), 27.08 ,0.1); - TS_ASSERT_DELTA( out->getParameter("f0.A0"), 2.18 ,0.1); + TS_ASSERT_DELTA( out->getParameter("f1.Height"), 232 ,1); + TS_ASSERT_DELTA( out->getParameter("f1.PeakCentre"), 79430 ,1); + TS_ASSERT_DELTA( out->getParameter("f1.Sigma"), 26.08 ,1); + TS_ASSERT_DELTA( out->getParameter("f0.A0"), 8 ,1); TS_ASSERT_DELTA( out->getParameter("f0.A1"), 0.0 ,0.01); AnalysisDataService::Instance().remove(wsName); From 203539339bb27a42aef20f3288d0475dbce56667 Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Thu, 19 Feb 2015 11:06:54 +0100 Subject: [PATCH 294/414] Refs #11104. Adding general test for IPeakFunction::intensity --- .../Framework/CurveFitting/CMakeLists.txt | 1 + .../test/IPeakFunctionIntensityTest.h | 152 ++++++++++++++++++ 2 files changed, 153 insertions(+) create mode 100644 Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h diff --git a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt index edcb417d8e0a..1907f29a5e01 100644 --- a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt +++ b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt @@ -257,6 +257,7 @@ set ( TEST_FILES GaussianTest.h GramCharlierComptonProfileTest.h IkedaCarpenterPVTest.h + IPeakFunctionIntensityTest.h LeBailFitTest.h LeBailFunctionTest.h LeastSquaresTest.h diff --git a/Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h b/Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h new file mode 100644 index 000000000000..12fa0c8f286e --- /dev/null +++ b/Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h @@ -0,0 +1,152 @@ +#ifndef IPEAKFUNCTIONINTENSITYTEST_H +#define IPEAKFUNCTIONINTENSITYTEST_H + +#include +#include "MantidAPI/FrameworkManager.h" +#include "MantidAPI/FunctionFactory.h" +#include "MantidAPI/IPeakFunction.h" +#include + +using namespace Mantid::API; + +#define DBL2STR(x) boost::lexical_cast(x) + +struct ParameterSet { + ParameterSet(double c, double h, double f) : center(c), height(h), fwhm(f) {} + + double center; + double height; + double fwhm; +}; + +class IPeakFunctionIntensityTest : public CxxTest::TestSuite { +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static IPeakFunctionIntensityTest *createSuite() { + return new IPeakFunctionIntensityTest(); + } + static void destroySuite(IPeakFunctionIntensityTest *suite) { delete suite; } + + IPeakFunctionIntensityTest() : m_blackList() { + FrameworkManager::Instance(); + + m_blackList.insert("BackToBackExponential"); + m_blackList.insert("DeltaFunction"); + m_blackList.insert("ElasticDiffRotDiscreteCircle"); + m_blackList.insert("ElasticDiffSphere"); + + m_peakFunctions = getAllPeakFunctions(m_blackList); + m_parameterSets = getParameterSets(); + } + + /* This test sets all peak function parameters (center, fwhm, height) + * to the values supplied in the first ParameterSet contained in + * m_parameterSets. + * + * Then it retrieves the intensities of the peak functions and stores them. + * Each time new parameters are set, the ratio of the height parameter to + * the previous step is compared to the intensity ratio - they should be + * the same. + */ + void testAllFunctions() { + initializePeakFunctions(m_peakFunctions, m_parameterSets[0]); + + std::vector initialIntensities = getIntensities(m_peakFunctions); + + for (size_t i = 1; i < m_parameterSets.size(); ++i) { + double oldHeight = m_parameterSets[i - 1].height; + double newHeight = m_parameterSets[i].height; + double heightRatio = newHeight / oldHeight; + + initializePeakFunctions(m_peakFunctions, m_parameterSets[i]); + + std::vector newIntensities = getIntensities(m_peakFunctions); + + for (size_t j = 0; j < initialIntensities.size(); ++j) { + double oldIntensity = initialIntensities[j]; + double newIntensity = newIntensities[j]; + double intensityRatio = newIntensity / oldIntensity; + + TSM_ASSERT_DELTA( + "ITERATION " + DBL2STR(i) + ", " + m_peakFunctions[j]->name() + + ": Height was increased from " + DBL2STR(oldHeight) + " to " + + DBL2STR(newHeight) + " (ratio " + DBL2STR(heightRatio) + + "), but intensity changed from " + DBL2STR(oldIntensity) + + " to " + DBL2STR(newIntensity) + " (ratio " + + DBL2STR(intensityRatio) + ").", + intensityRatio, heightRatio, 1e-10); + } + + initialIntensities = newIntensities; + } + } + +private: + std::vector + getAllPeakFunctions(const std::set &blackList) const { + std::vector peakFunctions; + + std::vector registeredFunctions = + FunctionFactory::Instance().getFunctionNames(); + + for (auto it = registeredFunctions.begin(); it != registeredFunctions.end(); + ++it) { + if (blackList.count(*it) == 0) { + IPeakFunction_sptr peakFunction = + boost::dynamic_pointer_cast( + FunctionFactory::Instance().createFunction(*it)); + + if (peakFunction) { + peakFunctions.push_back(peakFunction); + } + } + } + + return peakFunctions; + } + + void initializePeakFunctions(const std::vector &peaks, + const ParameterSet ¶meters) const { + + for (auto it = peaks.begin(); it != peaks.end(); ++it) { + (*it)->setCentre(parameters.center); + + // for Ikeda-Carpenter it's not allowed to set Fwhm + try { + (*it)->setFwhm(parameters.fwhm); + } + catch (std::invalid_argument) { + } + + (*it)->setHeight(parameters.height); + } + } + + std::vector getParameterSets() const { + std::vector parameterSets; + parameterSets.push_back(ParameterSet(0.0, 4.34, 0.25)); + parameterSets.push_back(ParameterSet(0.0, 5.34, 0.25)); + parameterSets.push_back(ParameterSet(0.0, 6.34, 0.25)); + parameterSets.push_back(ParameterSet(0.0, 7.34, 0.25)); + + return parameterSets; + } + + std::vector + getIntensities(const std::vector &peaks) const { + std::vector intensities; + + for (auto it = peaks.begin(); it != peaks.end(); ++it) { + intensities.push_back((*it)->intensity()); + } + + return intensities; + } + + std::vector m_peakFunctions; + std::vector m_parameterSets; + std::set m_blackList; +}; + +#endif // IPEAKFUNCTIONINTENSITYTEST_H From c7c5e1b483e581704ce280a89b0834bc853e92d9 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Thu, 19 Feb 2015 10:50:16 +0000 Subject: [PATCH 295/414] refs #11056. Fix doxygen warning. --- .../Framework/TestHelpers/src/ComponentCreationHelper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp b/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp index 0d694bc98c49..0618e788d5aa 100644 --- a/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp +++ b/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp @@ -573,7 +573,7 @@ Instrument_sptr createTestInstrumentRectangular2(int num_banks, int pixels, * @param detectorPos : V3D detector position * @return Instrument generated. */ -Instrument_sptr createMinimalInstrument(const V3D& sourcePos, const V3D& samplePos, const V3D& detectorPos ) +Instrument_sptr createMinimalInstrument(const Mantid::Kernel::V3D& sourcePos, const Mantid::Kernel::V3D& samplePos, const Mantid::Kernel::V3D& detectorPos ) { Instrument_sptr instrument = boost::make_shared(); instrument->setReferenceFrame( From 27e306588bf126895eccd2f79cd7aa575d8c7bb8 Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Thu, 19 Feb 2015 11:53:05 +0100 Subject: [PATCH 296/414] Refs #11104. Adding Muon_ExpDecayOscTest to blacklist --- .../Framework/CurveFitting/test/IPeakFunctionIntensityTest.h | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h b/Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h index 12fa0c8f286e..ade73e302e1c 100644 --- a/Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h @@ -35,6 +35,7 @@ class IPeakFunctionIntensityTest : public CxxTest::TestSuite { m_blackList.insert("DeltaFunction"); m_blackList.insert("ElasticDiffRotDiscreteCircle"); m_blackList.insert("ElasticDiffSphere"); + m_blackList.insert("Muon_ExpDecayOscTest"); m_peakFunctions = getAllPeakFunctions(m_blackList); m_parameterSets = getParameterSets(); From 1ec1f8336b0b8017acc4544bcac44b058ae00686 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Thu, 19 Feb 2015 11:11:12 +0000 Subject: [PATCH 297/414] refs #11056. CreateSampleWorkspace fixed. CreateSampleWorkspace does not set up a ReferenceFrame which is consistent with the actual layout of the instrument. I don't know how this probelem got in there in the first-place, or why it hadn't cause problem up to now! Peak calculations require that the reference frame is known so that we can dot product with the beam direction in order to determine dQ. Fixing this should now make the doc-tests pass. --- Code/Mantid/Framework/Algorithms/src/CreateSampleWorkspace.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/Algorithms/src/CreateSampleWorkspace.cpp b/Code/Mantid/Framework/Algorithms/src/CreateSampleWorkspace.cpp index f04d8ac8bb3f..99496421e98c 100644 --- a/Code/Mantid/Framework/Algorithms/src/CreateSampleWorkspace.cpp +++ b/Code/Mantid/Framework/Algorithms/src/CreateSampleWorkspace.cpp @@ -396,7 +396,7 @@ Instrument_sptr CreateSampleWorkspace::createTestInstrumentRectangular( int num_banks, int pixels, double pixelSpacing) { boost::shared_ptr testInst(new Instrument("basic_rect")); testInst->setReferenceFrame( - boost::shared_ptr(new ReferenceFrame(Y, X, Left, ""))); + boost::shared_ptr(new ReferenceFrame(Y, Z, Left, ""))); const double cylRadius(pixelSpacing / 2); const double cylHeight(0.0002); From f42f48de1ced2a4dfe573d06f9349cfd4444de26 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Thu, 19 Feb 2015 13:31:44 +0000 Subject: [PATCH 298/414] refs #11056. Run alg as child. --- Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h b/Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h index 278cb40f270a..0c842e3da845 100644 --- a/Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h +++ b/Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h @@ -75,8 +75,8 @@ class AddPeakHKLTest : public CxxTest::TestSuite ws->mutableSample().setOrientedLattice(&orientedLattice); ws->mutableRun().setGoniometer(goniometer, false); - Mantid::API::AnalysisDataService::Instance().add("peaks_ws",ws); AddPeakHKL alg; + alg.setChild(true); alg.initialize(); std::vector hklVec; hklVec.push_back(hkl.X()); @@ -85,10 +85,10 @@ class AddPeakHKLTest : public CxxTest::TestSuite alg.setProperty("HKL", hklVec); alg.setProperty("Workspace", ws); alg.execute(); - ws = Mantid::API::AnalysisDataService::Instance().retrieveWS("peaks_ws"); + IPeaksWorkspace_sptr ws_out = alg.getProperty("Workspace"); // Get the peak just added. - const Peak& peak = ws->getPeak(0); + const IPeak& peak =ws_out->getPeak(0); /* Now we check we have made a self - consistent peak From e64f93044bf72b49fbd7ea0e4c5256d63c42d52a Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Thu, 19 Feb 2015 15:09:59 +0100 Subject: [PATCH 299/414] Refs #11104. Not giving up on setIntensity so quickly If intensity is 0, we first try to set height to a different, arbitrary value, following Roman's suggestion. If it's still 0 after that, there's nothing left to do. --- Code/Mantid/Framework/API/src/IPeakFunction.cpp | 13 +++++++++++-- .../Framework/CurveFitting/test/GaussianTest.h | 7 +++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/API/src/IPeakFunction.cpp b/Code/Mantid/Framework/API/src/IPeakFunction.cpp index f5995bf995bb..07053b760fda 100644 --- a/Code/Mantid/Framework/API/src/IPeakFunction.cpp +++ b/Code/Mantid/Framework/API/src/IPeakFunction.cpp @@ -153,8 +153,17 @@ void IPeakFunction::setIntensity(const double newIntensity) { double currentIntensity = intensity(); if (currentIntensity == 0.0) { - throw std::invalid_argument( - "Cannot set new intensity, not enough information available."); + // Try to set a different height first. + setHeight(2.0); + + currentHeight = height(); + currentIntensity = intensity(); + + // If the current intensity is still 0, there's nothing left to do. + if (currentIntensity == 0.0) { + throw std::invalid_argument( + "Cannot set new intensity, not enough information available."); + } } setHeight(newIntensity / currentIntensity * currentHeight); diff --git a/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h b/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h index e7bc607d7898..ee2a682fdf6a 100644 --- a/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h @@ -621,8 +621,15 @@ class GaussianTest : public CxxTest::TestSuite TS_ASSERT_EQUALS(fn->intensity(), 0.0); + // This does not work, because fwhm is 0 and height is 0 TS_ASSERT_THROWS(fn->setIntensity(20.0), std::invalid_argument); TS_ASSERT_EQUALS(fn->intensity(), 0.0); + + // Now, fwhm is not zero + fn->setFwhm(0.02); + + TS_ASSERT_THROWS_NOTHING(fn->setIntensity(20.0)); + TS_ASSERT_DELTA(fn->intensity(), 20.0, 1e-10); } From 3a13ae5e3708ff9c83be21341e62e59927a3f929 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Thu, 19 Feb 2015 14:13:06 +0000 Subject: [PATCH 300/414] Update SaveIsawPeaks-v1.rst Information about saving peak shape. --- Code/Mantid/docs/source/algorithms/SaveIsawPeaks-v1.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/docs/source/algorithms/SaveIsawPeaks-v1.rst b/Code/Mantid/docs/source/algorithms/SaveIsawPeaks-v1.rst index 3715ca27c786..5371c65ac2ba 100644 --- a/Code/Mantid/docs/source/algorithms/SaveIsawPeaks-v1.rst +++ b/Code/Mantid/docs/source/algorithms/SaveIsawPeaks-v1.rst @@ -9,7 +9,9 @@ Description ----------- -Save a PeaksWorkspace to a ISAW-style ASCII .peaks file. +Save a :ref:`PeaksWorkspace ` to a ISAW-style ASCII .peaks file. + +The PeaksWorkspace :ref:`PeaksWorkspace ` consists of individual Peaks, each of which has an individual PeakShape relating to the way the workspace has been integrated. The PeakShape information is not saved out in the ISAW peaks format. To save the full peak information, use the NeXus format :ref:`SaveNexus `. Usage ----- From d1b4a7d7372a2237ba27c5446454fc63ef297c72 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Thu, 19 Feb 2015 14:13:42 +0000 Subject: [PATCH 301/414] Update SaveIsawPeaks-v1.rst Remove duplication --- Code/Mantid/docs/source/algorithms/SaveIsawPeaks-v1.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/docs/source/algorithms/SaveIsawPeaks-v1.rst b/Code/Mantid/docs/source/algorithms/SaveIsawPeaks-v1.rst index 5371c65ac2ba..19e0858e28f7 100644 --- a/Code/Mantid/docs/source/algorithms/SaveIsawPeaks-v1.rst +++ b/Code/Mantid/docs/source/algorithms/SaveIsawPeaks-v1.rst @@ -11,7 +11,7 @@ Description Save a :ref:`PeaksWorkspace ` to a ISAW-style ASCII .peaks file. -The PeaksWorkspace :ref:`PeaksWorkspace ` consists of individual Peaks, each of which has an individual PeakShape relating to the way the workspace has been integrated. The PeakShape information is not saved out in the ISAW peaks format. To save the full peak information, use the NeXus format :ref:`SaveNexus `. +The :ref:`PeaksWorkspace ` consists of individual Peaks, each of which has an individual PeakShape relating to the way the workspace has been integrated. The PeakShape information is not saved out in the ISAW peaks format. To save the full peak information, use the NeXus format :ref:`SaveNexus `. Usage ----- From 35d31454a17bb408669c9c2977d6ab8f14fecd61 Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Thu, 19 Feb 2015 14:33:07 +0000 Subject: [PATCH 302/414] Update PeaksWorkspace.rst Add PeakShape information and update tools to visualise with. --- .../docs/source/concepts/PeaksWorkspace.rst | 40 +++++++++++-------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/Code/Mantid/docs/source/concepts/PeaksWorkspace.rst b/Code/Mantid/docs/source/concepts/PeaksWorkspace.rst index 582398fdb5b5..89dc81780cdd 100644 --- a/Code/Mantid/docs/source/concepts/PeaksWorkspace.rst +++ b/Code/Mantid/docs/source/concepts/PeaksWorkspace.rst @@ -1,12 +1,10 @@ .. _PeaksWorkspace: -PeaksWorkspace -============== +# PeaksWorkspace The PeaksWorkspace is a special Workspace that holds a list of single crystal Peak objects. -Creating a PeaksWorkspace -------------------------- +## Creating a PeaksWorkspace * :ref:`FindPeaksMD ` will find peaks in reciprocal space in a :ref:`MDWorkspace `. * :ref:`FindSXPeaks ` will find peaks in detector space. @@ -15,16 +13,15 @@ Creating a PeaksWorkspace * The :ref:`SaveIsawPeaks ` algorithm will save a PeaksWorkspace to a file. * :ref:`CreatePeaksWorkspace ` will create an empty PeaksWorkspace that you can then edit. -Viewing a PeaksWorkspace ------------------------- +## Viewing a PeaksWorkspace * Double-click a PeaksWorkspace to see the full list of data of each Peak object. * In MantidPlot, you can drag/drop a PeaksWorkspace from the list of workspaces onto the `Instrument View `__ . This will overlay the peaks onto the detector face. -* Right-click a PeaksWorkspace and select the menu to show the peak positions in 3D in the `VatesSimpleInterface `__ . +* Right-click a PeaksWorkspace and select the menu to show the peak positions in 3D in the `VatesSimpleInterface `__ * In paraview, you can load a .Peaks file loader plugin to view a PeaksWorkspace. +* `PeaksViewer ` in the `SliceViewer ` -The Peak Object ---------------- +## The Peak Object Each peak object contains several pieces of information. Not all of them are necessary: @@ -34,14 +31,24 @@ Each peak object contains several pieces of information. Not all of them are nec * Goniometer rotation matrix (for finding Q in the sample frame) * Integrated intensity and error (optional) * Row/column of detector (only for :ref:`RectangularDetectors ` ) +* An integration shape (see below) -Using PeaksWorkspace's in Python --------------------------------- +### The Peak Shape + +Each Peak object contains a PeakShape. Only the integration algorithms which act on, and return PeaksWorkspaces set the shape of the peaks. The PeakShape is owned by the Peak, not the PeaksWorkspace, so when PeaksWorkspaces are split, or concatinated, the integration shapes are unaltered. Aside from the Null Peak Shape, each peak shape contains at least the following information. + +* The algorithm used to perform the integration +* The version of the algorithm used to perform the integration +* The frame in which the integration has been performed + +Subtypes of PeakShape will then provide additional information. For example PeakShapeSpherical provides the radius as well as background inner, and background outer radius. + + +## Using PeaksWorkspace's in Python The PeaksWorkspace and Peak objects are exposed to python. -PeaksWorkspace Python Interface -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +### PeaksWorkspace Python Interface .. code-block:: python @@ -50,8 +57,7 @@ PeaksWorkspace Python Interface p = pws.getPeak(12) pws.removePeak(34) -Peak Python Interface -~~~~~~~~~~~~~~~~~~~~~ +### Peak Python Interface You can get a handle to an existing peak with: @@ -64,7 +70,7 @@ Or you can create a new peak in this way: .. code-block:: python qlab = V3D(1.23, 3.45, 2.22) # Q in the lab frame of the peak - detector_distance = 2.5 # sample-detector distance in meters + detector_distance = 2.5 # sample-detector distance in meters. Detector distances are optional. Calculated in not provided. p = pws.createPeak(qlab, detector_distance) # The peak can later be added to the workspace pws.addPeak(p) @@ -89,4 +95,4 @@ Once you have a handle on a peak "p" you have several methods to query/modify it d = p.getDSpacing() -.. categories:: Concepts \ No newline at end of file +.. categories:: Concepts From 75e3198467c4649136b85a333b04beef25e7dd2e Mon Sep 17 00:00:00 2001 From: Owen Arnold Date: Thu, 19 Feb 2015 14:39:29 +0000 Subject: [PATCH 303/414] Update PeaksWorkspace.rst Fix to rst --- .../docs/source/concepts/PeaksWorkspace.rst | 29 ++++++++++++------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/Code/Mantid/docs/source/concepts/PeaksWorkspace.rst b/Code/Mantid/docs/source/concepts/PeaksWorkspace.rst index 89dc81780cdd..e6a32575ab9a 100644 --- a/Code/Mantid/docs/source/concepts/PeaksWorkspace.rst +++ b/Code/Mantid/docs/source/concepts/PeaksWorkspace.rst @@ -1,10 +1,10 @@ -.. _PeaksWorkspace: - -# PeaksWorkspace +PeaksWorkspace +=============== The PeaksWorkspace is a special Workspace that holds a list of single crystal Peak objects. -## Creating a PeaksWorkspace +Creating a PeaksWorkspace +-------------------------- * :ref:`FindPeaksMD ` will find peaks in reciprocal space in a :ref:`MDWorkspace `. * :ref:`FindSXPeaks ` will find peaks in detector space. @@ -13,15 +13,17 @@ The PeaksWorkspace is a special Workspace that holds a list of single crystal Pe * The :ref:`SaveIsawPeaks ` algorithm will save a PeaksWorkspace to a file. * :ref:`CreatePeaksWorkspace ` will create an empty PeaksWorkspace that you can then edit. -## Viewing a PeaksWorkspace +Viewing a PeaksWorkspace +-------------------------- * Double-click a PeaksWorkspace to see the full list of data of each Peak object. * In MantidPlot, you can drag/drop a PeaksWorkspace from the list of workspaces onto the `Instrument View `__ . This will overlay the peaks onto the detector face. * Right-click a PeaksWorkspace and select the menu to show the peak positions in 3D in the `VatesSimpleInterface `__ * In paraview, you can load a .Peaks file loader plugin to view a PeaksWorkspace. -* `PeaksViewer ` in the `SliceViewer ` +* `PeaksViewer `__ in the `SliceViewer `__ -## The Peak Object +The Peak Object +-------------------------- Each peak object contains several pieces of information. Not all of them are necessary: @@ -33,7 +35,8 @@ Each peak object contains several pieces of information. Not all of them are nec * Row/column of detector (only for :ref:`RectangularDetectors ` ) * An integration shape (see below) -### The Peak Shape +The Peak Shape +~~~~~~~~~~~~~~~ Each Peak object contains a PeakShape. Only the integration algorithms which act on, and return PeaksWorkspaces set the shape of the peaks. The PeakShape is owned by the Peak, not the PeaksWorkspace, so when PeaksWorkspaces are split, or concatinated, the integration shapes are unaltered. Aside from the Null Peak Shape, each peak shape contains at least the following information. @@ -44,11 +47,13 @@ Each Peak object contains a PeakShape. Only the integration algorithms which act Subtypes of PeakShape will then provide additional information. For example PeakShapeSpherical provides the radius as well as background inner, and background outer radius. -## Using PeaksWorkspace's in Python +Using PeaksWorkspaces in Python +--------------------------------- The PeaksWorkspace and Peak objects are exposed to python. -### PeaksWorkspace Python Interface +PeaksWorkspace Python Interface +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code-block:: python @@ -57,7 +62,8 @@ The PeaksWorkspace and Peak objects are exposed to python. p = pws.getPeak(12) pws.removePeak(34) -### Peak Python Interface +Peak Python Interface +~~~~~~~~~~~~~~~~~~~~~ You can get a handle to an existing peak with: @@ -93,6 +99,7 @@ Once you have a handle on a peak "p" you have several methods to query/modify it wl = p.getWavelength() tof = p.getTOF() d = p.getDSpacing() + shape = p.getPeakShape() .. categories:: Concepts From c56479857497741439c18f4b1ade78ba92e92435 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Thu, 19 Feb 2015 14:43:37 +0000 Subject: [PATCH 304/414] Add informative comment block to ObjCompAssemblyActor --- .../InstrumentWidget/ObjCompAssemblyActor.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjCompAssemblyActor.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjCompAssemblyActor.cpp index 12ca86abf272..c812be286cb0 100644 --- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjCompAssemblyActor.cpp +++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjCompAssemblyActor.cpp @@ -117,6 +117,19 @@ void ObjCompAssemblyActor::generateTexture(unsigned char* data, unsigned int& id GLint texParam = GL_NEAREST; glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); OpenGLError::check("TexObject::generateTexture()[set data] "); + /* If the above call to glTexImage2D has generated an error, it is likely as a result + * of outline="yes" being set in the IDF. If this is enabled then the texture above + * is generated with a width being equal to the number of points that make up the + * outline. However, some OpenGL implementations only support textures with a 2^n size. + * On the machines tested (Ubuntu 14.04, Windows 7, and RHEL6), this was not an issue, + * but we can't guarantee that a user wont try this on a system that doesn't support + * non power of 2 textures. In that case, the best thing to do would be to create a + * texture with a width of the next 2^n up, and adjust the texture coordinates + * accordingly. However, this is not a trivial change to make, and as far as we can tell + * no one has ever run into this issue, so it's being left for now. If this does prove + * problematic in the future, hopefully this note will save you some time figuring out + * the problem. + */ glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,texParam); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,texParam); OpenGLError::check("TexObject::generateTexture()[parameters] "); From f8445a1425781d236267bdb586e2cc33d4897c37 Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Thu, 19 Feb 2015 15:57:21 +0100 Subject: [PATCH 305/414] Refs #11104. Adding special case code for BackToBackExponential BackToBackExponential already has an intensity parameter, so the methods are overriden to get/set this parameter. --- .../BackToBackExponential.h | 4 ++++ .../test/BackToBackExponentialTest.h | 19 +++++++++++++++++++ .../test/IPeakFunctionIntensityTest.h | 1 - 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/BackToBackExponential.h b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/BackToBackExponential.h index 1feb4dcec305..103d8679b413 100644 --- a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/BackToBackExponential.h +++ b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/BackToBackExponential.h @@ -61,6 +61,10 @@ class DLLExport BackToBackExponential : public API::IPeakFunction { virtual void setHeight(const double h); virtual double fwhm() const; virtual void setFwhm(const double w); + virtual double intensity() const { return getParameter("I"); } + virtual void setIntensity(const double newIntensity) { + setParameter("I", newIntensity); + } /// overwrite IFunction base class methods std::string name() const { return "BackToBackExponential"; } diff --git a/Code/Mantid/Framework/CurveFitting/test/BackToBackExponentialTest.h b/Code/Mantid/Framework/CurveFitting/test/BackToBackExponentialTest.h index ab520925e308..31d564cca1f8 100644 --- a/Code/Mantid/Framework/CurveFitting/test/BackToBackExponentialTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/BackToBackExponentialTest.h @@ -185,6 +185,25 @@ class BackToBackExponentialTest : public CxxTest::TestSuite } } + void testIntensity() + { + const double s = 4.0; + const double I = 2.1; + BackToBackExponential b2bExp; + b2bExp.initialize(); + b2bExp.setParameter("I", I); + b2bExp.setParameter("A", 6.0);// large A and B make + b2bExp.setParameter("B", 6.0);// the exponentials narrow + b2bExp.setParameter("X0",0.0); + b2bExp.setParameter("S", s); + + TS_ASSERT_EQUALS(b2bExp.intensity(), 2.1); + TS_ASSERT_THROWS_NOTHING(b2bExp.setIntensity(3.0)); + + TS_ASSERT_EQUALS(b2bExp.intensity(), 3.0); + TS_ASSERT_EQUALS(b2bExp.getParameter("I"), 3.0); + } + }; diff --git a/Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h b/Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h index ade73e302e1c..513f22227ae1 100644 --- a/Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h @@ -31,7 +31,6 @@ class IPeakFunctionIntensityTest : public CxxTest::TestSuite { IPeakFunctionIntensityTest() : m_blackList() { FrameworkManager::Instance(); - m_blackList.insert("BackToBackExponential"); m_blackList.insert("DeltaFunction"); m_blackList.insert("ElasticDiffRotDiscreteCircle"); m_blackList.insert("ElasticDiffSphere"); From 700f6b7e98609573b304db80d8ba1d3f1ba654e9 Mon Sep 17 00:00:00 2001 From: Steven Hahn Date: Thu, 19 Feb 2015 10:12:17 -0500 Subject: [PATCH 306/414] Refs #11130. Add missing header to InternetHelper.h --- Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h b/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h index f655d8bb1739..88d2df21fa57 100644 --- a/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h +++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h @@ -5,6 +5,7 @@ #include "MantidKernel/DllConfig.h" #include "MantidKernel/ProxyInfo.h" +#include #include namespace Poco { From 978f39c703a628de2bcde1966aeade2ed07547aa Mon Sep 17 00:00:00 2001 From: Wenduo Zhou Date: Thu, 19 Feb 2015 10:14:40 -0500 Subject: [PATCH 307/414] Cleaned up some issues in doc. Refs #11112. --- .../algorithms/GenerateEventsFilter-v1.rst | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/Code/Mantid/docs/source/algorithms/GenerateEventsFilter-v1.rst b/Code/Mantid/docs/source/algorithms/GenerateEventsFilter-v1.rst index a97a47ec8c31..207d22da111a 100644 --- a/Code/Mantid/docs/source/algorithms/GenerateEventsFilter-v1.rst +++ b/Code/Mantid/docs/source/algorithms/GenerateEventsFilter-v1.rst @@ -88,35 +88,34 @@ this algorithm: +/- tolerance\_v. Generate event filters by time -============================== +############################## -Event filters can be created by defining start and stop time and time intervals. -The three input properties used are *StartTime*, *StopTime* and *TimeInterval*. -*TimeInterval* accepts an array of doubles. +Event filters can be created by defining start time, stop time and time intervals. +The three input properties for them are *StartTime*, *StopTime* and *TimeInterval*, +respectively. +*TimeInterval* accepts an array of doubles. If the array size is zero, then there will be one and only splitter will be -created from *StartTime* and *StopTime*. - +created from *StartTime* and *StopTime*. If the size of the array is one, then all event splitters will have the same duration of time. - In general if the array is composed as :math:`t_1, t_2, \cdots, t_n`, and :math:`T_0` is the run start time, then the event splitters will have the time boudaries as -.. math:: (T_0, T_0+t_1), (T_0+t_1, T_0+t_1+t_2), \cdots, (T_0+\sum_{i=1}^(n-1)t_i, T_0+\sum_{i=1}^nt_i), (T_0+\sum_{i=1}^nt_i, T_0+\sum_{i=1}^nt_i+t_1), \cdots +.. math:: (T_0, T_0+t_1), (T_0+t_1, T_0+t_1+t_2), \cdots, (T_0+\sum_{i=1}^{n-1}t_i, T_0+\sum_{i=1}^nt_i), (T_0+\sum_{i=1}^nt_i, T_0+\sum_{i=1}^nt_i+t_1), \cdots until the stop time is reached. Unit of time -############ +============ There are three types of units that are supported for time. They are second, nanosecond and percentage of duration from *StartTime* to *StopTime*. Generate event filters by sample log value -========================================== +########################################## The sample log will be divided to intervals as :math:`v_0, v_1, \cdots, v_{i-1}, v_i, v_{i+1}, \cdots`. All log entries, whose values falls into range :math:`[v_j, v_{j+1})`, will be assigned to @@ -124,7 +123,7 @@ a same workspace group. About how log value is recorded -############################### +=============================== SNS DAS records log values upon its changing. The frequency of log sampling is significantly faster than change of the log, i.e., sample @@ -134,7 +133,7 @@ log value changes as step functions. The option to do interpolation is not supported at this moment. Comparison to FilterByLogValue -############################## +============================== 1. If the first log value is within the specified range and the first log time is after run star time, FilterByLogValue assumes that the log From 9f9d3325a75ff296367fcd017a438f37566163a2 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Thu, 19 Feb 2015 16:09:21 +0000 Subject: [PATCH 308/414] Add NumDeriv=true for composite functions within MultiDOmainFunction Refs #11133 --- Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py index 35fab8fc8043..9d685e82b11b 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py +++ b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py @@ -301,8 +301,8 @@ def furyfitMult(inputWS, function, ftype, startx, endx, spec_min=0, spec_max=Non def createFuryMultiDomainFunction(function, input_ws): - multi= 'composite=MultiDomainFunction,NumDeriv=1;' - comp = '(composite=CompositeFunction,$domains=i;' + function + ');' + multi= 'composite=MultiDomainFunction,NumDeriv=true;' + comp = '(composite=CompositeFunction,NumDeriv=true,$domains=i;' + function + ');' ties = [] kwargs = {} @@ -314,7 +314,7 @@ def createFuryMultiDomainFunction(function, input_ws): if i > 0: kwargs['InputWorkspace_' + str(i)] = input_ws - #tie beta for every spectrum + #tie beta for every spectrum tie = 'f%d.f1.Beta=f0.f1.Beta' % i ties.append(tie) From 1f6235982a725df20f6954f429fd396049eb73c0 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Thu, 19 Feb 2015 16:34:40 +0000 Subject: [PATCH 309/414] Fix some issues with the Windows build script * CMake path is set once * Backslash chars are removed from the data search paths before addition to properties file. * Package uninstall happens regardless of exit status. Refs #10870 [skip ci] --- Code/Mantid/Build/Jenkins/buildscript.bat | 39 +++++++++++++---------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript.bat b/Code/Mantid/Build/Jenkins/buildscript.bat index 4071a94f1472..ce0d2ca69f03 100755 --- a/Code/Mantid/Build/Jenkins/buildscript.bat +++ b/Code/Mantid/Build/Jenkins/buildscript.bat @@ -1,4 +1,4 @@ -setlocal enbaleextensions enabledelayedexpansion +setlocal enableextensions enabledelayedexpansion ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: WINDOWS SCRIPT TO DRIVE THE JENKINS BUILDS OF MANTID. :: @@ -7,8 +7,8 @@ setlocal enbaleextensions enabledelayedexpansion :: WORKSPACE & JOB_NAME are environment variables that are set by Jenkins. :: BUILD_THREADS & PARAVIEW_DIR should be set in the configuration of each slave. ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: - -"C:\Program Files (x86)\CMake 2.8\bin\cmake.exe" --version +set CMAKE_BIN_DIR=C:\Program Files (x86)\CMake 2.8\bin +"%CMAKE_BIN_DIR%\cmake.exe" --version echo %sha1% ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: @@ -53,7 +53,7 @@ if not "%JOB_NAME%" == "%JOB_NAME:pull_requests=%" ( :: Packaging options ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: set PACKAGE_DOCS= -if "%BUILDPKG%" EQU "yes" ( +if "%BUILDPKG%" == "yes" ( set PACKAGE_DOCS=-DPACKAGE_DOCS=ON ) @@ -92,7 +92,7 @@ set PATH=%WORKSPACE%\Code\Third_Party\lib\win64;%WORKSPACE%\Code\Third_Party\lib ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: CMake configuration ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -"C:\Program Files (x86)\CMake 2.8\bin\cmake.exe" -G "Visual Studio 11 Win64" -DCONSOLE=OFF -DENABLE_CPACK=ON -DMAKE_VATES=ON -DParaView_DIR=%PARAVIEW_DIR% -DMANTID_DATA_STORE=%MANTID_DATA_STORE% -DUSE_PRECOMPILED_HEADERS=ON %PACKAGE_DOCS% ..\Code\Mantid +"%CMAKE_BIN_DIR%\cmake.exe" -G "Visual Studio 11 Win64" -DCONSOLE=OFF -DENABLE_CPACK=ON -DMAKE_VATES=ON -DParaView_DIR=%PARAVIEW_DIR% -DMANTID_DATA_STORE=!MANTID_DATA_STORE! -DUSE_PRECOMPILED_HEADERS=ON %PACKAGE_DOCS% ..\Code\Mantid if ERRORLEVEL 1 exit /B %ERRORLEVEL% ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: @@ -104,16 +104,17 @@ if ERRORLEVEL 1 exit /B %ERRORLEVEL% ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Run the tests ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -# Remove the user properties file just in case anything polluted it +:: Remove the user properties file just in case anything polluted it set USERPROPS=bin\%BUILD_CONFIG%\Mantid.user.properties del %USERPROPS% -"C:\Program Files (x86)\CMake 2.8\bin\ctest.exe" -C %BUILD_CONFIG% -j%BUILD_THREADS% --schedule-random --output-on-failure +"%CMAKE_BIN_DIR%\ctest.exe" -C %BUILD_CONFIG% -j%BUILD_THREADS% --schedule-random --output-on-failure if ERRORLEVEL 1 exit /B %ERRORLEVEL% ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Create the install kit if required ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -if "%BUILDPKG%" EQU "yes" ( +if "%BUILDPKG%" == "yes" ( + echo Building package :: Build offline documentation msbuild /nologo /nr:false /p:Configuration=%BUILD_CONFIG% docs/docs-qthelp.vcxproj @@ -121,7 +122,7 @@ if "%BUILDPKG%" EQU "yes" ( :: It always marks the build as a failure even thought the MantidPlot exit :: code is correct! ::if ERRORLEVEL 1 exit /B %ERRORLEVEL% - cpack -C %BUILD_CONFIG% --config CPackConfig.cmake + "%CMAKE_BIN_DIR%\cpack.exe" -C %BUILD_CONFIG% --config CPackConfig.cmake ) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: @@ -130,20 +131,26 @@ if "%BUILDPKG%" EQU "yes" ( ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: if not "%JOB_NAME%"=="%JOB_NAME:pull_requests=%" ( :: Install package - python %WORKSPACE%\Code\Mantid\Testing\SystemTests\scripts\mantidinstaller.py install %WORKSPACE%\build - cd %WORKSPACE%\build\docs - ::Remove user properties, disable instrument updating & usage reports + set SYSTEMTESTS_DIR=%WORKSPACE%\Code\Mantid\Testing\SystemTests + python !SYSTEMTESTS_DIR!\scripts\mantidinstaller.py install %WORKSPACE%\build + + ::Remove user properties, disable instrument updating & usage reports and add data paths del /Q C:\MantidInstall\bin\Mantid.user.properties echo UpdateInstrumentDefinitions.OnStartup = 0 > C:\MantidInstall\bin\Mantid.user.properties echo usagereports.enabled = 0 >> C:\MantidInstall\bin\Mantid.user.properties - set DATA_ROOT=%WORKSPACE%\build\ExternalData\Testing\Data - echo datasearch.directories = !DATA_ROOT!\UnitTest;!DATA_ROOT!\DocTest;%WORKSPACE%\Code\Mantid\instrument >> C:\MantidInstall\bin\Mantid.user.properties + :: User properties file cannot contain backslash characters + set WORKSPACE_UNIX_STYLE=%WORKSPACE:\=/% + set DATA_ROOT=!WORKSPACE_UNIX_STYLE!/build/ExternalData/Testing/Data + echo datasearch.directories = !DATA_ROOT!/UnitTest;!DATA_ROOT!/DocTest;!WORKSPACE_UNIX_STYLE!/Code/Mantid/instrument >> C:\MantidInstall\bin\Mantid.user.properties + :: Run tests + cd %WORKSPACE%\build\docs C:\MantidInstall\bin\MantidPlot.exe -xq runsphinx_doctest.py set RETCODE=!ERRORLEVEL! - :: Remove + + :: Remove Mantid cd %WORKSPACE%\build - python %WORKSPACE%\Code\Mantid\Testing\SystemTests\scripts\mantidinstaller.py uninstall %WORKSPACE%\build + python !SYSTEMTESTS_DIR!\scripts\mantidinstaller.py uninstall %WORKSPACE%\build if !RETCODE! NEQ 0 exit /B 1 ) From 979fd658b19d44a9cc98230f210f1f919feba238 Mon Sep 17 00:00:00 2001 From: Steven Hahn Date: Thu, 19 Feb 2015 12:13:55 -0500 Subject: [PATCH 310/414] Refs #11136. Change how clang build is determined --- Code/Mantid/Build/Jenkins/buildscript | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript b/Code/Mantid/Build/Jenkins/buildscript index 61417dc99d96..b4fd6334244c 100755 --- a/Code/Mantid/Build/Jenkins/buildscript +++ b/Code/Mantid/Build/Jenkins/buildscript @@ -15,7 +15,18 @@ cmake --version echo "SHA1=${sha1}" -if [[ ${JOB_NAME} == *clang* ]]; then + +#determine if we are using the clang compiler. +#true if *clang* is in the jobname or if we are on a mac without icpc +if ! command -v icpc 2>/dev/null 1>&2 && [[ $(uname) = 'Darwin' ]] ; then + export USE_CLANG=true +elif [[ ${JOB_NAME} == *clang* ]]; then + export USE_CLANG=true +else + export USE_CLANG=false +fi + +if [["$USE_CLANG" == "true"]]; then # Assuming we are using the clang compiler echo "Using clang/llvm compiler." clang --version @@ -35,7 +46,7 @@ fi ############################################################################### # OS X 10.8 setup steps ############################################################################### -if [[ $(uname) == 'Darwin' ]] && [[ ${JOB_NAME} != *clang* ]]; then +if [[ $(uname) == 'Darwin' ]] && [[ "$USE_CLANG" == "false" ]]; then # Assuming we are using the Intel compiler cd $WORKSPACE/Code ./fetch_Third_Party.sh From 831630222215beb77ec2531271792ed1988a0db5 Mon Sep 17 00:00:00 2001 From: Steven Hahn Date: Thu, 19 Feb 2015 13:03:06 -0500 Subject: [PATCH 311/414] Refs #11117. Add PocoVersion.h to .gitignore. --- Code/Mantid/Framework/Kernel/src/.gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/Kernel/src/.gitignore b/Code/Mantid/Framework/Kernel/src/.gitignore index a81090024ef7..a6ab44e00db2 100644 --- a/Code/Mantid/Framework/Kernel/src/.gitignore +++ b/Code/Mantid/Framework/Kernel/src/.gitignore @@ -1,2 +1,3 @@ MantidVersion.cpp -ParaViewVersion.cpp \ No newline at end of file +PocoVersion.h +ParaViewVersion.cpp From ee1e6ddd59c519712fad6cd526c2433fdee84e41 Mon Sep 17 00:00:00 2001 From: Steven Hahn Date: Thu, 19 Feb 2015 13:39:35 -0500 Subject: [PATCH 312/414] Refs #11132. fix boost linking errors. --- Code/Mantid/Framework/API/test/PeakTransformHKLTest.h | 10 ++++++++++ .../Mantid/Framework/API/test/PeakTransformQLabTest.h | 10 ++++++++++ .../Framework/API/test/PeakTransformQSampleTest.h | 11 +++++++++++ 3 files changed, 31 insertions(+) diff --git a/Code/Mantid/Framework/API/test/PeakTransformHKLTest.h b/Code/Mantid/Framework/API/test/PeakTransformHKLTest.h index f726f3355326..20a99d8feac7 100644 --- a/Code/Mantid/Framework/API/test/PeakTransformHKLTest.h +++ b/Code/Mantid/Framework/API/test/PeakTransformHKLTest.h @@ -10,6 +10,16 @@ using namespace Mantid::API; using Mantid::Kernel::V3D; using namespace testing; +namespace boost{ + template + std::basic_ostream& operator<<(std::basic_ostream& out, optional const& maybe) + { + if (maybe) + out << maybe; + return out; + } +} + class PeakTransformHKLTest : public CxxTest::TestSuite { public: diff --git a/Code/Mantid/Framework/API/test/PeakTransformQLabTest.h b/Code/Mantid/Framework/API/test/PeakTransformQLabTest.h index b3184387f832..849824ad26cc 100644 --- a/Code/Mantid/Framework/API/test/PeakTransformQLabTest.h +++ b/Code/Mantid/Framework/API/test/PeakTransformQLabTest.h @@ -11,6 +11,16 @@ using namespace Mantid; using Mantid::Kernel::V3D; using namespace testing; +namespace boost{ + template + std::basic_ostream& operator<<(std::basic_ostream& out, optional const& maybe) + { + if (maybe) + out << maybe; + return out; + } +} + class PeakTransformQLabTest : public CxxTest::TestSuite { diff --git a/Code/Mantid/Framework/API/test/PeakTransformQSampleTest.h b/Code/Mantid/Framework/API/test/PeakTransformQSampleTest.h index f3d01c140557..9e970ba1b51a 100644 --- a/Code/Mantid/Framework/API/test/PeakTransformQSampleTest.h +++ b/Code/Mantid/Framework/API/test/PeakTransformQSampleTest.h @@ -11,6 +11,17 @@ using namespace Mantid; using Mantid::Kernel::V3D; using namespace testing; + +namespace boost{ + template + std::basic_ostream& operator<<(std::basic_ostream& out, optional const& maybe) + { + if (maybe) + out << maybe; + return out; + } +} + class PeakTransformQSampleTest : public CxxTest::TestSuite { From bc84bb9fdd03816f1608b8322386c0cbe265a075 Mon Sep 17 00:00:00 2001 From: Pete Peterson Date: Thu, 19 Feb 2015 14:51:31 -0500 Subject: [PATCH 313/414] Re #11136. Reworked if/else logic --- Code/Mantid/Build/Jenkins/buildscript | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/Code/Mantid/Build/Jenkins/buildscript b/Code/Mantid/Build/Jenkins/buildscript index b4fd6334244c..9d5c910eaf46 100755 --- a/Code/Mantid/Build/Jenkins/buildscript +++ b/Code/Mantid/Build/Jenkins/buildscript @@ -16,17 +16,16 @@ cmake --version echo "SHA1=${sha1}" -#determine if we are using the clang compiler. -#true if *clang* is in the jobname or if we are on a mac without icpc -if ! command -v icpc 2>/dev/null 1>&2 && [[ $(uname) = 'Darwin' ]] ; then - export USE_CLANG=true -elif [[ ${JOB_NAME} == *clang* ]]; then - export USE_CLANG=true -else - export USE_CLANG=false +#determine if should use the clang compiler. +if [[ ${JOB_NAME} == *clang* ]]; then + USE_CLANG=true +elif [[ $(uname) == 'Darwin' ]] ; then + if [[ ! $(command -v icpc) ]] ; then + USE_CLANG=true + fi fi -if [["$USE_CLANG" == "true"]]; then +if [[ $USE_CLANG ]]; then # Assuming we are using the clang compiler echo "Using clang/llvm compiler." clang --version @@ -46,7 +45,7 @@ fi ############################################################################### # OS X 10.8 setup steps ############################################################################### -if [[ $(uname) == 'Darwin' ]] && [[ "$USE_CLANG" == "false" ]]; then +if [[ $(uname) == 'Darwin' ]] && [[ ! $USE_CLANG ]]; then # Assuming we are using the Intel compiler cd $WORKSPACE/Code ./fetch_Third_Party.sh From 9cc34613348c555adf21d68526ce79d014c93d1f Mon Sep 17 00:00:00 2001 From: Wenduo Zhou Date: Thu, 19 Feb 2015 16:03:57 -0500 Subject: [PATCH 314/414] Fixed a conflict. Refs #11112. --- Code/Mantid/Framework/Kernel/src/InternetHelper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp index a62084f74ec7..0642b39d799a 100644 --- a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp +++ b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp @@ -142,7 +142,7 @@ int InternetHelper::sendRequestAndProcess(HTTPClientSession &session, std::ostream &responseStream) { // create a request this->createRequest(uri); - session.sendRequest(*m_request) << m_body.str(); + session.sendRequest(*m_request) << m_body; std::istream &rs = session.receiveResponse(*m_response); From eff27e70a8fe964b3288dfa05eec61e45d1de1c4 Mon Sep 17 00:00:00 2001 From: Stuart Campbell Date: Thu, 19 Feb 2015 16:50:16 -0500 Subject: [PATCH 315/414] Use mantidlibs software collection for RHEL7/F20. Added a test for "Maipo" == RHEL7 and "Heisenbug" == Fedora 20 so that they will now also use the mantidlibs scl refs #11137 --- Code/Mantid/Build/CMake/LinuxPackageScripts.cmake | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake b/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake index b3c39effafcc..cafc4f205b0f 100644 --- a/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake +++ b/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake @@ -93,7 +93,9 @@ set ( PRE_UNINSTALL_FILE ${CMAKE_CURRENT_BINARY_DIR}/prerm ) set ( POST_UNINSTALL_FILE ${CMAKE_CURRENT_BINARY_DIR}/postrm ) if ( "${UNIX_DIST}" MATCHES "RedHatEnterprise" OR "${UNIX_DIST}" MATCHES "^Fedora" ) # RHEL/Fedora - if ( "${UNIX_CODENAME}" MATCHES "Santiago" ) # el6 + if ( "${UNIX_CODENAME}" MATCHES "Santiago" OR + "${UNIX_CODENAME}" MATCHES "Maipo" OR + "${UNIX_CODENAME}" MATCHES "Heisenbug" ) set ( WRAPPER_PREFIX "scl enable mantidlibs \"" ) set ( WRAPPER_POSTFIX "\"" ) set ( EXTRA_LDPATH "/usr/lib64/paraview" ) From 97ba4490cfd744d4510a1dcf96441cdb2c574365 Mon Sep 17 00:00:00 2001 From: Martyn Gigg Date: Fri, 16 Jan 2015 13:18:54 +0000 Subject: [PATCH 316/414] Fix rpm for Fedora >= 18 and RHEL >= 7 The rpm command is now more strict on these systems and requires the package not to own system directories Refs #10911 --- Code/Mantid/Build/CMake/LinuxPackageScripts.cmake | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake b/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake index cafc4f205b0f..097cc466fbbc 100644 --- a/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake +++ b/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake @@ -22,6 +22,10 @@ endif() set ( CMAKE_INSTALL_RPATH ${CMAKE_INSTALL_PREFIX}/${LIB_DIR};${CMAKE_INSTALL_PREFIX}/${PLUGINS_DIR};${CMAKE_INSTALL_PREFIX}/${PVPLUGINS_DIR} ) +# Tell rpm that this package does not own /opt /usr/share/{applications,pixmaps} +# Required for Fedora >= 18 and RHEL >= 7 +set ( CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION /opt /usr/share/applications /usr/share/pixmaps ) + ########################################################################### # LD_PRELOAD TCMalloc ########################################################################### From 0e65a1864e18e0207f903ede2b4c810da425b715 Mon Sep 17 00:00:00 2001 From: Stuart Campbell Date: Thu, 19 Feb 2015 19:21:29 -0500 Subject: [PATCH 317/414] Removed Fedora 20 use of software collection. There seems to be some issues with the newer versions of scl that are shipped with Fedora 20/21. For the moment I am removing the F20 check so that this will only use the software collection for RHEL6/7. refs #11137 --- Code/Mantid/Build/CMake/LinuxPackageScripts.cmake | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake b/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake index 097cc466fbbc..760ecee5a349 100644 --- a/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake +++ b/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake @@ -98,8 +98,7 @@ set ( POST_UNINSTALL_FILE ${CMAKE_CURRENT_BINARY_DIR}/postrm ) if ( "${UNIX_DIST}" MATCHES "RedHatEnterprise" OR "${UNIX_DIST}" MATCHES "^Fedora" ) # RHEL/Fedora if ( "${UNIX_CODENAME}" MATCHES "Santiago" OR - "${UNIX_CODENAME}" MATCHES "Maipo" OR - "${UNIX_CODENAME}" MATCHES "Heisenbug" ) + "${UNIX_CODENAME}" MATCHES "Maipo" ) set ( WRAPPER_PREFIX "scl enable mantidlibs \"" ) set ( WRAPPER_POSTFIX "\"" ) set ( EXTRA_LDPATH "/usr/lib64/paraview" ) From 02c4ff69c586d8b8919e70d46ea26fdded554c73 Mon Sep 17 00:00:00 2001 From: Andrei Savici Date: Thu, 19 Feb 2015 19:41:40 -0500 Subject: [PATCH 318/414] Some pylint warnings. Refs #11134 --- .../plugins/algorithms/BASISReduction.py | 6 +- .../plugins/algorithms/BASISReduction311.py | 25 ++--- .../algorithms/CalculateSampleTransmission.py | 1 + .../CalibrateRectangularDetectors.py | 17 ++-- .../plugins/algorithms/CheckForSampleLogs.py | 5 +- .../plugins/algorithms/ConjoinFiles.py | 67 +------------ .../plugins/algorithms/ConjoinSpectra.py | 1 + .../algorithms/ConvertSnsRoiFileToMask.py | 5 +- .../plugins/algorithms/CorrectLogTimes.py | 2 +- .../algorithms/CreateEmptyTableWorkspace.py | 1 + .../algorithms/CreateLeBailFitInput.py | 13 +-- .../plugins/algorithms/DSFinterp.py | 31 +++--- .../plugins/algorithms/DakotaChiSquared.py | 11 ++- .../plugins/algorithms/EnginXCalibrate.py | 14 ++- .../plugins/algorithms/EnginXCalibrateFull.py | 7 +- .../plugins/algorithms/EnginXFitPeaks.py | 12 +-- .../plugins/algorithms/EnginXFocus.py | 7 +- .../algorithms/ExaminePowderDiffProfile.py | 28 +++--- .../plugins/algorithms/Examples/Squares.py | 1 + .../plugins/algorithms/ExportExperimentLog.py | 19 ++-- .../algorithms/ExportSampleLogsToCSVFile.py | 5 +- .../plugins/algorithms/FilterLogByTime.py | 1 + .../algorithms/FindReflectometryLines.py | 1 + .../GenerateGroupingSNSInelastic.py | 1 + .../plugins/algorithms/GetEiMonDet.py | 1 + .../plugins/algorithms/GetEiT0atSNS.py | 1 + .../algorithms/IndirectTransmission.py | 1 + .../plugins/algorithms/LoadFullprofFile.py | 13 +-- .../algorithms/LoadLogPropertyTable.py | 1 + .../plugins/algorithms/LoadMultipleGSS.py | 1 + .../plugins/algorithms/LoadSINQ.py | 3 +- .../plugins/algorithms/LoadSINQFile.py | 7 +- .../plugins/algorithms/LoadVesuvio.py | 3 +- .../plugins/algorithms/MaskAngle.py | 1 + .../plugins/algorithms/MaskBTP.py | 1 + .../algorithms/MaskWorkspaceToCalFile.py | 20 ++-- .../plugins/algorithms/Mean.py | 1 + .../plugins/algorithms/MergeCalFiles.py | 1 + .../PDDetermineCharacterizations.py | 12 +-- .../plugins/algorithms/PearlMCAbsorption.py | 1 + .../plugins/algorithms/PoldiMerge.py | 1 + .../plugins/algorithms/PoldiProjectAddDir.py | 1 + .../plugins/algorithms/PoldiProjectAddFile.py | 5 +- .../plugins/algorithms/PoldiProjectRun.py | 7 +- .../plugins/algorithms/RefLReduction.py | 51 +++++----- .../algorithms/RefinePowderDiffProfileSeq.py | 43 +++++---- .../plugins/algorithms/RetrieveRunInfo.py | 9 +- .../plugins/algorithms/SANSSubtract.py | 1 + .../algorithms/SANSWideAngleCorrection.py | 8 +- .../plugins/algorithms/SNSPowderReduction.py | 65 ++++++------- .../plugins/algorithms/SaveVulcanGSS.py | 17 ++-- .../algorithms/SelectPowderDiffPeaks.py | 11 ++- .../plugins/algorithms/SortByQVectors.py | 3 +- .../plugins/algorithms/SortDetectors.py | 3 +- .../plugins/algorithms/SortXAxis.py | 1 + .../plugins/algorithms/SuggestTibCNCS.py | 1 + .../plugins/algorithms/SuggestTibHYSPEC.py | 10 +- .../plugins/algorithms/Symmetrise.py | 5 +- .../algorithms/TestWorkspaceGroupProperty.py | 4 +- .../plugins/algorithms/USANSSimulation.py | 3 +- .../UpdatePeakParameterTableValue.py | 4 +- .../plugins/algorithms/VesuvioResolution.py | 5 +- .../plugins/algorithms/ViewBOA.py | 7 +- .../CreateCalibrationWorkspace.py | 15 +-- .../algorithms/WorkflowAlgorithms/CutMD.py | 3 +- .../WorkflowAlgorithms/DensityOfStates.py | 33 +++---- .../EQSANSAzimuthalAverage1D.py | 1 + .../EQSANSDirectBeamTransmission.py | 25 ++--- .../WorkflowAlgorithms/EQSANSNormalise.py | 1 + .../ElasticWindowMultiple.py | 1 + .../algorithms/WorkflowAlgorithms/Fury.py | 9 +- .../WorkflowAlgorithms/FuryFitMultiple.py | 1 + .../WorkflowAlgorithms/HFIRSANSReduction.py | 11 ++- .../IndirectILLReduction.py | 1 + .../WorkflowAlgorithms/IndirectResolution.py | 5 +- .../IndirectTransmissionMonitor.py | 1 + .../InelasticIndirectReduction.py | 7 +- .../algorithms/WorkflowAlgorithms/JumpFit.py | 15 +-- .../MSGDiffractionReduction.py | 6 +- .../algorithms/WorkflowAlgorithms/MolDyn.py | 3 +- .../WorkflowAlgorithms/MuscatData.py | 3 +- .../WorkflowAlgorithms/MuscatFunc.py | 1 + .../NormaliseByThickness.py | 1 + .../OSIRISDiffractionReduction.py | 3 +- .../algorithms/WorkflowAlgorithms/QLines.py | 1 + .../algorithms/WorkflowAlgorithms/Quest.py | 1 + .../WorkflowAlgorithms/REFLReprocess.py | 1 + .../ReactorSANSResolution.py | 1 + .../algorithms/WorkflowAlgorithms/ResNorm.py | 1 + .../WorkflowAlgorithms/SANSAbsoluteScale.py | 3 +- .../SANSAzimuthalAverage1D.py | 5 +- .../SANSBeamSpreaderTransmission.py | 1 + .../SANSDirectBeamTransmission.py | 2 +- .../algorithms/WorkflowAlgorithms/SANSMask.py | 1 + .../WorkflowAlgorithms/SANSReduction.py | 7 +- .../WorkflowAlgorithms/SavePlot1D.py | 3 +- .../WorkflowAlgorithms/SofQWMoments.py | 1 + .../WorkflowAlgorithms/TimeSlice.py | 5 +- .../WorkflowAlgorithms/TransmissionUtils.py | 30 +++--- .../WorkflowAlgorithms/USANSReduction.py | 19 ++-- .../plugins/algorithms/sfCalculator.py | 61 ++++++------ .../plugins/functions/ChudleyElliot.py | 1 + .../plugins/functions/DSFinterp1DFit.py | 3 +- .../functions/Examples/Example1DFunction.py | 1 + .../functions/Examples/ExamplePeakFunction.py | 1 + .../plugins/functions/FickDiffusion.py | 1 + .../plugins/functions/Guinier.py | 1 + .../plugins/functions/GuinierPorod.py | 3 +- .../plugins/functions/HallRoss.py | 1 + .../plugins/functions/Lorentz.py | 1 + .../plugins/functions/Porod.py | 1 + .../plugins/functions/StretchedExpFT.py | 1 + .../plugins/functions/TeixeiraWater.py | 1 + .../Examples/TubeCalibDemoMaps_All.py | 61 ++++++------ .../Examples/TubeCalibDemoMaps_B1.py | 3 +- .../Examples/TubeCalibDemoMaps_C4C3.py | 3 +- .../Examples/TubeCalibDemoMaps_C4C3C2.py | 3 +- .../Examples/TubeCalibDemoMaps_D2.py | 1 + .../TubeCalibDemoMaps_D2_WideMargins.py | 1 + .../Examples/TubeCalibDemoMaps_D4.py | 1 + .../Examples/TubeCalibDemoMerlin.py | 61 ++++++------ .../Examples/TubeCalibDemoMerlin_Simple.py | 3 +- .../Examples/TubeCalibDemoWish0.py | 1 + .../Examples/TubeCalibDemoWish1.py | 1 + .../Examples/TubeCalibDemoWish_5panels.py | 1 + .../Examples/TubeCalibDemoWish_Simple.py | 11 ++- Code/Mantid/scripts/Calibration/tube.py | 3 +- Code/Mantid/scripts/Calibration/tube_calib.py | 5 +- Code/Mantid/scripts/Calibration/tube_spec.py | 1 + .../Mantid/scripts/CrystalTools/PeakReport.py | 1 + Code/Mantid/scripts/DGS_Reduction.py | 2 +- .../Mantid/scripts/Engineering/EnginXUtils.py | 1 + .../scripts/Examples/HRPDDialog_Example.py | 8 +- .../Examples/InstrumentView_Example.py | 1 + .../PlotAsymmetryByLogValue_Example.py | 1 + .../scripts/Examples/SampleLogs_Demo.py | 1 + .../Examples/SimpleMtdCommands_Example.py | 1 + .../scripts/Examples/SolidAngle_Example.py | 1 + Code/Mantid/scripts/Examples/StripPeaks.py | 1 + .../Examples/TableWorkspace_Example.py | 1 + Code/Mantid/scripts/FilterEvents.py | 7 +- .../scripts/FilterEvents/MplFigureCanvas.py | 3 +- .../scripts/FilterEvents/Ui_ErrorMessage.py | 1 + .../scripts/FilterEvents/Ui_MainWindow.py | 1 + .../scripts/FilterEvents/eventFilterGUI.py | 9 +- Code/Mantid/scripts/ISIS_Reflectometry.py | 3 +- .../Inelastic/Direct/CommonFunctions.py | 1 + .../Direct/DirectEnergyConversion.py | 41 ++++---- .../Inelastic/Direct/NonIDF_Properties.py | 1 + .../Inelastic/Direct/PropertiesDescriptors.py | 14 +-- .../Inelastic/Direct/PropertyManager.py | 1 + .../Inelastic/Direct/ReductionHelpers.py | 4 +- .../Inelastic/Direct/ReductionWrapper.py | 6 +- .../scripts/Inelastic/Direct/RunDescriptor.py | 1 + .../scripts/Inelastic/Direct/dgreduce.py | 1 + .../scripts/Inelastic/Direct/diagnostics.py | 18 ++-- .../scripts/Inelastic/IndirectAbsCor.py | 3 +- .../Mantid/scripts/Inelastic/IndirectBayes.py | 35 +++---- .../scripts/Inelastic/IndirectCommon.py | 1 + .../scripts/Inelastic/IndirectDataAnalysis.py | 19 ++-- .../Inelastic/IndirectDiffractionReduction.py | 1 + .../Inelastic/IndirectEnergyConversion.py | 5 +- .../scripts/Inelastic/IndirectMuscat.py | 17 ++-- .../scripts/Inelastic/IndirectNeutron.py | 25 ++--- .../inelastic_indirect_reduction_steps.py | 25 ++--- Code/Mantid/scripts/Inelastic/msg_reducer.py | 4 +- .../Interface/reduction_application.py | 4 +- .../reduction_gui/instruments/interface.py | 1 + .../diffraction_adv_setup_script.py | 21 ++-- .../diffraction_filter_setup_script.py | 3 +- .../diffraction_reduction_script.py | 5 +- .../diffraction_run_setup_script.py | 32 +++---- .../reduction/eqsans_reduction.py | 1 + .../reduction_gui/reduction/hfir_reduction.py | 1 + .../inelastic/dgs_absolute_units_script.py | 1 + .../inelastic/dgs_data_corrections_script.py | 45 ++++----- .../dgs_diagnose_detectors_script.py | 5 +- .../inelastic/dgs_reduction_script.py | 1 + .../inelastic/dgs_sample_data_setup_script.py | 9 +- .../reduction_gui/reduction/output_script.py | 1 + .../reduction/reflectometer/refl_reduction.py | 1 + .../reflectometer/refl_sf_calculator.py | 1 + .../reduction_gui/reduction/sans/data_cat.py | 1 + .../reduction/sans/eqsans_catalog.py | 1 + .../reduction/sans/eqsans_options_script.py | 2 +- .../reduction/sans/hfir_background_script.py | 11 ++- .../reduction/sans/hfir_catalog.py | 1 + .../reduction/sans/hfir_data_proxy.py | 1 + .../reduction/sans/hfir_detector_script.py | 30 +++--- .../reduction/sans/hfir_options_script.py | 8 +- .../reduction/sans/hfir_sample_script.py | 9 +- .../reduction_gui/reduction/scripter.py | 1 + .../reduction_gui/widgets/base_widget.py | 9 +- .../reduction_gui/widgets/cluster_status.py | 1 + .../diffraction/diffraction_adv_setup.py | 5 +- .../diffraction/diffraction_filter_setup.py | 25 ++--- .../diffraction/diffraction_run_setup.py | 23 ++--- .../widgets/inelastic/dgs_absolute_units.py | 1 + .../widgets/inelastic/dgs_data_corrections.py | 1 + .../inelastic/dgs_diagnose_detectors.py | 1 + .../widgets/inelastic/dgs_pd_sc_conversion.py | 1 + .../widgets/inelastic/dgs_sample_setup.py | 7 +- .../widgets/reflectometer/LoadSNSRoi.py | 1 + .../reflectometer/base_ref_reduction.py | 17 ++-- .../launch_peak_back_selection_1d.py | 1 + .../widgets/reflectometer/refl_data_simple.py | 5 +- .../widgets/reflectometer/refl_reduction.py | 3 +- .../reflectometer/refl_sf_calculator.py | 5 +- .../widgets/reflectometer/refm_reduction.py | 5 +- .../widgets/reflectometer/stitcher.py | 11 ++- .../reduction_gui/widgets/sans/eqsans_data.py | 1 + .../widgets/sans/eqsans_instrument.py | 1 + .../widgets/sans/hfir_background.py | 1 + .../widgets/sans/hfir_detector.py | 3 +- .../widgets/sans/hfir_instrument.py | 1 + .../widgets/sans/hfir_sample_data.py | 1 + .../widgets/sans/sans_catalog.py | 3 +- .../reduction_gui/widgets/sans/stitcher.py | 1 + .../diffraction/ui_diffraction_adv_setup.py | 3 +- .../ui_diffraction_filter_setup.py | 3 +- .../ui/diffraction/ui_diffraction_info.py | 3 +- .../diffraction/ui_diffraction_run_setup.py | 5 +- .../ui/diffraction/ui_filter_info.py | 3 +- .../ui/inelastic/ui_dgs_absolute_units.py | 1 + .../ui/inelastic/ui_dgs_data_corrections.py | 1 + .../ui/inelastic/ui_dgs_diagnose_detectors.py | 1 + .../ui/inelastic/ui_dgs_pd_sc_conversion.py | 1 + .../ui/inelastic/ui_dgs_sample_setup.py | 1 + .../ui/reflectometer/refl_choose_col.py | 1 + .../ui/reflectometer/refl_columns.py | 1 + .../Interface/ui/reflectometer/refl_gui.py | 1 + .../ui/reflectometer/refl_gui_run.py | 1 + .../ui/reflectometer/refl_options.py | 1 + .../ui/reflectometer/refl_options_window.py | 1 + .../Interface/ui/reflectometer/refl_save.py | 1 + .../Interface/ui/reflectometer/refl_window.py | 1 + .../ui/reflectometer/ui_data_refl_simple.py | 11 ++- .../ui/reflectometer/ui_refl_sf_calculator.py | 7 +- .../ui/reflectometer/ui_refl_stitching.py | 9 +- .../ui/reflectometer/ui_refm_reduction.py | 9 +- .../Interface/ui/sans/ui_eqsans_info.py | 3 +- .../Interface/ui/sans/ui_eqsans_instrument.py | 5 +- .../ui/sans/ui_eqsans_sample_data.py | 1 + .../Interface/ui/sans/ui_hfir_background.py | 1 + .../Interface/ui/sans/ui_hfir_detector.py | 1 + .../Interface/ui/sans/ui_hfir_instrument.py | 9 +- .../Interface/ui/sans/ui_hfir_sample_data.py | 1 + .../Interface/ui/sans/ui_trans_direct_beam.py | 1 + .../Interface/ui/sans/ui_trans_spreader.py | 1 + .../Interface/ui/ui_cluster_details_dialog.py | 1 + .../scripts/Interface/ui/ui_cluster_status.py | 1 + .../scripts/Interface/ui/ui_data_catalog.py | 1 + .../scripts/Interface/ui/ui_hfir_output.py | 1 + .../Interface/ui/ui_instrument_dialog.py | 1 + .../scripts/Interface/ui/ui_reduction_main.py | 3 +- .../scripts/Interface/ui/ui_stitcher.py | 1 + .../Interface/ui/ui_trans_direct_beam.py | 1 + .../scripts/Interface/ui/ui_trans_spreader.py | 1 + .../LargeScaleStructures/EQSANS_geometry.py | 5 +- .../LargeScaleStructures/REF_L_geometry.py | 2 +- .../LargeScaleStructures/ReflectometerCors.py | 1 + .../LargeScaleStructures/data_stitching.py | 25 +++-- .../LargeScaleStructures/geometry_writer.py | 20 ++-- Code/Mantid/scripts/ORNL_SANS.py | 2 +- .../scripts/Powder_Diffraction_Reduction.py | 1 + Code/Mantid/scripts/PyChop.py | 7 +- Code/Mantid/scripts/PyChop/PyChop.py | 1 + Code/Mantid/scripts/PyChop/PyChopGUI.py | 10 +- Code/Mantid/scripts/PyChop/PyChopUI.py | 1 + Code/Mantid/scripts/PyChop/PyChop_LET_UI.py | 1 + Code/Mantid/scripts/PyChop/fluxGUI.py | 3 +- Code/Mantid/scripts/REFL_Reduction.py | 2 +- Code/Mantid/scripts/REFL_SF_Calculator.py | 2 +- Code/Mantid/scripts/REFM_Reduction.py | 2 +- .../isis_reflectometry/combineMulti.py | 13 +-- .../convert_to_wavelength.py | 1 + .../Reflectometry/isis_reflectometry/l2q.py | 2 +- .../isis_reflectometry/load_live_runs.py | 1 + .../isis_reflectometry/procedures.py | 1 + .../Reflectometry/isis_reflectometry/quick.py | 19 ++-- .../isis_reflectometry/saveModule.py | 1 + .../scripts/SANS/ISISCommandInterface.py | 1 + Code/Mantid/scripts/SANS/SANSBatchMode.py | 1 + Code/Mantid/scripts/SANS/SANSUtility.py | 1 + Code/Mantid/scripts/SANS/SANSadd2.py | 3 +- Code/Mantid/scripts/SANS/centre_finder.py | 5 +- Code/Mantid/scripts/SANS/isis_instrument.py | 1 + Code/Mantid/scripts/SANS/isis_reducer.py | 1 + .../scripts/SANS/isis_reduction_steps.py | 19 ++-- .../scripts/SCD_Reduction/ReduceDictionary.py | 1 + .../scripts/SCD_Reduction/ReduceSCD_OneRun.py | 95 ++++++++++--------- .../SCD_Reduction/ReduceSCD_Parallel.py | 3 +- Code/Mantid/scripts/TofConverter.py | 7 +- .../scripts/TofConverter/Ui_MainWindow.py | 1 + .../scripts/TofConverter/converterGUI.py | 1 + .../scripts/Vates/Diffraction_Workflow.py | 21 ++-- .../scripts/Vates/Inelastic_Workflow.py | 17 ++-- Code/Mantid/scripts/Vates/SXD_NaCl.py | 1 + Code/Mantid/scripts/reducer_singleton.py | 1 + .../scripts/reduction/command_interface.py | 1 + Code/Mantid/scripts/reduction/find_data.py | 1 + .../instruments/example/ExampleRedStep.py | 1 + .../instruments/example/example_reducer.py | 2 +- .../inelastic/direct_command_interface.py | 11 +-- .../inelastic/inelastic_reducer.py | 2 +- .../reflectometer/data_manipulation.py | 7 +- .../instruments/reflectometer/wks_utility.py | 50 +++++----- .../instruments/sans/sans_reducer.py | 10 +- .../instruments/sans/sans_reduction_steps.py | 13 +-- Code/Mantid/scripts/reduction/reducer.py | 1 + .../reduction_workflow/command_interface.py | 1 + .../scripts/reduction_workflow/find_data.py | 1 + .../sans/hfir_command_interface.py | 9 +- .../instruments/sans/hfir_instrument.py | 3 +- .../instruments/sans/sns_command_interface.py | 45 ++++----- .../instruments/sans/sns_instrument.py | 4 +- .../scripts/reduction_workflow/reducer.py | 3 +- 317 files changed, 1207 insertions(+), 1037 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py index da742cdd3d46..17ad01df8e7c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py @@ -1,8 +1,8 @@ +#pylint: disable=no-init import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * from mantid import config -import os MICROEV_TO_MILLIEV = 1000.0 DEFAULT_BINS = [0., 0., 0.] @@ -217,7 +217,7 @@ def _calibData(self, sam_ws, mon_ws): api.MaskDetectors(Workspace=sam_ws, DetectorList=self._dMask) #MaskedWorkspace='BASIS_MASK') - api.ModeratorTzeroLinear(InputWorkspace=sam_ws, + api.ModeratorTzeroLinear(InputWorkspace=sam_ws,\ OutputWorkspace=sam_ws) api.LoadParameterFile(Workspace=sam_ws, Filename=config.getInstrumentDirectory() + 'BASIS_silicon_111_Parameters.xml') @@ -226,7 +226,7 @@ def _calibData(self, sam_ws, mon_ws): Target='Wavelength', EMode='Indirect') if not self._noMonNorm: - api.ModeratorTzeroLinear(InputWorkspace=mon_ws, + api.ModeratorTzeroLinear(InputWorkspace=mon_ws,\ OutputWorkspace=mon_ws) api.Rebin(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Params='10') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py index 2e60dadde08d..63c8e0f525da 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * @@ -33,18 +34,18 @@ def PyInit(self): "Stop monitor normalization") self.declareProperty("NormRunNumbers", "", "Normalization run numbers") arrVal = FloatArrayLengthValidator(2) - self.declareProperty(FloatArrayProperty("NormWavelengthRange", DEFAULT_RANGE, - arrVal, direction=Direction.Input), + self.declareProperty(FloatArrayProperty("NormWavelengthRange", DEFAULT_RANGE,\ + arrVal, direction=Direction.Input),\ "Wavelength range for normalization. default:(6.24A, 6.30A)") self.declareProperty(FloatArrayProperty("EnergyBins", DEFAULT_BINS, - direction=Direction.Input), + direction=Direction.Input),\ "Energy transfer binning scheme (in ueV)") self.declareProperty(FloatArrayProperty("MomentumTransferBins", DEFAULT_BINS, - direction=Direction.Input), + direction=Direction.Input),\ "Momentum transfer binning scheme") - self.declareProperty(FileProperty(name="MaskFile", defaultValue="", - action=FileAction.OptionalLoad, extensions=['.xml']), + self.declareProperty(FileProperty(name="MaskFile", defaultValue="",\ + action=FileAction.OptionalLoad, extensions=['.xml']),\ "Directory location for standard masking and grouping files.") grouping_type = ["None", "Low-Resolution", "By-Tube"] self.declareProperty("GroupDetectors", "None", @@ -100,9 +101,9 @@ def PyExec(self): self._sumRuns(norm_set, self._normWs, self._normMonWs, extra_extension) self._calibData(self._normWs, self._normMonWs) - api.Rebin(InputWorkspace=self._normWs, OutputWorkspace=self._normWs, + api.Rebin(InputWorkspace=self._normWs, OutputWorkspace=self._normWs,\ Params=self._normRange) - api.FindDetectorsOutsideLimits(InputWorkspace=self._normWs, + api.FindDetectorsOutsideLimits(InputWorkspace=self._normWs,\ OutputWorkspace="BASIS_NORM_MASK") self._run_list = self._getRuns(self.getProperty("RunNumbers").value) @@ -116,9 +117,9 @@ def PyExec(self): self._calibData(self._samWs, self._samMonWs) if self._doNorm: - api.MaskDetectors(Workspace=self._samWs, + api.MaskDetectors(Workspace=self._samWs,\ MaskedWorkspace='BASIS_NORM_MASK') - api.Divide(LHSWorkspace=self._samWs, RHSWorkspace=self._normWs, + api.Divide(LHSWorkspace=self._samWs, RHSWorkspace=self._normWs,\ OutputWorkspace=self._samWs) api.ConvertUnits(InputWorkspace=self._samWs, @@ -220,7 +221,7 @@ def _calibData(self, sam_ws, mon_ws): api.MaskDetectors(Workspace=sam_ws, DetectorList=self._dMask) #MaskedWorkspace='BASIS_MASK') - api.ModeratorTzeroLinear(InputWorkspace=sam_ws, + api.ModeratorTzeroLinear(InputWorkspace=sam_ws,\ OutputWorkspace=sam_ws) api.LoadParameterFile(Workspace=sam_ws, Filename=os.path.join(DEFAULT_CONFIG_DIR, 'BASIS_silicon_311_Parameters.xml')) @@ -229,7 +230,7 @@ def _calibData(self, sam_ws, mon_ws): Target='Wavelength', EMode='Indirect') if not self._noMonNorm: - api.ModeratorTzeroLinear(InputWorkspace=mon_ws, + api.ModeratorTzeroLinear(InputWorkspace=mon_ws,\ OutputWorkspace=mon_ws) api.Rebin(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Params='10') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py index c88d3bf4f803..3621eb7fa21e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py index d6aa0ea4000f..c30f020a18b1 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * from mantid.simpleapi import * @@ -64,15 +65,15 @@ def PyInit(self): "Comma delimited d-space positions of reference peaks. Use 1-3 for Cross Correlation. Unlimited for many peaks option.") self.declareProperty("PeakWindowMax", 0., "Maximum window around a peak to search for it. Optional.") - self.declareProperty(ITableWorkspaceProperty("FitwindowTableWorkspace", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(ITableWorkspaceProperty("FitwindowTableWorkspace", "", Direction.Input, PropertyMode.Optional),\ "Name of input table workspace containing the fit window information for each spectrum. ") self.declareProperty("MinimumPeakHeight", 2., "Minimum value allowed for peak height") - self.declareProperty("MinimumPeakHeightObs", 0., + self.declareProperty("MinimumPeakHeightObs", 0.,\ "Minimum value of a peak's maximum observed Y value for this peak to be used to calculate offset.") - self.declareProperty(MatrixWorkspaceProperty("DetectorResolutionWorkspace", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(MatrixWorkspaceProperty("DetectorResolutionWorkspace", "", Direction.Input, PropertyMode.Optional),\ "Name of optional input matrix workspace for each detector's resolution (D(d)/d).") - self.declareProperty(FloatArrayProperty("AllowedResRange", [0.25, 4.0], direction=Direction.Input), + self.declareProperty(FloatArrayProperty("AllowedResRange", [0.25, 4.0], direction=Direction.Input),\ "Range of allowed individual peak's resolution factor to input detector's resolution.") self.declareProperty("PeakFunction", "Gaussian", StringListValidator(["BackToBackExponential", "Gaussian", "Lorentzian"]), @@ -314,7 +315,7 @@ def _cccalibrate(self, wksp, calib): for ws in [str(wksp)+"cc3", str(wksp)+"offset3", str(wksp)+"mask3"]: if AnalysisDataService.doesExist(ws): AnalysisDataService.remove(ws) - (temp, numGroupedSpectra, numGroups) = CreateGroupingWorkspace(InputWorkspace=wksp, GroupDetectorsBy=self._grouping, + (temp, numGroupedSpectra, numGroups) = CreateGroupingWorkspace(InputWorkspace=wksp, GroupDetectorsBy=self._grouping,\ OutputWorkspace=str(wksp)+"group") if (numGroupedSpectra==0) or (numGroups==0): raise RuntimeError("%d spectra will be in %d groups" % (numGroupedSpectra, numGroups)) @@ -363,7 +364,7 @@ def _multicalibrate(self, wksp, calib): if not "histo" in self.getProperty("Extension").value: wksp = Rebin(InputWorkspace=wksp, OutputWorkspace=wksp.name(), Params=str(self._binning[0])+","+str((self._binning[1]))+","+str(self._binning[2])) - (temp, numGroupedSpectra, numGroups) = CreateGroupingWorkspace(InputWorkspace=wksp, GroupDetectorsBy=self._grouping, + (temp, numGroupedSpectra, numGroups) = CreateGroupingWorkspace(InputWorkspace=wksp, GroupDetectorsBy=self._grouping,\ OutputWorkspace=str(wksp)+"group") if (numGroupedSpectra==0) or (numGroups==0): raise RuntimeError("%d spectra will be in %d groups" % (numGroupedSpectra, numGroups)) @@ -386,7 +387,7 @@ def _multicalibrate(self, wksp, calib): reslowf = resrange[0] resupf = resrange[1] if reslowf >= resupf: - raise NotImplementedError("Allowed resolution range factor, lower boundary (%f) must be smaller than upper boundary (%f)." + raise NotImplementedError("Allowed resolution range factor, lower boundary (%f) must be smaller than upper boundary (%f)."\ % (reslowf, resupf)) else: reslowf = 0.0 @@ -436,7 +437,7 @@ def _focus(self, wksp, calib): if wksp is None: return None MaskDetectors(Workspace=wksp, MaskedWorkspace=str(wksp)+"mask") - wksp = AlignDetectors(InputWorkspace=wksp, OutputWorkspace=wksp.name(), + wksp = AlignDetectors(InputWorkspace=wksp, OutputWorkspace=wksp.name(),\ OffsetsWorkspace=str(wksp)+"offset") # Diffraction focusing using new calibration file with offsets if self._diffractionfocus: diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py index bda7c2b9952c..ad5329b501db 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py @@ -1,5 +1,5 @@ +#pylint: disable=invalid-name, no-init from mantid.api import PythonAlgorithm, AlgorithmFactory, WorkspaceProperty -import mantid.simpleapi from mantid.kernel import Direction, logger class CheckForSampleLogs(PythonAlgorithm): @@ -23,7 +23,8 @@ def PyInit(self): """ self.declareProperty(WorkspaceProperty("Workspace", "",Direction.Input), "The workspace to check.") self.declareProperty("LogNames","","Names of the logs to look for") - self.declareProperty("Result","A string that will be empty if all the logs are found, otherwise will contain an error message",Direction.Output) + self.declareProperty("Result","A string that will be empty if all the logs are found, "\ + "otherwise will contain an error message",Direction.Output) return def PyExec(self): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py index 78fa1e54ff87..5870377471bc 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py @@ -1,66 +1 @@ -from mantid.api import * -from mantid.kernel import * -from mantid.simpleapi import * -import os - -class ConjoinFiles(PythonAlgorithm): - def category(self): - return "DataHandling;PythonAlgorithms" - - def name(self): - return "ConjoinFiles" - - def summary(self): - return "Conjoin two file-based workspaces." - - def __load(self, directory, instr, run, loader, exts, wksp): - filename = None - for ext in exts: - filename = "%s_%s%s" % (instr, str(run), ext) - if len(directory) > 0: - filename = os.path.join(directory, filename) - if not os.path.exists(filename): - continue - try: - self.log().information("Trying to load '%s'" % filename) - loader(Filename=filename, OutputWorkspace=wksp) - return - except Exception, e: - logger.information(str(e)) - pass - raise RuntimeError("Failed to load run %s from file %s" % (str(run), filename)) - - def PyInit(self): - greaterThanZero = IntArrayBoundedValidator() - greaterThanZero.setLower(0) - self.declareProperty(IntArrayProperty("RunNumbers",values=[0], validator=greaterThanZero), doc="Run numbers") - self.declareProperty(WorkspaceProperty("OutputWorkspace", "", direction=Direction.Output)) - self.declareProperty(FileProperty("Directory", "", FileAction.OptionalDirectory)) - - def PyExec(self): - # generic stuff for running - wksp = self.getPropertyValue("OutputWorkspace") - runs = self.getProperty("RunNumbers") - instr = config.getInstrument().shortName() - directory = self.getPropertyValue("Directory").strip() - - # change here if you want something other than gsas files - exts = ['.txt', '.gsa'] - loader = LoadGSS - - # load things and conjoin them - first = True - for run in runs.value: - run = str(run) - if first: - self.__load(directory, instr, run, loader, exts, wksp) - first = False - else: - self.__load(directory, instr, run, loader, exts, run) - ConjoinWorkspaces(InputWorkspace1=wksp, InputWorkspace2=run, CheckOverlapping=False) - if mtd.doesExist(run): - DeleteWorkspace(run) - - self.setProperty("OutputWorkspace", mtd[wksp]) - -AlgorithmFactory.subscribe(ConjoinFiles) +#pylint: disable=no-init,invalid-name diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py index f22e38a75532..0213ee542467 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * from mantid.simpleapi import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py index 93301070c0de..5492ba7dd1a0 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi as msapi import mantid.api as api import mantid.kernel as kernel @@ -37,7 +38,7 @@ def PyInit(self): self.declareProperty(api.FileProperty(name="SnsRoiFile", defaultValue="", action=api.FileAction.Load, - extensions=EXTENSIONS), + extensions=EXTENSIONS),\ "SNS reduction ROI file to load.") allowedInstruments = kernel.StringListValidator(INSTRUMENTS) self.declareProperty("Instrument", "", @@ -48,7 +49,7 @@ def PyInit(self): +"file (Optional). Default is _Mask.") self.declareProperty(api.FileProperty(name="OutputDirectory", defaultValue=config['defaultsave.directory'], - action=api.FileAction.Directory), + action=api.FileAction.Directory),\ "Directory to save mask file."\ +" Default is current Mantid save directory.") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py index 2f2478c27b9a..1839dcb61bc9 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py @@ -1,7 +1,7 @@ +#pylint: disable=invalid-name,no-init import mantid.simpleapi import mantid.api import mantid.kernel -import numpy class CorrectLogTimes(mantid.api.PythonAlgorithm): """ Class to shift log times to match proton charge diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py index 162f572d05da..5ed80f5db642 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory from mantid.kernel import Direction diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py index 029a0c8ada2b..d86dce9610f8 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name #from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory, FileProperty, FileAction #from mantid.kernel import Direction, StringListValidator, FloatBoundedValidator @@ -30,28 +31,28 @@ def PyInit(self): #instruments=["POWGEN", "NOMAD", "VULCAN"] #self.declareProperty("Instrument", "POWGEN", StringListValidator(instruments), "Powder diffractometer's name") - self.declareProperty(FileProperty("ReflectionsFile","", FileAction.OptionalLoad, ['.hkl']), + self.declareProperty(FileProperty("ReflectionsFile","", FileAction.OptionalLoad, ['.hkl']),\ "Name of [http://www.ill.eu/sites/fullprof/ Fullprof] .hkl file that contains the peaks.") - self.declareProperty(FileProperty("FullprofParameterFile", "", FileAction.Load, ['.irf']), + self.declareProperty(FileProperty("FullprofParameterFile", "", FileAction.Load, ['.irf']),\ "Fullprof's .irf file containing the peak parameters.") - self.declareProperty("GenerateBraggReflections", False, + self.declareProperty("GenerateBraggReflections", False,\ "Generate Bragg reflections other than reading a Fullprof .irf file. ") arrvalidator = IntArrayBoundedValidator() arrvalidator.setLower(0) - self.declareProperty(IntArrayProperty("MaxHKL", values=[12, 12, 12], validator=arrvalidator, + self.declareProperty(IntArrayProperty("MaxHKL", values=[12, 12, 12], validator=arrvalidator,\ direction=Direction.Input), "Maximum reflection (HKL) to generate") self.declareProperty("Bank", 1, "Bank ID for output if there are more than one bank in .irf file.") self.declareProperty("LatticeConstant", -0.0, validator=FloatBoundedValidator(lower=1.0E-9), doc="Lattice constant for cubic crystal.") - self.declareProperty(ITableWorkspaceProperty("InstrumentParameterWorkspace", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("InstrumentParameterWorkspace", "", Direction.Output),\ "Name of Table Workspace Containing Peak Parameters From .irf File.") - self.declareProperty(ITableWorkspaceProperty("BraggPeakParameterWorkspace", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("BraggPeakParameterWorkspace", "", Direction.Output),\ "Name of Table Workspace Containing Peaks' Miller Indices From .prf File.") return diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py index 9b1e79a6ea00..bd71c1c6e5ac 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py @@ -1,8 +1,8 @@ -from mantid.api import PythonAlgorithm, MatrixWorkspaceProperty, AlgorithmFactory +#pylint: disable=no-init,invalid-name +from mantid.api import PythonAlgorithm, AlgorithmFactory from mantid.simpleapi import CloneWorkspace, mtd -from mantid.kernel import StringListValidator, FloatArrayProperty, FloatArrayLengthValidator, FloatArrayMandatoryValidator, StringArrayProperty, StringArrayMandatoryValidator, Direction, FloatBoundedValidator, logger, EnabledWhenProperty, PropertyCriterion - -from pdb import set_trace as tr +from mantid.kernel import StringListValidator, FloatArrayProperty, FloatArrayMandatoryValidator,\ + StringArrayProperty, StringArrayMandatoryValidator, Direction, logger, EnabledWhenProperty, PropertyCriterion class DSFinterp(PythonAlgorithm): @@ -13,14 +13,18 @@ def name(self): return 'DSFinterp' def summary(self): - return 'Given a set of parameter values {Ti} and corresponding structure factors S(Q,E,Ti), this algorithm interpolates S(Q,E,T) for any value of parameter T within the range spanned by the {Ti} set.' + return 'Given a set of parameter values {Ti} and corresponding structure factors S(Q,E,Ti), this algorithm '\ + 'interpolates S(Q,E,T) for any value of parameter T within the range spanned by the {Ti} set.' def PyInit(self): arrvalidator = StringArrayMandatoryValidator() lrg='Input' - self.declareProperty(StringArrayProperty('Workspaces', values=[], validator=arrvalidator, direction=Direction.Input), doc='list of input workspaces') - self.declareProperty('LoadErrors', True, direction=Direction.Input, doc='Do we load error data contained in the workspaces?') - self.declareProperty(FloatArrayProperty('ParameterValues', values=[], validator=FloatArrayMandatoryValidator(),direction=Direction.Input), doc='list of input parameter values') + self.declareProperty(StringArrayProperty('Workspaces', values=[], validator=arrvalidator,\ + direction=Direction.Input), doc='list of input workspaces') + self.declareProperty('LoadErrors', True, direction=Direction.Input,\ + doc='Do we load error data contained in the workspaces?') + self.declareProperty(FloatArrayProperty('ParameterValues', values=[],\ + validator=FloatArrayMandatoryValidator(),direction=Direction.Input), doc='list of input parameter values') self.setPropertyGroup('Workspaces', lrg) self.setPropertyGroup('LoadErrors', lrg) self.setPropertyGroup('ParameterValues', lrg) @@ -30,7 +34,8 @@ def PyInit(self): self.declareProperty('RegressionWindow', 6, direction=Direction.Input, doc='window size for the running local-regression') self.setPropertySettings("RegressionWindow", condition) regtypes = [ 'linear', 'quadratic'] - self.declareProperty('RegressionType', 'quadratic', StringListValidator(regtypes), direction=Direction.Input, doc='type of local-regression; linear and quadratic are available') + self.declareProperty('RegressionType', 'quadratic', StringListValidator(regtypes),\ + direction=Direction.Input, doc='type of local-regression; linear and quadratic are available') self.setPropertySettings("RegressionType", condition) lrg = 'Running Local Regression Options' self.setPropertyGroup('LocalRegression', lrg) @@ -39,7 +44,8 @@ def PyInit(self): lrg='Output' self.declareProperty(FloatArrayProperty('TargetParameters', values=[], ), doc="Parameters to interpolate the structure factor") - self.declareProperty(StringArrayProperty('OutputWorkspaces', values=[], validator=arrvalidator), doc='list of output workspaces to save the interpolated structure factors') + self.declareProperty(StringArrayProperty('OutputWorkspaces', values=[], validator=arrvalidator),\ + doc='list of output workspaces to save the interpolated structure factors') self.setPropertyGroup('TargetParameters', lrg) self.setPropertyGroup('OutputWorkspaces', lrg) self.channelgroup = None @@ -109,5 +115,6 @@ def PyExec(self): import dsfinterp AlgorithmFactory.subscribe(DSFinterp) except: - logger.debug('Failed to subscribe algorithm DSFinterp; Python package dsfinterp may be missing (https://pypi.python.org/pypi/dsfinterp)') - pass + logger.debug('Failed to subscribe algorithm DSFinterp; Python package dsfinterp'\ + 'may be missing (https://pypi.python.org/pypi/dsfinterp)') + diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py index 1bebb1496bd8..b50f41e1db4e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py @@ -1,5 +1,6 @@ +#pylint: disable=no-init,invalid-name from mantid.api import PythonAlgorithm, AlgorithmFactory,MatrixWorkspaceProperty,PropertyMode -from mantid.kernel import Direction,IntBoundedValidator,FloatBoundedValidator +from mantid.kernel import Direction import mantid.simpleapi import mantid import numpy @@ -46,13 +47,13 @@ def PyExec(self): __w2=mantid.simpleapi.Load(f2) #validate inputs - if (type(__w1)!= mantid.api._api.MatrixWorkspace): + if type(__w1)!= mantid.api.MatrixWorkspace: mantid.kernel.logger.error('Wrong workspace type for data file') raise ValueError( 'Wrong workspace type for data file') - if (type(__w2)!= mantid.api._api.MatrixWorkspace): + if type(__w2)!= mantid.api.MatrixWorkspace: mantid.kernel.logger.error('Wrong workspace type for calculated file') raise ValueError( 'Wrong workspace type for calculated file') - if((__w1.blocksize()!=__w2.blocksize()) or (__w1.getNumberHistograms()!=__w2.getNumberHistograms())): + if __w1.blocksize()!=__w2.blocksize() or __w1.getNumberHistograms()!=__w2.getNumberHistograms(): mantid.kernel.logger.error('The file sizes are different') raise ValueError( 'The file sizes are different') @@ -83,6 +84,6 @@ def PyExec(self): mantid.simpleapi.DeleteWorkspace(__w2.getName()) mantid.simpleapi.DeleteWorkspace(__soe2.getName()) if (len(soeName)==0): - mantid.simpleapi.DeleteWorkspace(__soe.getName()) + mantid.simpleapi.DeleteWorkspace(__soe.getName()) AlgorithmFactory.subscribe(DakotaChiSquared) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py index 4988e37de329..7b7cef59550e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py @@ -1,9 +1,7 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * -import csv -import numpy as np -import math class EnginXCalibrate(PythonAlgorithm): def category(self): @@ -16,21 +14,21 @@ def summary(self): return "Calibrates a detector bank by performing a single peak fitting." def PyInit(self): - self.declareProperty(FileProperty("Filename", "", FileAction.Load), + self.declareProperty(FileProperty("Filename", "", FileAction.Load),\ "Calibration run to use") - self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""), + self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""),\ "A list of dSpacing values where peaks are expected.") self.declareProperty("Bank", 1, "Which bank to calibrate") - self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional),\ "Calibrated detector positions. If not specified, default ones are used.") - self.declareProperty("Difc", 0.0, direction = Direction.Output, + self.declareProperty("Difc", 0.0, direction = Direction.Output,\ doc = "Calibrated Difc value for the bank") - self.declareProperty("Zero", 0.0, direction = Direction.Output, + self.declareProperty("Zero", 0.0, direction = Direction.Output,\ doc = "Calibrated Zero value for the bank") def PyExec(self): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py index 458b633ea3c7..c76292257350 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * import math @@ -13,13 +14,13 @@ def summary(self): return "Calibrates every pixel position by performing single peak fitting." def PyInit(self): - self.declareProperty(FileProperty("Filename", "", FileAction.Load), + self.declareProperty(FileProperty("Filename", "", FileAction.Load),\ "Calibration run to use") - self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Output),\ "A table with the detector IDs and calibrated detector positions in V3P format.") - self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""), + self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""),\ "A list of dSpacing values where peaks are expected.") self.declareProperty("Bank", 1, "Which bank to calibrate") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py index f51adff839a0..96c1ae6844d1 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py @@ -1,8 +1,8 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * import math -import numpy as np class EnginXFitPeaks(PythonAlgorithm): def category(self): @@ -15,21 +15,21 @@ def summary(self): return "The algorithm fits an expected diffraction pattern to a workpace spectrum by performing single peak fits." def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input),\ "Workspace to fit peaks in. ToF is expected X unit.") - self.declareProperty("WorkspaceIndex", 0, + self.declareProperty("WorkspaceIndex", 0,\ "Index of the spectra to fit peaks in") - self.declareProperty(FloatArrayProperty("ExpectedPeaks", (self._getDefaultPeaks())), + self.declareProperty(FloatArrayProperty("ExpectedPeaks", (self._getDefaultPeaks())),\ "A list of dSpacing values to be translated into TOF to find expected peaks.") self.declareProperty(FileProperty(name="ExpectedPeaksFromFile",defaultValue="",action=FileAction.OptionalLoad,extensions = [".csv"]),"Load from file a list of dSpacing values to be translated into TOF to find expected peaks.") - self.declareProperty("Difc", 0.0, direction = Direction.Output, + self.declareProperty("Difc", 0.0, direction = Direction.Output,\ doc = "Fitted Difc value") - self.declareProperty("Zero", 0.0, direction = Direction.Output, + self.declareProperty("Zero", 0.0, direction = Direction.Output,\ doc = "Fitted Zero value") def PyExec(self): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py index 6ee09d8b6e38..79a3c6e19551 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * @@ -12,13 +13,13 @@ def summary(self): return "Focuses a run." def PyInit(self): - self.declareProperty(FileProperty("Filename", "", FileAction.Load), + self.declareProperty(FileProperty("Filename", "", FileAction.Load),\ "Run to focus") - self.declareProperty(WorkspaceProperty("OutputWorkspace", "", Direction.Output), + self.declareProperty(WorkspaceProperty("OutputWorkspace", "", Direction.Output),\ "A workspace with focussed data") - self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional),\ "Calibrated detector positions. If not specified, default ones are used.") self.declareProperty("Bank", 1, "Which bank to focus") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py index a4971cb0a1f4..856b430c91c7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py @@ -1,6 +1,4 @@ -# from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory, FileProperty, FileAction, MatrixWorkspaceProperty, WorkspaceProperty, PropertyMode -# from mantid.kernel import Direction, StringListValidator - +#pylint: disable=no-init import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * @@ -27,9 +25,9 @@ def PyInit(self): """ Declare properties """ # Data file - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, PropertyMode.Optional),\ "Name of data workspace containing the diffraction pattern in .prf file. ") - self.declareProperty(FileProperty("DataFilename","", FileAction.OptionalLoad, ['.dat']), + self.declareProperty(FileProperty("DataFilename","", FileAction.OptionalLoad, ['.dat']),\ "Name of input data file.") self.declareProperty("LoadData", False, "Option to load data other than reading from an existing data workspace.") @@ -37,34 +35,36 @@ def PyInit(self): self.declareProperty("EndX", -0.0, "Maximum x value (TOF) to do the pattern calculation.") # Peak profile type - profiletypes = ["Back-to-back exponential convoluted with PseudoVoigt", "Thermal Neutron Back-to-back exponential convoluted with PseudoVoigt"] - self.declareProperty("ProfileType", "Back-to-back exponential convoluted with PseudoVoigt", StringListValidator(profiletypes), "Type of peak profile.") + profiletypes = ["Back-to-back exponential convoluted with PseudoVoigt", \ + "Thermal Neutron Back-to-back exponential convoluted with PseudoVoigt"] + self.declareProperty("ProfileType", "Back-to-back exponential convoluted with PseudoVoigt",\ + StringListValidator(profiletypes), "Type of peak profile.") # Table workspaces - self.declareProperty(ITableWorkspaceProperty("ProfileWorkspace", "", Direction.InOut), + self.declareProperty(ITableWorkspaceProperty("ProfileWorkspace", "", Direction.InOut),\ "Name of table workspace containing peak parameters as input.") - self.declareProperty(ITableWorkspaceProperty("BraggPeakWorkspace", "", Direction.InOut), + self.declareProperty(ITableWorkspaceProperty("BraggPeakWorkspace", "", Direction.InOut),\ "Name of table workspace containing reflections (bragg peaks) in form of Miller index.") - self.declareProperty(FileProperty("ProfileFilename","", FileAction.OptionalLoad, ['.irf']), + self.declareProperty(FileProperty("ProfileFilename","", FileAction.OptionalLoad, ['.irf']),\ "Name of input data file.") self.declareProperty("Lattice", -0.0, "Lattice size of the cubic unit cell.") self.declareProperty("GenerateInformationWS", False, "Optional to genearte profile table workspace and Bragg peak table. ") # Background - self.declareProperty(ITableWorkspaceProperty("BackgroundParameterWorkspace", "", Direction.InOut), + self.declareProperty(ITableWorkspaceProperty("BackgroundParameterWorkspace", "", Direction.InOut),\ "Name of table workspace containing background parameters.") self.declareProperty("ProcessBackground", False, "Option to process background from input data file.") backgroundtypes = ["Polynomial", "Chebyshev", "FullprofPolynomial"] self.declareProperty("BackgroundType", "Polynomial", StringListValidator(backgroundtypes), "Type of background.") arrvalidator = FloatArrayBoundedValidator() arrvalidator.setLower(0.) - self.declareProperty(FloatArrayProperty("BackgroundPoints", values=[], validator=arrvalidator, direction=Direction.Input), + self.declareProperty(FloatArrayProperty("BackgroundPoints", values=[], validator=arrvalidator, direction=Direction.Input),\ "User specified X/TOF values of the data points to calculate background.") - self.declareProperty(MatrixWorkspaceProperty("BackgroundWorkspace", "", Direction.Output, PropertyMode.Optional), + self.declareProperty(MatrixWorkspaceProperty("BackgroundWorkspace", "", Direction.Output, PropertyMode.Optional),\ "Name of data workspace containing the background data. ") # Output - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output),\ "Name of data workspace containing the diffraction pattern in .prf file. ") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py index 76cc78dc8a9d..93c5cd44c1ff 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py index d02cbed8a41e..0dfbd0139ab6 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py @@ -1,11 +1,11 @@ -import mantid.simpleapi as api +#pylint: disable=no-init,invalid-name import mantid from mantid.api import * from mantid.kernel import * - -import os import datetime - +import time +import os + class ExportExperimentLog(PythonAlgorithm): """ Algorithm to export experiment log @@ -21,11 +21,11 @@ def PyInit(self): wsprop = MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input) self.declareProperty(wsprop, "Input workspace containing the sample log information. ") - self.declareProperty(FileProperty("OutputFilename","", FileAction.Save, ['.txt, .csv']), + self.declareProperty(FileProperty("OutputFilename","", FileAction.Save, ['.txt, .csv']),\ "Output file of the experiment log.") filemodes = ["append", "fastappend", "new"] - self.declareProperty("FileMode", "append", mantid.kernel.StringListValidator(filemodes), + self.declareProperty("FileMode", "append", mantid.kernel.StringListValidator(filemodes),\ "Optional to create a new file or append to an existing file.") lognameprop = StringArrayProperty("SampleLogNames", values=[], direction=Direction.Input) @@ -49,7 +49,7 @@ def PyInit(self): self.declareProperty(overrideprop, "List of paired strings as log title and value to override values from workspace.") # Time zone - timezones = ["UTC", "America/New_York", "Asia/Shanghai", "Australia/Sydney", "Europe/London", "GMT+0", + timezones = ["UTC", "America/New_York", "Asia/Shanghai", "Australia/Sydney", "Europe/London", "GMT+0",\ "Europe/Paris", "Europe/Copenhagen"] self.declareProperty("TimeZone", "America/New_York", StringListValidator(timezones)) @@ -97,8 +97,6 @@ def PyExec(self): def _processInputs(self): """ Process input properties """ - import os - import os.path self._wksp = self.getProperty("InputWorkspace").value @@ -254,9 +252,6 @@ def _examineLogFile(self): def _startNewFile(self): """ Start a new file is user wants and save the older one to a different name """ - import datetime - import time - import os # Rename old file and reset the file mode diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py index fbc231e69cea..794c7aa47292 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py @@ -1,8 +1,7 @@ -import mantid.simpleapi as api +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * import os -import datetime class ExportSampleLogsToCSVFile(PythonAlgorithm): """ Python algorithm to export sample logs to spread sheet file @@ -42,7 +41,7 @@ def PyInit(self): self.declareProperty("Header", "", "String in the header file.") # Time zone - timezones = ["UTC", "America/New_York", "Asia/Shanghai", "Australia/Sydney", "Europe/London", "GMT+0", + timezones = ["UTC", "America/New_York", "Asia/Shanghai", "Australia/Sydney", "Europe/London", "GMT+0",\ "Europe/Paris", "Europe/Copenhagen"] self.declareProperty("TimeZone", "America/New_York", StringListValidator(timezones)) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FilterLogByTime.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FilterLogByTime.py index df8108481e11..38684e50853b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FilterLogByTime.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FilterLogByTime.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py index d014770dc56f..45f0fd876835 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * import numpy as np diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py index fd44cde703f6..890767754914 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid import mantid.api import mantid.simpleapi diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiMonDet.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiMonDet.py index 1d8d55dab696..e2eb1fa40dab 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiMonDet.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiMonDet.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import PythonAlgorithm, AlgorithmFactory,WorkspaceProperty from mantid.kernel import Direction,IntBoundedValidator,FloatBoundedValidator import mantid.simpleapi diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiT0atSNS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiT0atSNS.py index 400b0fac80f6..582beaf012a8 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiT0atSNS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiT0atSNS.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid import numpy diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py index f708e716043e..1b9bbcfbc9f4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py index 9ffb0b45fbb1..7956ca69d90a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py @@ -1,7 +1,8 @@ -from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory, FileProperty, FileAction, MatrixWorkspaceProperty, WorkspaceProperty -from mantid.kernel import Direction, StringListValidator +#pylint: disable=no-init,invalid-name +from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory,\ + FileProperty, FileAction, MatrixWorkspaceProperty +from mantid.kernel import Direction -import mantid.simpleapi as api _OUTPUTLEVEL = "NOOUTPUT" @@ -26,15 +27,15 @@ def summary(self): def PyInit(self): """ Declare properties """ - self.declareProperty(FileProperty("Filename","", FileAction.Load, ['.hkl', '.prf', '.dat']), + self.declareProperty(FileProperty("Filename","", FileAction.Load, ['.hkl', '.prf', '.dat']),\ "Name of [http://www.ill.eu/sites/fullprof/ Fullprof] .hkl or .prf file.") #self.declareProperty("Bank", 1, "Bank ID for output if there are more than one bank in .irf file.") - self.declareProperty(ITableWorkspaceProperty("PeakParameterWorkspace", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("PeakParameterWorkspace", "", Direction.Output),\ "Name of table workspace containing peak parameters from .hkl file.") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output),\ "Name of data workspace containing the diffraction pattern in .prf file. ") return diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py index eaaf9bdbb5cc..a5b924fcc228 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import time import datetime import numbers diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py index 76558b362f05..e226a6747e00 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.simpleapi import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQ.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQ.py index dcb74ad3bd2b..2aeedd4bc6f2 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQ.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQ.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name,no-init #-------------------------------------------------------------- # Algorithm which loads a SINQ file. # This algorithm calculates the filename from instrument @@ -7,7 +8,7 @@ # Mark Koennecke, November 2012 #-------------------------------------------------------------- from mantid.api import AlgorithmFactory -from mantid.api import PythonAlgorithm, WorkspaceFactory, FileProperty, FileAction, WorkspaceProperty +from mantid.api import PythonAlgorithm, WorkspaceProperty from mantid.kernel import Direction, StringListValidator, ConfigServiceImpl import mantid.simpleapi import datetime diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py index 1e9b7476a306..99f276747866 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name #-------------------------------------------------------------- # Algorithm which loads a SINQ file. It matches the instrument # and the right dictionary file and then goes away and calls @@ -6,8 +7,8 @@ # Mark Koennecke, November 2012 #-------------------------------------------------------------- from mantid.api import AlgorithmFactory -from mantid.api import PythonAlgorithm, WorkspaceFactory, FileProperty, FileAction, WorkspaceProperty, FrameworkManager -from mantid.kernel import Direction, StringListValidator, ConfigServiceImpl +from mantid.api import PythonAlgorithm, FileProperty, FileAction, WorkspaceProperty +from mantid.kernel import Direction, StringListValidator import mantid.simpleapi from mantid import config import os.path @@ -50,7 +51,7 @@ def PyExec(self): "RITA-2":"rita.dic", "SANS":"sans.dic", "SANS2":"sans.dic", - "TRICS":"trics.dic" + "TRICS":"trics.dic"\ } dictsearch = os.path.join(config['instrumentDefinition.directory'],"nexusdictionaries") dicname = os.path.join(dictsearch, diclookup[inst]) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py index 500396a95f42..6ebd1da4ea1b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import (CropWorkspace, LoadEmptyInstrument, LoadRaw, Plus, @@ -52,7 +53,7 @@ def PyInit(self): self.declareProperty(FileProperty(INST_PAR_PROP,"",action=FileAction.OptionalLoad, extensions=["dat"]), - doc="An optional IP file. If provided the values are used to correct " + doc="An optional IP file. If provided the values are used to correct "\ "the default instrument values and attach the t0 values to each detector") self.declareProperty(SUM_PROP, False, diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py index 00e12cc3fdaa..7cd1366266bd 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi import mantid.kernel import mantid.api diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py index 5aa82a595b8c..fb9ced964035 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi import mantid.api import mantid.kernel diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py index 95f9fccfd65c..6df3c2e9af03 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py @@ -1,13 +1,13 @@ -import sys +#pylint: disable=invalid-name, no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * -class QueryFlag: +class QueryFlag(object): def isMasked(self, detector, yValue): return detector.isMasked() -class QueryValue: +class QueryValue(object): def isMasked(self, detector, yValue): return yValue == 1 @@ -23,8 +23,10 @@ def summary(self): return "Saves the masking information in a workspace to a Cal File." def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), "The workspace containing the Masking to extract.") - self.declareProperty(FileProperty(name="OutputFile",defaultValue="",action=FileAction.Save,extensions=['cal']), "The file for the results.") + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input),\ + "The workspace containing the Masking to extract.") + self.declareProperty(FileProperty(name="OutputFile",defaultValue="",\ + action=FileAction.Save,extensions=['cal']), "The file for the results.") self.declareProperty("Invert", False, "If True, masking is inverted in the input workspace. Default: False") @@ -35,7 +37,7 @@ def PyExec(self): invert = self.getProperty("Invert").value mask_query = QueryFlag() if inputWorkspace.id() == "MaskWorkspace": - mask_query = QueryValue() + mask_query = QueryValue() #check for consistency if len(inputWorkspace.readX(0)) < 1: @@ -58,7 +60,7 @@ def PyExec(self): try: det = inputWorkspace.getDetector(i) y_value = inputWorkspace.readY(i)[0] - if (mask_query.isMasked(det, y_value)): #check if masked + if mask_query.isMasked(det, y_value): #check if masked group = masking_flag else: group = not_masking_flag @@ -67,8 +69,8 @@ def PyExec(self): detIDs = det.getDetectorIDs() except: detIDs = [det.getID()] - for id in detIDs: - calFile.write(self.FormatLine(i,id,0.0,group,group)) + for did in detIDs: + calFile.write(self.FormatLine(i,did,0.0,group,group)) except: #no detector for this spectra pass diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py index 54b5e72b53af..30f3ca27639d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py index 244933f644bc..aefeec5a8ba2 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py index a4b49a463d6d..e779abe8845b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py @@ -1,4 +1,4 @@ -import mantid.simpleapi as api +#pylint: disable=no-init from mantid.api import * from mantid.kernel import * @@ -61,12 +61,12 @@ def PyInit(self): self.declareProperty("NormBackRun", 0, doc="The background" + defaultMsg) - self.declareProperty(StringArrayProperty("FrequencyLogNames", ["SpeedRequest1", "Speed1", "frequency"], - direction=Direction.Input), + self.declareProperty(StringArrayProperty("FrequencyLogNames", ["SpeedRequest1", "Speed1", "frequency"],\ + direction=Direction.Input),\ "Possible log names for frequency.") - self.declareProperty(StringArrayProperty("WaveLengthLogNames", ["LambdaRequest", "lambda"], - direction=Direction.Input), + self.declareProperty(StringArrayProperty("WaveLengthLogNames", ["LambdaRequest", "lambda"],\ + direction=Direction.Input),\ "Candidate log names for wave length.") return @@ -246,7 +246,7 @@ def getWavelength(self, logs, wkspName): else: if wavelength.units != "Angstrom" and wavelength.units != "A": - msg = "Only know how to deal with %s in Angstrom (A) but not %s" % (name, + msg = "Only know how to deal with %s in Angstrom (A) but not %s" % (name,\ wavelength.units) self.log().warning(msg) break diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py index 43a1655ceb0a..9432da8feb82 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import LoadAscii diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py index e26796bc3c08..10aa59a5b53e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import StringArrayProperty, Direction from mantid.simpleapi import * from mantid.api import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py index 10e66a2436d7..515631e1685e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.api import (PythonAlgorithm, AlgorithmFactory) from mantid.api import (FileProperty, diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py index 6b93e1d1513e..5559c8cd5ef3 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py @@ -1,8 +1,7 @@ +#pylint: disable=no-init from mantid.api import * from mantid.kernel import Direction - -from os import listdir -from os.path import isfile, join, split, splitext +from os.path import split, splitext import re diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py index 3480e64a2f54..5d090b0e2b30 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.api import PythonAlgorithm from mantid.api import ITableWorkspaceProperty from mantid.api import AlgorithmFactory, WorkspaceFactory @@ -12,8 +13,8 @@ PoldiLoadChopperSlits, PoldiLoadSpectra, PoldiLoadIPP, - PoldiAutoCorrelation, - PoldiPeakDetection, + #PoldiAutoCorrelation, + #PoldiPeakDetection, GroupWorkspaces, RenameWorkspace) import os.path @@ -42,7 +43,7 @@ def PyInit(self): self.declareProperty(ITableWorkspaceProperty("InputWorkspace", "PoldiAnalysis", direction=Direction.Input), "Poldi analysis main worksheet") - self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "PoldiIPPmanager", direction=Direction.Output), + self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "PoldiIPPmanager", direction=Direction.Output),\ "Poldi IPP table manager") self.declareProperty("wlenmin", 1.1, diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py index 4e1722361f91..e4dff3b3c1de 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.simpleapi import * from numpy import zeros, shape, arange @@ -186,8 +187,8 @@ def PyExec(self): error_0 = 1. / pc # rebin data - ws_histo_data = wks_utility.rebinNeXus(ws_event_data, - [binTOFrange[0], binTOFsteps, binTOFrange[1]], + ws_histo_data = wks_utility.rebinNeXus(ws_event_data,\ + [binTOFrange[0], binTOFsteps, binTOFrange[1]],\ 'data') # get q range @@ -197,18 +198,18 @@ def PyExec(self): [first_slit_size, last_slit_size] = wks_utility.getSlitsSize(ws_histo_data) # keep only TOF range - ws_histo_data = wks_utility.cropTOF(ws_histo_data, - TOFrange[0], - TOFrange[1], + ws_histo_data = wks_utility.cropTOF(ws_histo_data,\ + TOFrange[0],\ + TOFrange[1],\ 'data') # normalize by current proton charge ws_histo_data = wks_utility.normalizeNeXus(ws_histo_data, 'data') # integrate over low resolution range - [data_tof_axis, data_y_axis, data_y_error_axis] = wks_utility.integrateOverLowResRange(ws_histo_data, - dataLowResRange, - 'data', + [data_tof_axis, data_y_axis, data_y_error_axis] = wks_utility.integrateOverLowResRange(ws_histo_data,\ + dataLowResRange,\ + 'data',\ is_nexus_detector_rotated_flag) # #DEBUG ONLY @@ -248,36 +249,36 @@ def PyExec(self): error_0 = 1. / pc # rebin normalization - ws_histo_norm = wks_utility.rebinNeXus(ws_event_norm, - [binTOFrange[0], binTOFsteps, binTOFrange[1]], + ws_histo_norm = wks_utility.rebinNeXus(ws_event_norm,\ + [binTOFrange[0], binTOFsteps, binTOFrange[1]],\ 'normalization') # keep only TOF range - ws_histo_norm = wks_utility.cropTOF(ws_histo_norm, - TOFrange[0], - TOFrange[1], + ws_histo_norm = wks_utility.cropTOF(ws_histo_norm,\ + TOFrange[0],\ + TOFrange[1],\ 'normalization') # normalize by current proton charge ws_histo_norm = wks_utility.normalizeNeXus(ws_histo_norm, 'normalization') # integrate over low resolution range - [norm_tof_axis, norm_y_axis, norm_y_error_axis] = wks_utility.integrateOverLowResRange(ws_histo_norm, - normLowResRange, - 'normalization', + [norm_tof_axis, norm_y_axis, norm_y_error_axis] = wks_utility.integrateOverLowResRange(ws_histo_norm,\ + normLowResRange,\ + 'normalization',\ is_nexus_detector_rotated_flag) # substract background - [norm_y_axis, norm_y_error_axis] = wks_utility.substractBackground(norm_tof_axis[0:-1], - norm_y_axis, - norm_y_error_axis, - normPeakRange, - normBackFlag, - normBackRange, - error_0, + [norm_y_axis, norm_y_error_axis] = wks_utility.substractBackground(norm_tof_axis[0:-1],\ + norm_y_axis,\ + norm_y_error_axis,\ + normPeakRange,\ + normBackFlag,\ + normBackRange,\ + error_0,\ 'normalization') - [av_norm, av_norm_error] = wks_utility.fullSumWithError(norm_y_axis, + [av_norm, av_norm_error] = wks_utility.fullSumWithError(norm_y_axis,\ norm_y_error_axis) # ## DEBUGGING ONLY @@ -362,7 +363,7 @@ def PyExec(self): # cleanup data - [final_y_axis, final_y_error_axis] = wks_utility.cleanupData1D(final_y_axis, + [final_y_axis, final_y_error_axis] = wks_utility.cleanupData1D(final_y_axis,\ final_error_axis) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py index 4db03267838d..54a5880695c3 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * import mantid.simpleapi as api from mantid.api import * @@ -27,21 +28,21 @@ def summary(self): def PyInit(self): """ Declare properties """ - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, PropertyMode.Optional),\ "Name of data workspace containing the diffraction pattern in .prf file. ") self.declareProperty("WorkspaceIndex", 0, "Spectrum (workspace index starting from 0) of the data to refine against in input workspace.") - self.declareProperty(ITableWorkspaceProperty("SeqControlInfoWorkspace", "", Direction.InOut, PropertyMode.Optional), + self.declareProperty(ITableWorkspaceProperty("SeqControlInfoWorkspace", "", Direction.InOut, PropertyMode.Optional),\ "Name of table workspace containing sequential refinement information.") - self.declareProperty(ITableWorkspaceProperty("InputProfileWorkspace", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(ITableWorkspaceProperty("InputProfileWorkspace", "", Direction.Input, PropertyMode.Optional),\ "Name of table workspace containing starting profile parameters.") - self.declareProperty(ITableWorkspaceProperty("InputBraggPeaksWorkspace", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(ITableWorkspaceProperty("InputBraggPeaksWorkspace", "", Direction.Input, PropertyMode.Optional),\ "Name of table workspace containing a list of reflections. ") - self.declareProperty(ITableWorkspaceProperty("InputBackgroundParameterWorkspace", "", Direction.Input, + self.declareProperty(ITableWorkspaceProperty("InputBackgroundParameterWorkspace", "", Direction.Input,\ PropertyMode.Optional), "Name of table workspace containing a list of reflections. ") self.declareProperty("StartX", -0., "Start X (TOF) to refine diffraction pattern.") @@ -52,15 +53,15 @@ def PyInit(self): #refoptions = ["Levenberg-Marquardt", "Random Walk", "Single Peak Fit"] refoptions = ["Random Walk"] - self.declareProperty("RefinementOption", "Random Walk", StringListValidator(refoptions), + self.declareProperty("RefinementOption", "Random Walk", StringListValidator(refoptions),\ "Options of algorithm to refine. ") - self.declareProperty(StringArrayProperty("ParametersToRefine", values=[], direction=Direction.Input), + self.declareProperty(StringArrayProperty("ParametersToRefine", values=[], direction=Direction.Input),\ "List of parameters to refine.") self.declareProperty("NumRefineCycles", 1, "Number of refinement cycles.") - peaktypes = ["", "Neutron Back-to-back exponential convoluted with pseudo-voigt", + peaktypes = ["", "Neutron Back-to-back exponential convoluted with pseudo-voigt",\ "Thermal neutron Back-to-back exponential convoluted with pseudo-voigt"] self.declareProperty("ProfileType", "", StringListValidator(peaktypes), "Type of peak profile function.") @@ -70,11 +71,11 @@ def PyInit(self): self.declareProperty("FromStep", -1, "If non-negative, the previous code is not set from last step, but the step specified.") # Property for save project - self.declareProperty(FileProperty("OutputProjectFilename","", FileAction.OptionalSave, ['.nxs']), + self.declareProperty(FileProperty("OutputProjectFilename","", FileAction.OptionalSave, ['.nxs']),\ "Name of sequential project file.") # Property for save project - self.declareProperty(FileProperty("InputProjectFilename","", FileAction.OptionalLoad, ['.nxs']), + self.declareProperty(FileProperty("InputProjectFilename","", FileAction.OptionalLoad, ['.nxs']),\ "Name of sequential project file.") # Project ID @@ -98,7 +99,7 @@ def PyExec(self): if seqrefine.isSetup() is True: raise NotImplementedError("Impossible to have it set up already.") - seqrefine.initSetup(self.dataws, self.wsindex, self.peaktype, self.profilews, self.braggpeakws, self.bkgdtype, + seqrefine.initSetup(self.dataws, self.wsindex, self.peaktype, self.profilews, self.braggpeakws, self.bkgdtype,\ self.bkgdparws, self.startx, self.endx) elif self.functionoption == "Refine": @@ -174,7 +175,7 @@ def _processInputProperties(self): if self.functionoption != "Load": self.datawsname = str(self.dataws) if self.wsindex < 0 or self.wsindex >= self.dataws.getNumberHistograms(): - raise NotImplementedError("Input workspace index %d is out of range (0, %d)." % + raise NotImplementedError("Input workspace index %d is out of range (0, %d)." %\ (self.wsindex, self.dataws.getNumberHistograms())) return @@ -264,7 +265,7 @@ def initSetup(self, dataws, wsindex, peaktype, profilews, braggpeakws, bkgdtype, self._recordPostRefineInfo(runner) # Group the newly generated workspace and do some record - api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, self._profileWS, self._braggpeakws, self._bkgdparws), + api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, self._profileWS, self._braggpeakws, self._bkgdparws),\ OutputWorkspace=self._wsgroupName) self._wsgroupCreated = True @@ -355,16 +356,16 @@ def refine(self, dataws, wsindex, parametersToFit, numcycles, startx, endx, last # Group newly generated workspaces and add name to reposiotry if self._wsgroupCreated is True: - api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname, self._wsgroupName), + api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname, self._wsgroupName),\ OutputWorkspace=self._wsgroupName) else: wsgroup = AnalysisDataService.retrieve(self._wsgroupName) hasbkgd = list(wsgroup.getNames()).count(bkgdparamwsname) if hasbkgd == 1: - api.GroupWorkspaces(InputWorkspaces="%s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname), + api.GroupWorkspaces(InputWorkspaces="%s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname),\ OutputWorkspace=self._wsgroupName) elif hasbkgd == 0: - api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname, bkgdparamwsname), + api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname, bkgdparamwsname),\ OutputWorkspace=self._wsgroupName) else: raise NotImplementedError("Impossible to have 1 workspace appeared twice in a workspace group.") @@ -482,7 +483,7 @@ def _parseRecordTable(self, laststep): self._lastValidRowIndex = lastvalidrow if laststep > lastrecordedstep: - self.glog.warning("Last step %d is not recorded. Using step %d instead. " % + self.glog.warning("Last step %d is not recorded. Using step %d instead. " %\ (laststep, lastrecordedstep)) laststep = lastrecordedstep elif laststep < 0: @@ -500,12 +501,12 @@ def _parseRecordTable(self, laststep): bkgdtype = self._recordws.cell(lastrow, 3).strip() bkgdparamwsname = self._recordws.cell(lastrow, 4).strip() if profilewsname == "": - raise NotImplementedError("Profile workspace name is emtpy in row %d. It is not supposed to happen." % + raise NotImplementedError("Profile workspace name is emtpy in row %d. It is not supposed to happen." %\ (lastvalidrow)) break # ENDWHILE if profilewsname == "": - raise NotImplementedError("Step %d is not found in record table. It is impossible. " % + raise NotImplementedError("Step %d is not found in record table. It is impossible. " %\ (laststep)) # Current step @@ -529,7 +530,7 @@ def _recordPreRefineInfo(self, refiner, laststep): if self._recordWSLastRowInvalid is False: self._currstep = numrows - rectablews.addRow([self._currstep, "", "", "", "", "", -1.0, laststep, -1.0, "profilews", + rectablews.addRow([self._currstep, "", "", "", "", "", -1.0, laststep, -1.0, "profilews",\ "reflectionws", "Polynomial", "BkgdParm"]) else: self._currstep = numrows-1 @@ -774,7 +775,7 @@ def calculate(self, startx, endx): """ Do Le bail calculation """ if (self._inputIsSetup and self._outputIsSetup) is False: - raise NotImplementedError("Either input or output is not setup: inputIsStepUp = %s, outputIsSetup = %s" % + raise NotImplementedError("Either input or output is not setup: inputIsStepUp = %s, outputIsSetup = %s" %\ (str(self._inputIsSetup), str(self._outputIsSetup))) self.glog.information("**** Calculate: DataWorksapce = %s" % (str(self.datawsname))) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py index a6c9e59a75d2..e0640213e80d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name,no-init from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty from mantid.simpleapi import * from mantid.kernel import StringMandatoryValidator, Direction @@ -125,7 +126,7 @@ def __init__(self, filenames): # any are missing. missing_files = list(ifilterfalse(os.path.exists, filenames)) if len(missing_files) > 0: - raise ValueError("One or more files are missing: " + + raise ValueError("One or more files are missing: " +\ str(missing_files)) self._filenames = filenames @@ -188,11 +189,11 @@ def PyInit(self): '', StringMandatoryValidator(), doc='The range of runs to retrieve the run info for. E.g. "100-105".') - self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output),\ doc= """The name of the TableWorkspace that will be created. '''You must specify a name that does not already exist.''' """) def PyExec(self): - PROP_NAMES = ["inst_abrv", "run_number", "user_name", "run_title", + PROP_NAMES = ["inst_abrv", "run_number", "user_name", "run_title",\ "hd_dur"] # Not all ISIS run files have the relevant prop_names, but we may as @@ -203,7 +204,7 @@ def PyExec(self): # Ensure workspace does not already exist. output_ws_name = self.getPropertyValue("OutputWorkspace") if mtd.doesExist(output_ws_name): - raise ValueError("Workspace \"" + output_ws_name + "\" already " + raise ValueError("Workspace \"" + output_ws_name + "\" already "\ "exists. Either delete it, or choose another workspace name.") # Check that all run files are available. diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSSubtract.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSSubtract.py index c79e5ce731ba..ac929f70a0d8 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSSubtract.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSSubtract.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import Direction, FloatBoundedValidator import mantid.simpleapi diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py index 563b0b4f3fee..faf8e2681369 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py @@ -1,6 +1,6 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * -import os import sys import numpy as np @@ -18,11 +18,11 @@ def summary(self): return "Calculate the Wide Angle correction for SANS transmissions." def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("SampleData", "", direction = Direction.Input), + self.declareProperty(MatrixWorkspaceProperty("SampleData", "", direction = Direction.Input),\ "A workspace cropped to the detector to be reduced (the SAME as the input to [[Q1D]]); used to verify the solid angle. The workspace is not modified, just inspected.") - self.declareProperty(MatrixWorkspaceProperty("TransmissionData","",direction=Direction.Input), + self.declareProperty(MatrixWorkspaceProperty("TransmissionData","",direction=Direction.Input),\ "The transmission data calculated, referred to as T_0 in equations in discussion section") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace","",direction=Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace","",direction=Direction.Output),\ "The transmission corrected SANS data, normalised (divided) by T_0, see discussion section") def PyExec(self): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py index 829f922e370c..60b3fa2c264a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name,no-init import mantid import mantid.api import mantid.simpleapi as api @@ -34,7 +35,7 @@ def PyInit(self): self.declareProperty("Instrument", "PG3", StringListValidator(instruments), "Powder diffractometer's name") arrvalidator = IntArrayBoundedValidator() arrvalidator.setLower(0) - self.declareProperty(IntArrayProperty("RunNumber", values=[0], validator=arrvalidator, + self.declareProperty(IntArrayProperty("RunNumber", values=[0], validator=arrvalidator,\ direction=Direction.Input), "Number of sample run or 0 for only Vanadium and/or Background") extensions = [ "_histo.nxs", "_event.nxs", "_runinfo.xml"] self.declareProperty("Extension", "_event.nxs", @@ -52,9 +53,9 @@ def PyInit(self): doc="If specified overrides value in CharacterizationRunsFile. If -1 turns off correction.") self.declareProperty("VanadiumBackgroundNumber", defaultValue=0, validator=IntBoundedValidator(lower=-1), doc="If specified overrides value in CharacterizationRunsFile. If -1 turns off correction.") - self.declareProperty(FileProperty(name="CalibrationFile",defaultValue="",action=FileAction.Load, + self.declareProperty(FileProperty(name="CalibrationFile",defaultValue="",action=FileAction.Load,\ extensions = ["cal"])) - self.declareProperty(FileProperty(name="CharacterizationRunsFile",defaultValue="",action=FileAction.OptionalLoad, + self.declareProperty(FileProperty(name="CharacterizationRunsFile",defaultValue="",action=FileAction.OptionalLoad,\ extensions = ["txt"]),"File with characterization runs denoted") self.declareProperty("UnwrapRef", 0., "Reference total flight path for frame unwrapping. Zero skips the correction") @@ -67,7 +68,7 @@ def PyInit(self): self.declareProperty("MaxChunkSize", 0.0, "Specify maximum Gbytes of file to read in one chunk. Default is whole file.") self.declareProperty("FilterCharacterizations", False, "Filter the characterization runs using above parameters. This only works for event files.") - self.declareProperty(FloatArrayProperty("Binning", values=[0.,0.,0.], + self.declareProperty(FloatArrayProperty("Binning", values=[0.,0.,0.],\ direction=Direction.Input), "Positive is linear bins, negative is logorithmic") self.declareProperty("ResampleX", 0, "Number of bins in x-axis. Non-zero value overrides \"Params\" property. Negative value means logorithmic binning.") @@ -102,12 +103,12 @@ def PyInit(self): self.declareProperty("CompressTOFTolerance", 0.01, "Tolerance to compress events in TOF.") - self.declareProperty(StringArrayProperty("FrequencyLogNames", ["SpeedRequest1", "Speed1", "frequency"], - direction=Direction.Input), + self.declareProperty(StringArrayProperty("FrequencyLogNames", ["SpeedRequest1", "Speed1", "frequency"],\ + direction=Direction.Input),\ "Possible log names for frequency.") - self.declareProperty(StringArrayProperty("WaveLengthLogNames", ["LambdaRequest", "lambda"], - direction=Direction.Input), + self.declareProperty(StringArrayProperty("WaveLengthLogNames", ["LambdaRequest", "lambda"],\ + direction=Direction.Input),\ "Candidate log names for wave length.") return @@ -212,7 +213,7 @@ def PyExec(self): runnumber = temp self.log().information("[Sum] Process run number %s. " %(str(runnumber))) - temp = self._focusChunks(temp, SUFFIX, timeFilterWall, calib, + temp = self._focusChunks(temp, SUFFIX, timeFilterWall, calib,\ preserveEvents=preserveEvents) tempinfo = self._getinfo(temp) @@ -230,7 +231,7 @@ def PyExec(self): % (tempinfo["wavelength"], info["wavelength"])) samRun = api.Plus(LHSWorkspace=samRun, RHSWorkspace=temp, OutputWorkspace=samRun) if samRun.id() == EVENT_WORKSPACE_ID: - samRun = api.CompressEvents(InputWorkspace=samRun, OutputWorkspace=samRun, + samRun = api.CompressEvents(InputWorkspace=samRun, OutputWorkspace=samRun,\ Tolerance=COMPRESS_TOL_TOF) # 10ns api.DeleteWorkspace(str(temp)) # ENDIF @@ -248,7 +249,7 @@ def PyExec(self): # first round of processing the sample if not self.getProperty("Sum").value and samRun > 0: self._info = None - returned = self._focusChunks(samRun, SUFFIX, timeFilterWall, calib, self._splitws, + returned = self._focusChunks(samRun, SUFFIX, timeFilterWall, calib, self._splitws,\ preserveEvents=preserveEvents) if isinstance(returned, list): @@ -298,13 +299,13 @@ def PyExec(self): if ("%s_%d" % (self._instrument, canRun)) in mtd: canRun = mtd["%s_%d" % (self._instrument, canRun)] else: - canRun = self._focusChunks(canRun, SUFFIX, canFilterWall, calib, + canRun = self._focusChunks(canRun, SUFFIX, canFilterWall, calib,\ preserveEvents=preserveEvents) canRun = api.ConvertUnits(InputWorkspace=canRun, OutputWorkspace=canRun, Target="TOF") smoothParams = self.getProperty("BackgroundSmoothParams").value if smoothParams != None and len(smoothParams)>0: - canRun = api.FFTSmooth(InputWorkspace=canRun, OutputWorkspace=canRun, Filter="Butterworth", + canRun = api.FFTSmooth(InputWorkspace=canRun, OutputWorkspace=canRun, Filter="Butterworth",\ Params=smoothParams,IgnoreXBins=True,AllSpectra=True) workspacelist.append(str(canRun)) @@ -375,13 +376,13 @@ def PyExec(self): # strip peaks if self.getProperty("StripVanadiumPeaks").value: vanRun = api.ConvertUnits(InputWorkspace=vanRun, OutputWorkspace=vanRun, Target="dSpacing") - vanRun = api.StripVanadiumPeaks(InputWorkspace=vanRun, OutputWorkspace=vanRun, FWHM=self._vanPeakFWHM, - PeakPositionTolerance=self.getProperty("VanadiumPeakTol").value, + vanRun = api.StripVanadiumPeaks(InputWorkspace=vanRun, OutputWorkspace=vanRun, FWHM=self._vanPeakFWHM,\ + PeakPositionTolerance=self.getProperty("VanadiumPeakTol").value,\ BackgroundType="Quadratic", HighBackground=True) else: self.log().information("Not strip vanadium peaks") vanRun = api.ConvertUnits(InputWorkspace=vanRun, OutputWorkspace=vanRun, Target="TOF") - vanRun = api.FFTSmooth(InputWorkspace=vanRun, OutputWorkspace=vanRun, Filter="Butterworth", + vanRun = api.FFTSmooth(InputWorkspace=vanRun, OutputWorkspace=vanRun, Filter="Butterworth",\ Params=self._vanSmoothing,IgnoreXBins=True,AllSpectra=True) vanRun = api.SetUncertainties(InputWorkspace=vanRun, OutputWorkspace=vanRun) vanRun = api.ConvertUnits(InputWorkspace=vanRun, OutputWorkspace=vanRun, Target="TOF") @@ -400,7 +401,7 @@ def PyExec(self): samRun = api.ConvertToMatrixWorkspace(InputWorkspace=samRun, OutputWorkspace=samRun) samRun = api.Minus(LHSWorkspace=samRun, RHSWorkspace=canRun, OutputWorkspace=samRun) if samRun.id() == EVENT_WORKSPACE_ID: - samRun = api.CompressEvents(InputWorkspace=samRun, OutputWorkspace=samRun, + samRun = api.CompressEvents(InputWorkspace=samRun, OutputWorkspace=samRun,\ Tolerance=COMPRESS_TOL_TOF) # 10ns canRun = str(canRun) if vanRun is not None: @@ -412,7 +413,7 @@ def PyExec(self): normalized = False if samRun.id() == EVENT_WORKSPACE_ID: - samRun = api.CompressEvents(InputWorkspace=samRun, OutputWorkspace=samRun, + samRun = api.CompressEvents(InputWorkspace=samRun, OutputWorkspace=samRun,\ Tolerance=COMPRESS_TOL_TOF) # 5ns/ # make sure there are no negative values - gsas hates them @@ -610,13 +611,13 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, # Splitting workspace basename = str(temp) if self._splitinfotablews is None: - api.FilterEvents(InputWorkspace=temp, OutputWorkspaceBaseName=basename, + api.FilterEvents(InputWorkspace=temp, OutputWorkspaceBaseName=basename,\ SplitterWorkspace=splitwksp, GroupWorkspaces=True) else: self.log().information("SplitterWorkspace = %s, Information Workspace = %s. " % ( str(splitwksp), str(self._splitinfotablews))) - api.FilterEvents(InputWorkspace=temp, OutputWorkspaceBaseName=basename, - SplitterWorkspace=splitwksp, InformationWorkspace = str(self._splitinfotablews), + api.FilterEvents(InputWorkspace=temp, OutputWorkspaceBaseName=basename,\ + SplitterWorkspace=splitwksp, InformationWorkspace = str(self._splitinfotablews),\ GroupWorkspaces=True) # ENDIF wsgroup = mtd[basename] @@ -662,19 +663,19 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, temp = tempwslist[itemp] # Align and focus focuspos = self._focusPos - temp = api.AlignAndFocusPowder(InputWorkspace=temp, OutputWorkspace=temp, CalFileName=calib, - Params=self._binning, ResampleX=self._resampleX, Dspacing=self._bin_in_dspace, - DMin=self._info["d_min"], DMax=self._info["d_max"], TMin=self._info["tof_min"], TMax=self._info["tof_max"], - PreserveEvents=preserveEvents, - RemovePromptPulseWidth=self._removePromptPulseWidth, CompressTolerance=COMPRESS_TOL_TOF, - UnwrapRef=self._LRef, LowResRef=self._DIFCref, LowResSpectrumOffset=self._lowResTOFoffset, + temp = api.AlignAndFocusPowder(InputWorkspace=temp, OutputWorkspace=temp, CalFileName=calib,\ + Params=self._binning, ResampleX=self._resampleX, Dspacing=self._bin_in_dspace,\ + DMin=self._info["d_min"], DMax=self._info["d_max"], TMin=self._info["tof_min"], TMax=self._info["tof_max"],\ + PreserveEvents=preserveEvents,\ + RemovePromptPulseWidth=self._removePromptPulseWidth, CompressTolerance=COMPRESS_TOL_TOF,\ + UnwrapRef=self._LRef, LowResRef=self._DIFCref, LowResSpectrumOffset=self._lowResTOFoffset,\ CropWavelengthMin=self._wavelengthMin, **(focuspos)) for iws in xrange(temp.getNumberHistograms()): spec = temp.getSpectrum(iws) self.log().debug("[DBx131] ws %d: spectrum ID = %d. " % (iws, spec.getSpectrumNo())) if preserveEvents is True and isinstance(temp, mantid.api._api.IEventWorkspace) is True: - self.log().information("After being aligned and focussed workspace %s; Number of events = %d of chunk %d " % (str(temp), + self.log().information("After being aligned and focussed workspace %s; Number of events = %d of chunk %d " % (str(temp),\ temp.getNumberEvents(), ichunk)) # Rename and/or add to workspace of same splitter but different chunk @@ -698,7 +699,7 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, # Sum workspaces for all mpi tasks if HAVE_MPI: for itemp in xrange(numwksp): - wksplist[itemp] = api.GatherWorkspaces(InputWorkspace=wksplist[itemp], + wksplist[itemp] = api.GatherWorkspaces(InputWorkspace=wksplist[itemp],\ PreserveEvents=preserveEvents, AccumulationMethod="Add", OutputWorkspace=wksplist[itemp]) # ENDIF MPI @@ -715,7 +716,7 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, for itemp in xrange(numwksp): if wksplist[itemp].id() == EVENT_WORKSPACE_ID: - wksplist[itemp] = api.CompressEvents(InputWorkspace=wksplist[itemp], + wksplist[itemp] = api.CompressEvents(InputWorkspace=wksplist[itemp],\ OutputWorkspace=wksplist[itemp], Tolerance=COMPRESS_TOL_TOF) # 100ns try: @@ -779,12 +780,12 @@ def _save(self, wksp, info, normalized, pdfgetn): if "pdfgetn" in self._outTypes: pdfwksp = str(wksp)+"_norm" pdfwksp = api.SetUncertainties(InputWorkspace=wksp, OutputWorkspace=pdfwksp, SetError="sqrt") - api.SaveGSS(InputWorkspace=pdfwksp, Filename=filename+".getn", SplitFiles=False, Append=False, + api.SaveGSS(InputWorkspace=pdfwksp, Filename=filename+".getn", SplitFiles=False, Append=False,\ MultiplyByBinWidth=False, Bank=info["bank"], Format="SLOG", ExtendedHeader=True) api.DeleteWorkspace(pdfwksp) return # don't do the other bits of saving if "gsas" in self._outTypes: - api.SaveGSS(InputWorkspace=wksp, Filename=filename+".gsa", SplitFiles=False, Append=False, + api.SaveGSS(InputWorkspace=wksp, Filename=filename+".gsa", SplitFiles=False, Append=False,\ MultiplyByBinWidth=normalized, Bank=info["bank"], Format="SLOG", ExtendedHeader=True) if "fullprof" in self._outTypes: api.SaveFocusedXYE(InputWorkspace=wksp, StartAtBankNumber=info["bank"], Filename=filename+".dat") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SaveVulcanGSS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SaveVulcanGSS.py index 8b8404cbd1cf..c4ea036d7f54 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SaveVulcanGSS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SaveVulcanGSS.py @@ -1,8 +1,7 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * -import mantid.simpleapi as api -from mantid.api import AnalysisDataService class SaveVulcanGSS(PythonAlgorithm): """ Save GSS file for VULCAN @@ -25,16 +24,16 @@ def summary(self): def PyInit(self): """ Declare properties """ - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input),\ "Focussed diffraction workspace to be exported to GSAS file. ") - self.declareProperty(FileProperty("BinFilename","", FileAction.Load, ['.dat']), + self.declareProperty(FileProperty("BinFilename","", FileAction.Load, ['.dat']),\ "Name of a data file containing the bin boundaries in Log(TOF). ") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output),\ "Name of rebinned matrix workspace. ") - self.declareProperty(FileProperty("GSSFilename","", FileAction.Save, ['.gda']), + self.declareProperty(FileProperty("GSSFilename","", FileAction.Save, ['.gda']),\ "Name of the output GSAS file. ") self.declareProperty("IPTS", 0, "IPTS number") @@ -155,7 +154,7 @@ def _rebinVdrive(self, inputws, vec_refT, outputwsname): # ENDFOR (i) # ENDFOR (iws) api.DeleteWorkspace(Workspace=tempws) - gsaws = api.CreateWorkspace(DataX=newvecx, DataY=newvecy, DataE=newvece, NSpec=numhist, + gsaws = api.CreateWorkspace(DataX=newvecx, DataY=newvecy, DataE=newvece, NSpec=numhist,\ UnitX="TOF", ParentWorkspace=inputws, OutputWorkspace=outputwsname) return gsaws @@ -168,7 +167,7 @@ def _saveGSAS(self, gsaws, gdafilename): gsaws = api.ConvertToHistogram(InputWorkspace=gsaws, OutputWorkspace=str(gsaws)) # Save - api.SaveGSS(InputWorkspace=gsaws, Filename=gdafilename, SplitFiles=False, Append=False, + api.SaveGSS(InputWorkspace=gsaws, Filename=gdafilename, SplitFiles=False, Append=False,\ Format="SLOG", MultiplyByBinWidth=False, ExtendedHeader=False, UseSpectrumNumberAsBankID=True) return gsaws @@ -205,7 +204,7 @@ def _rewriteGSSFile(self, gssfilename, newheader): filebuffer += tmpbuffer banklines = [line] # ENDIFELSE - elif (inbank is True and cline.startswith("#") is False): + elif inbank is True and cline.startswith("#") is False: # Write data line banklines.append(line.strip("\n")) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py index ac30f56eeb42..f1f48228b43e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py @@ -1,5 +1,6 @@ -from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory, FileProperty, FileAction -from mantid.kernel import Direction, StringListValidator +#pylint: disable=no-init,invalid-name +from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory +from mantid.kernel import Direction import warnings _OUTPUTLEVEL = "NOOUTPUT" @@ -23,13 +24,13 @@ def summary(self): def PyInit(self): """ Declare properties """ - self.declareProperty(ITableWorkspaceProperty("BraggPeakParameterWorkspace", "", Direction.Input), + self.declareProperty(ITableWorkspaceProperty("BraggPeakParameterWorkspace", "", Direction.Input),\ "Name of Table Workspace containing peak parameters.") - self.declareProperty(ITableWorkspaceProperty("ZscoreWorkspace", "", Direction.Input), + self.declareProperty(ITableWorkspaceProperty("ZscoreWorkspace", "", Direction.Input),\ "Name of Table Workspace containing z-score for the peak parametrs.") - self.declareProperty(ITableWorkspaceProperty("OutputBraggPeakParameterWorkspace", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("OutputBraggPeakParameterWorkspace", "", Direction.Output),\ "Name of Table Workspace containing the filtered peaks' parameters.") self.declareProperty("MinimumPeakHeight", 0.0, "Minimum peak height allowed for the peaks to fit. ") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortByQVectors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortByQVectors.py index b91261511d0c..b3cbfdc1117b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortByQVectors.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortByQVectors.py @@ -1,10 +1,9 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * from mantid.simpleapi import (DeleteWorkspace, ExtractSingleSpectrum, RenameWorkspace, ConjoinWorkspaces, Transpose) import numpy as np -import os - class SortByQVectors(PythonAlgorithm): """ Sorts spectra from a workspace diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py index 700ec5b13b40..d5b19459b33f 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py @@ -1,4 +1,5 @@ -from mantid.api import PythonAlgorithm, AlgorithmFactory,WorkspaceProperty,PropertyMode +#pylint: disable=no-init,invalid-name +from mantid.api import PythonAlgorithm, AlgorithmFactory from mantid.kernel import Direction,IntArrayProperty, FloatArrayProperty import mantid,math,numpy diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py index 8786acbeea29..06cb23819356 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi as api from mantid.api import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py index 39cfe0bbbbcc..acee867295a5 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import PythonAlgorithm, AlgorithmFactory import mantid.simpleapi from mantid.kernel import FloatBoundedValidator,Direction diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibHYSPEC.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibHYSPEC.py index 50d32ed5451d..64aa3a82fa35 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibHYSPEC.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibHYSPEC.py @@ -1,5 +1,5 @@ +#pylint: disable=no-init from mantid.api import PythonAlgorithm, AlgorithmFactory -import mantid.simpleapi from mantid.kernel import FloatBoundedValidator,Direction,logger from numpy import sqrt,divide @@ -25,7 +25,7 @@ def summary(self): def PyInit(self): """ Declare properties """ - val=mantid.kernel.FloatBoundedValidator() + val=FloatBoundedValidator() val.setBounds(3,100) #reasonable incident nergy range for HYSPEC self.declareProperty("IncidentEnergy",0.,val,"Incident energy (3 to 100 meV)") self.declareProperty("TibMin",0.,Direction.Output) @@ -54,9 +54,9 @@ def PyExec(self): pre_lead_us = 16667 * index_under_frame pre_tail_us = pre_lead_us + tail_length_us post_lead_us = 16667 * (1+ index_under_frame) - post_tail_us = post_lead_us + tail_length_us - E_final_meV = -1 - E_transfer_meV = -1 + #post_tail_us = post_lead_us + tail_length_us + #E_final_meV = -1 + #E_transfer_meV = -1 # finding an ok TIB range MinTIB_us = 2000.0 slop_frac = 0.2 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py index 4f498695472c..41e7ef7be15f 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid import logger, mtd from mantid.api import PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, ITableWorkspaceProperty, PropertyMode from mantid.kernel import Direction, IntArrayProperty @@ -33,10 +34,10 @@ def PyInit(self): self.declareProperty('Save', defaultValue=False, doc='Switch saving result to nxs file Off/On') - self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '', + self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '',\ Direction.Output), doc='Name to call the output workspace.') - self.declareProperty(ITableWorkspaceProperty('OutputPropertiesTable', '', + self.declareProperty(ITableWorkspaceProperty('OutputPropertiesTable', '',\ Direction.Output, PropertyMode.Optional), doc='Name to call the properties output table workspace.') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/TestWorkspaceGroupProperty.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/TestWorkspaceGroupProperty.py index 8c30cd6b4d00..876e42219b17 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/TestWorkspaceGroupProperty.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/TestWorkspaceGroupProperty.py @@ -1,8 +1,6 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * -import numpy as np - -import os class TestWorkspaceGroupProperty(PythonAlgorithm): """ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/USANSSimulation.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/USANSSimulation.py index 3063fe07e683..14bd8682f2e1 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/USANSSimulation.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/USANSSimulation.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * @@ -17,7 +18,7 @@ def summary(self): def PyInit(self): self.declareProperty("TwoTheta", 0.01, "Scattering angle in degrees") - self.declareProperty(FloatArrayProperty("WavelengthPeaks", values=[0.72, 0.9, 1.2, 1.8, 3.6], + self.declareProperty(FloatArrayProperty("WavelengthPeaks", values=[0.72, 0.9, 1.2, 1.8, 3.6],\ direction=Direction.Input), "Wavelength peaks out of the monochromator") self.declareProperty("CountTime", 1000.0, "Fake count time") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py index eb15cd0d59e6..09c2c90a91e4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py @@ -1,8 +1,8 @@ +#pylint: disable=no-init,invalid-name import mantid import mantid.api import mantid.kernel import mantid.simpleapi -from numpy import arange class UpdatePeakParameterTableValue(mantid.api.PythonAlgorithm): """ Class to generate grouping file @@ -74,7 +74,7 @@ def PyExec(self): if colnamedict.has_key(colname): icolumn = colnamedict[colname] else: - raise NotImplementedError("Column name %s does not exist in TableWorkspace %s" + raise NotImplementedError("Column name %s does not exist in TableWorkspace %s"\ % (colname, tablews.name())) # 3. Set value diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py index dd677756799f..9b1aa2a178ae 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * @@ -110,8 +111,8 @@ def _calculate_resolution(self, workspace, output_ws_name): fit = mantid.api.AlgorithmManager.createUnmanaged('Fit') fit.initialize() fit.setChild(True) - mantid.simpleapi._set_properties(fit, function, InputWorkspace=workspace, MaxIterations=0, - CreateOutput=True, Output=fit_naming_stem, WorkspaceIndex=self._spectrum_index, + mantid.simpleapi._set_properties(fit, function, InputWorkspace=workspace, MaxIterations=0,\ + CreateOutput=True, Output=fit_naming_stem, WorkspaceIndex=self._spectrum_index,\ OutputCompositeMembers=True) fit.execute() fit_ws = fit.getProperty('OutputWorkspace').value diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ViewBOA.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ViewBOA.py index f60ce127a51f..cb180b688301 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ViewBOA.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ViewBOA.py @@ -1,11 +1,10 @@ +#pylint: disable=no-init,invalid-name from mantid.api import AlgorithmFactory -from mantid.api import PythonAlgorithm, WorkspaceFactory, FileProperty, FileAction, WorkspaceProperty -from mantid.kernel import Direction, StringListValidator, ConfigServiceImpl +from mantid.api import PythonAlgorithm +from mantid.kernel import Direction import mantid.simpleapi from mantid.simpleapi import mtd import datetime -import math -import os.path class ViewBOA(PythonAlgorithm): def category(self): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateCalibrationWorkspace.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateCalibrationWorkspace.py index e8aa6020978f..f09f10d61188 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateCalibrationWorkspace.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateCalibrationWorkspace.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * @@ -17,19 +18,19 @@ def PyInit(self): self.declareProperty(StringArrayProperty(name='InputFiles'), doc='Comma separated list of input files') - self.declareProperty(WorkspaceProperty('OutputWorkspace', '', + self.declareProperty(WorkspaceProperty('OutputWorkspace', '',\ direction=Direction.Output), doc='Output workspace for calibration data') - self.declareProperty(IntArrayProperty(name='DetectorRange', values=[0, 1], + self.declareProperty(IntArrayProperty(name='DetectorRange', values=[0, 1],\ validator=IntArrayMandatoryValidator()), doc='Range of detectors') - self.declareProperty(FloatArrayProperty(name='PeakRange', values=[0.0, 100.0], + self.declareProperty(FloatArrayProperty(name='PeakRange', values=[0.0, 100.0],\ validator=FloatArrayMandatoryValidator()), doc='') - self.declareProperty(FloatArrayProperty(name='BackgroundRange', values=[0.0, 1000.0], + self.declareProperty(FloatArrayProperty(name='BackgroundRange', values=[0.0, 1000.0],\ validator=FloatArrayMandatoryValidator()), doc='') @@ -79,8 +80,8 @@ def PyExec(self): (_, filename) = os.path.split(in_file) (root, _) = os.path.splitext(filename) try: - Load(Filename=in_file, OutputWorkspace=root, - SpectrumMin=int(self._spec_range[0]), SpectrumMax=int(self._spec_range[1]), + Load(Filename=in_file, OutputWorkspace=root,\ + SpectrumMin=int(self._spec_range[0]), SpectrumMax=int(self._spec_range[1]),\ LoadLogFiles=False) runs.append(root) except Exception as exc: @@ -94,7 +95,7 @@ def PyExec(self): else: calib_ws_name = runs[0] - CalculateFlatBackground(InputWorkspace=calib_ws_name, OutputWorkspace=calib_ws_name, + CalculateFlatBackground(InputWorkspace=calib_ws_name, OutputWorkspace=calib_ws_name,\ StartX=self._back_range[0], EndX=self._back_range[1], Mode='Mean') from inelastic_indirect_reduction_steps import NormaliseToUnityStep diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py index b5fdca55a691..5ae861013969 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name,no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * @@ -42,7 +43,7 @@ def PyInit(self): self.declareProperty(FloatArrayProperty(name='P4Bin', values=[]), doc='Projection 4 binning') - self.declareProperty(IMDWorkspaceProperty('OutputWorkspace', '', + self.declareProperty(IMDWorkspaceProperty('OutputWorkspace', '',\ direction=Direction.Output), doc='Output cut workspace') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py index ed313b04e543..73e8e9bb7908 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * @@ -14,44 +15,44 @@ def summary(self): def PyInit(self): # Declare properties - self.declareProperty(FileProperty('File', '', action=FileAction.Load, - extensions = ["phonon", "castep"]), + self.declareProperty(FileProperty('File', '', action=FileAction.Load,\ + extensions = ["phonon", "castep"]),\ doc='Filename of the file.') - self.declareProperty(name='Function',defaultValue='Gaussian', - validator=StringListValidator(['Gaussian', 'Lorentzian']), + self.declareProperty(name='Function',defaultValue='Gaussian',\ + validator=StringListValidator(['Gaussian', 'Lorentzian']),\ doc="Type of function to fit to peaks.") - self.declareProperty(name='PeakWidth', defaultValue=10.0, + self.declareProperty(name='PeakWidth', defaultValue=10.0,\ doc='Set Gaussian/Lorentzian FWHM for broadening. Default is 10') - self.declareProperty(name='SpectrumType',defaultValue='DOS', - validator=StringListValidator(['IonTable', 'DOS', 'IR_Active', 'Raman_Active']), + self.declareProperty(name='SpectrumType',defaultValue='DOS',\ + validator=StringListValidator(['IonTable', 'DOS', 'IR_Active', 'Raman_Active']),\ doc="Type of intensities to extract and model (fundamentals-only) from .phonon.") - self.declareProperty(name='Scale', defaultValue=1.0, + self.declareProperty(name='Scale', defaultValue=1.0,\ doc='Scale the intesity by the given factor. Default is no scaling.') - self.declareProperty(name='BinWidth', defaultValue=1.0, + self.declareProperty(name='BinWidth', defaultValue=1.0,\ doc='Set histogram resolution for binning (eV or cm**-1). Default is 1') - self.declareProperty(name='Temperature', defaultValue=300.0, + self.declareProperty(name='Temperature', defaultValue=300.0,\ doc='Temperature to use (in raman spectrum modelling). Default is 300') - self.declareProperty(name='ZeroThreshold', defaultValue=3.0, + self.declareProperty(name='ZeroThreshold', defaultValue=3.0,\ doc='Ignore frequencies below the this threshold. Default is 3.0') - self.declareProperty(StringArrayProperty('Ions', Direction.Input), + self.declareProperty(StringArrayProperty('Ions', Direction.Input),\ doc="List of Ions to use to calculate partial density of states. If left blank, total density of states will be calculated") - self.declareProperty(name='SumContributions', defaultValue=False, + self.declareProperty(name='SumContributions', defaultValue=False,\ doc="Sum the partial density of states into a single workspace.") - self.declareProperty(name='ScaleByCrossSection', defaultValue='None', - validator=StringListValidator(['None', 'Total', 'Incoherent', 'Coherent']), + self.declareProperty(name='ScaleByCrossSection', defaultValue='None',\ + validator=StringListValidator(['None', 'Total', 'Incoherent', 'Coherent']),\ doc="Sum the partial density of states by the scattering cross section.") - self.declareProperty(WorkspaceProperty('OutputWorkspace', '', Direction.Output), + self.declareProperty(WorkspaceProperty('OutputWorkspace', '', Direction.Output),\ doc="Name to give the output workspace.") # Regex pattern for a floating point number diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py index 4d22ae839387..7ad7e03b6a55 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * from mantid.simpleapi import Scale diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py index 1f2648223ff7..c2111ba25e62 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * import mantid.simpleapi as api @@ -171,18 +172,18 @@ def _crop_and_compute(wl_min_prop, wl_max_prop, suffix): raise RuntimeError, "DirectBeamTransmission could not retrieve the %s property" % wl_max_prop rebin_params = "%4.1f,%4.1f,%4.1f" % (wl_min, 0.1, wl_max) - alg = TransmissionUtils.simple_algorithm("Rebin", + alg = TransmissionUtils.simple_algorithm("Rebin",\ {"InputWorkspace": sample_mon_ws, "OutputWorkspace": "__sample_mon_"+suffix, "Params": rebin_params, - "PreserveEvents": False + "PreserveEvents": False\ }) sample_ws = alg.getProperty("OutputWorkspace").value - alg = TransmissionUtils.simple_algorithm("Rebin", + alg = TransmissionUtils.simple_algorithm("Rebin",\ {"InputWorkspace": empty_mon_ws, "OutputWorkspace": "__empty_mon_"+suffix, "Params": rebin_params, - "PreserveEvents": False + "PreserveEvents": False\ }) empty_ws = alg.getProperty("OutputWorkspace").value trans_ws, raw_ws = TransmissionUtils.calculate_transmission(self, @@ -190,18 +191,18 @@ def _crop_and_compute(wl_min_prop, wl_max_prop, suffix): empty_ws, first_det, "__transmission_"+suffix) - alg = TransmissionUtils.simple_algorithm("RebinToWorkspace", + alg = TransmissionUtils.simple_algorithm("RebinToWorkspace",\ {"WorkspaceToRebin": trans_ws, "WorkspaceToMatch": workspace, "OutputWorkspace": "__transmission_"+suffix, - "PreserveEvents": False + "PreserveEvents": False\ }) trans_ws = alg.getProperty("OutputWorkspace").value - alg = TransmissionUtils.simple_algorithm("RebinToWorkspace", + alg = TransmissionUtils.simple_algorithm("RebinToWorkspace",\ {"WorkspaceToRebin": raw_ws, "WorkspaceToMatch": workspace, "OutputWorkspace": "__transmission_unfitted_"+suffix, - "PreserveEvents": False + "PreserveEvents": False\ }) raw_ws = alg.getProperty("OutputWorkspace").value @@ -213,19 +214,19 @@ def _crop_and_compute(wl_min_prop, wl_max_prop, suffix): # Second frame trans_frame_2, raw_frame_2 = _crop_and_compute("wavelength_min_frame2", "wavelength_max_frame2", "_frame2") - alg = TransmissionUtils.simple_algorithm("Plus", + alg = TransmissionUtils.simple_algorithm("Plus",\ {"LHSWorkspace": trans_frame_1, "RHSWorkspace": trans_frame_2, - "OutputWorkspace": "__transmission", + "OutputWorkspace": "__transmission",\ }) trans_ws = alg.getProperty("OutputWorkspace").value self.setPropertyValue("TransmissionWorkspace", trans_ws_name) self.setProperty("TransmissionWorkspace", trans_ws) - alg = TransmissionUtils.simple_algorithm("Plus", + alg = TransmissionUtils.simple_algorithm("Plus",\ {"LHSWorkspace": raw_frame_1, "RHSWorkspace": raw_frame_2, - "OutputWorkspace": "__transmission_unfitted", + "OutputWorkspace": "__transmission_unfitted",\ }) raw_ws = alg.getProperty("OutputWorkspace").value raw_ws_name = "__transmission_raw_%s" % input_ws_name diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSNormalise.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSNormalise.py index b9f863377703..007297da7d84 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSNormalise.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSNormalise.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.api import * from mantid.kernel import * from reduction_workflow.find_data import find_file diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py index 9349f30d0d17..a93585f8b2ed 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.kernel import * from mantid.api import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py index e478aa2674b4..28aad4ce7454 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.api import PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, PropertyMode from mantid.kernel import StringListValidator, StringMandatoryValidator, Direction, logger @@ -12,11 +13,11 @@ def category(self): return "Workflow\\MIDAS;PythonAlgorithms" def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty('Sample', '', + self.declareProperty(MatrixWorkspaceProperty('Sample', '',\ optional=PropertyMode.Mandatory, direction=Direction.Input), doc="Name for the Sample workspace.") - self.declareProperty(MatrixWorkspaceProperty('Resolution', '', + self.declareProperty(MatrixWorkspaceProperty('Resolution', '',\ optional=PropertyMode.Mandatory, direction=Direction.Input), doc="Name for the Resolution workspace.") @@ -24,11 +25,11 @@ def PyInit(self): 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', '', + self.declareProperty(MatrixWorkspaceProperty('ParameterWorkspace', '',\ direction=Direction.Output, optional=PropertyMode.Optional), doc='Table workspace for saving Fury properties') - self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '', + self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '',\ direction=Direction.Output, optional=PropertyMode.Optional), doc='Output workspace') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py index 94584c4e1363..4f4a9c2d8d40 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid import config, logger, mtd, AlgorithmFactory from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py index 93867743acd6..3365684c2f7d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * @@ -60,8 +61,8 @@ def _load_data(filename, output_ws): self.default_output_dir = head else: output_str += _load_data(data_file[i], '__tmp_wksp') - api.Plus(LHSWorkspace=workspace, - RHSWorkspace='__tmp_wksp', + api.Plus(LHSWorkspace=workspace,\ + RHSWorkspace='__tmp_wksp',\ OutputWorkspace=workspace) # Get the monitor and timer values ws = AnalysisDataService.retrieve('__tmp_wksp') @@ -171,7 +172,7 @@ def PyExec(self): if "BackgroundFiles" in property_list: background = property_manager.getProperty("BackgroundFiles").value background_ws = "__background_%s" % output_ws - msg = self._multiple_load(background, background_ws, + msg = self._multiple_load(background, background_ws,\ property_manager, property_manager_name) bck_msg = "Loaded background %s\n" % background bck_msg += msg @@ -232,8 +233,8 @@ def PyExec(self): WorkspaceToMatch=output_ws, OutputWorkspace=background_ws+'_rebin', PreserveEvents=False) - api.Minus(LHSWorkspace=output_ws, - RHSWorkspace=background_ws, + api.Minus(LHSWorkspace=output_ws,\ + RHSWorkspace=background_ws,\ OutputWorkspace=output_ws) bck_msg = bck_msg.replace('\n','\n |') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py index acc78baa98ce..793061723169 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.simpleapi import * from mantid.kernel import StringListValidator, Direction from mantid.api import DataProcessorAlgorithm, PropertyMode, AlgorithmFactory, FileProperty, FileAction, MatrixWorkspaceProperty diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py index 01007e07b918..dc0854a7bc33 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * @@ -16,8 +17,8 @@ def PyInit(self): self.declareProperty(StringArrayProperty(name='InputFiles'), doc='Comma seperated list if input files') - self.declareProperty(WorkspaceProperty('OutputWorkspace', '', - optional=PropertyMode.Optional, + self.declareProperty(WorkspaceProperty('OutputWorkspace', '',\ + optional=PropertyMode.Optional,\ direction=Direction.Output), doc='Output resolution workspace (if left blank a name will be gernerated automatically)') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmissionMonitor.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmissionMonitor.py index 87f1d83cd956..1a8047bb8fe1 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmissionMonitor.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmissionMonitor.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py index ccb95aedc155..5334c887e88d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * @@ -17,7 +18,7 @@ def PyInit(self): self.declareProperty(StringArrayProperty(name='InputFiles'), doc='Comma separated list of input files') - self.declareProperty(WorkspaceGroupProperty('OutputWorkspace', '', + self.declareProperty(WorkspaceGroupProperty('OutputWorkspace', '',\ direction=Direction.Output), doc='Workspace group for the resulting workspaces') @@ -31,10 +32,10 @@ def PyInit(self): self.declareProperty(name='Reflection', defaultValue='', doc='Reflection used during run', validator=StringListValidator(['002', '004', '006', '111'])) - self.declareProperty(WorkspaceProperty('CalibrationWorkspace', '', + self.declareProperty(WorkspaceProperty('CalibrationWorkspace', '',\ direction=Direction.Input, optional=PropertyMode.Optional), doc='Workspace contining calibration data') - self.declareProperty(IntArrayProperty(name='DetectorRange', values=[0, 1], + self.declareProperty(IntArrayProperty(name='DetectorRange', values=[0, 1],\ validator=IntArrayMandatoryValidator()), doc='Comma separated range of detectors to use') self.declareProperty(FloatArrayProperty(name='BackgroundRange'), diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py index 0d5e64bbfc4e..d41ac822cdb2 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.kernel import * from mantid.api import * import os @@ -11,7 +12,7 @@ def category(self): def PyInit(self): - self.declareProperty(WorkspaceProperty('InputWorkspace', '', direction=Direction.Input), + self.declareProperty(WorkspaceProperty('InputWorkspace', '', direction=Direction.Input),\ doc='Input workspace in HWHM') valid_functions = ['ChudleyElliot', 'HallRoss', 'FickDiffusion', 'TeixeiraWater'] @@ -19,20 +20,20 @@ def PyInit(self): validator=StringListValidator(valid_functions), doc='The fit function to use') - self.declareProperty(name='Width', defaultValue=0, validator=IntMandatoryValidator(), + self.declareProperty(name='Width', defaultValue=0, validator=IntMandatoryValidator(),\ doc='Spectrum in the workspace to use for fiting') - self.declareProperty(name='QMin', defaultValue=0.0, validator=FloatMandatoryValidator(), + self.declareProperty(name='QMin', defaultValue=0.0, validator=FloatMandatoryValidator(),\ doc='Lower bound of Q range to use for fitting') - self.declareProperty(name='QMax', defaultValue=0.0, validator=FloatMandatoryValidator(), + self.declareProperty(name='QMax', defaultValue=0.0, validator=FloatMandatoryValidator(),\ doc='Upper bound of Q range to use for fitting') - self.declareProperty(name='Output', defaultValue='', direction=Direction.InOut, + self.declareProperty(name='Output', defaultValue='', direction=Direction.InOut,\ doc='Output name') - self.declareProperty(name='Plot', defaultValue=False, + self.declareProperty(name='Plot', defaultValue=False,\ doc='Plot result workspace') - self.declareProperty(name='Save', defaultValue=False, + self.declareProperty(name='Save', defaultValue=False,\ doc='Save result workspace to nexus file in the default save directory') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MSGDiffractionReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MSGDiffractionReduction.py index 15438f256618..73e8140748ac 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MSGDiffractionReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MSGDiffractionReduction.py @@ -1,11 +1,9 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * from mantid import config -import os.path, math - - class MSGDiffractionReduction(PythonAlgorithm): def category(self): @@ -40,7 +38,7 @@ def PyInit(self): self.declareProperty(name='RebinParam', defaultValue='', doc='Rebin parameters.') - self.declareProperty(WorkspaceGroupProperty('OutputWorkspace', '', + self.declareProperty(WorkspaceGroupProperty('OutputWorkspace', '',\ direction=Direction.Output), doc='Group name for the result workspaces.') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MolDyn.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MolDyn.py index 5e0b12ef31cc..245c36e2bc7a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MolDyn.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MolDyn.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name,no-init from mantid.simpleapi import * from mantid.kernel import * from mantid.api import * @@ -70,7 +71,7 @@ def summary(self): def PyInit(self): self.declareProperty(FileProperty('Filename', '', action=FileAction.OptionalLoad, - extensions=['.cdl', '.dat']), + extensions=['.cdl', '.dat']),\ doc='File path for data') self.declareProperty(StringArrayProperty('Functions'), diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py index 673230721c69..db6ceac74b9b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py @@ -1,6 +1,7 @@ +#pylint: disable=no-init # Algorithm to start Bayes programs from mantid.api import PythonAlgorithm, AlgorithmFactory -from mantid.kernel import StringListValidator, StringMandatoryValidator, logger +from mantid.kernel import StringListValidator, StringMandatoryValidator class MuscatData(PythonAlgorithm): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py index eb93747adc62..81b168ac4a7c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name # Algorithm to start Bayes programs from mantid.kernel import StringListValidator, StringMandatoryValidator from mantid.api import PythonAlgorithm, AlgorithmFactory diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py index c0d0e329f1fa..9e595dcb0c3b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py index 9ce72199366f..fb5aa4f3dc57 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name,no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * @@ -38,7 +39,7 @@ def addWs(self, wsname): try: dRange = timeRegimeToDRange[timeRegime] except KeyError: - raise RuntimeError("Unable to identify the DRange of " + wsname + + raise RuntimeError("Unable to identify the DRange of " + wsname +\ ", which has a time regime of " + str(timeRegime)) # Add the workspace to the map, alongside its DRange. diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py index 20678332d280..0d8c34b1def5 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.kernel import StringListValidator, StringMandatoryValidator from mantid.api import PythonAlgorithm, AlgorithmFactory diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py index b0f4decb1ded..fcc64819ecb9 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.api import PythonAlgorithm, AlgorithmFactory from mantid.kernel import StringListValidator, StringMandatoryValidator from mantid.simpleapi import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py index 9b1946133b5d..b25b90a721c7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * from mantid.simpleapi import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py index 4dbd424925ed..b505c147b431 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py index 217086f0f431..defb51dcebc7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.api import PythonAlgorithm, AlgorithmFactory from mantid.kernel import StringListValidator, StringMandatoryValidator from mantid.simpleapi import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py index 6736b723ce04..7b688b826504 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py @@ -1,8 +1,7 @@ +#pylint: disable=no-init,invalid-name import os -import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * -from reduction_workflow.instruments.sans import hfir_instrument from reduction_workflow.find_data import find_data class SANSAbsoluteScale(PythonAlgorithm): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py index 295813c96ccb..88d7baf2b75e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * import math @@ -17,7 +18,7 @@ def PyInit(self): self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", direction=Direction.Input)) - self.declareProperty(FloatArrayProperty("Binning", values=[0.,0.,0.], + self.declareProperty(FloatArrayProperty("Binning", values=[0.,0.,0.],\ direction=Direction.InOut), "Positive is linear bins, negative is logarithmic") self.declareProperty("NumberOfBins", 100, validator=IntBoundedValidator(lower=1), @@ -174,7 +175,7 @@ def PyExec(self): alg.setProperty("InputWorkspace", wedge_i) alg.execute() - self.declareProperty(MatrixWorkspaceProperty("WedgeWorkspace_%s" % i, "", + self.declareProperty(MatrixWorkspaceProperty("WedgeWorkspace_%s" % i, "",\ direction = Direction.Output)) self.setPropertyValue("WedgeWorkspace_%s" % i, wedge_i_name) self.setProperty("WedgeWorkspace_%s" % i, wedge_i) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py index 90b04c7fbfd4..afbe6031ab5e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDirectBeamTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDirectBeamTransmission.py index 57546fb4008b..562d77e894f0 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDirectBeamTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDirectBeamTransmission.py @@ -1,4 +1,4 @@ -import mantid.simpleapi as api +#pylint: disable=no-init from mantid.api import * from mantid.kernel import * import os diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSMask.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSMask.py index acba4b537f19..b7e48edbea1f 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSMask.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSMask.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py index fc38ab31a45e..175f8c3fbe5f 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * @@ -156,7 +157,7 @@ def _py_exec(self): if "BackgroundFiles" in property_list: background = property_manager.getProperty("BackgroundFiles").value background_ws = "__background_%s" % output_ws - msg = self._multiple_load(background, background_ws, + msg = self._multiple_load(background, background_ws,\ property_manager, property_manager_name) bck_msg = "Loaded background %s\n" % background bck_msg += msg @@ -219,8 +220,8 @@ def _py_exec(self): WorkspaceToMatch=output_ws, OutputWorkspace=background_ws+'_rebin', PreserveEvents=True) - api.Minus(LHSWorkspace=output_ws, - RHSWorkspace=background_ws+'_rebin', + api.Minus(LHSWorkspace=output_ws,\ + RHSWorkspace=background_ws+'_rebin',\ OutputWorkspace=output_ws) bck_msg = bck_msg.replace('\n','\n |') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py index e806b2cbcc5c..5e4beec1e3c7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid,sys class SavePlot1D(mantid.api.PythonAlgorithm): @@ -58,7 +59,7 @@ def DoPlot(self,ws): spectra=ws.getNumberHistograms() if spectra>10: mantid.kernel.logger.warning("more than 10 spectra to plot") - prog_reporter=mantid.api.Progress(self,start=0.0,end=1.0, + prog_reporter=mantid.api.Progress(self,start=0.0,end=1.0,\ nreports=spectra) for j in range(spectra): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py index 6debe06b76df..b2d10281f507 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name # Algorithm to start Bayes programs from mantid.simpleapi import * from mantid.api import DataProcessorAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, WorkspaceGroupProperty diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TimeSlice.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TimeSlice.py index 45895d7ad55d..6357edebf5c7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TimeSlice.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TimeSlice.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * @@ -59,7 +60,7 @@ def PyInit(self): self.declareProperty(StringArrayProperty(name='InputFiles'), doc='Comma separated list of input files') - self.declareProperty(WorkspaceProperty(name='CalibrationWorkspace', defaultValue='', + self.declareProperty(WorkspaceProperty(name='CalibrationWorkspace', defaultValue='',\ direction=Direction.Input, optional=PropertyMode.Optional), doc='Calibration workspace') @@ -81,7 +82,7 @@ def PyInit(self): self.declareProperty(name='OutputNameSuffix', defaultValue='_slice', doc='Suffix to append to raw file name for name of output workspace') - self.declareProperty(WorkspaceGroupProperty(name='OutputWorkspace', defaultValue='', + self.declareProperty(WorkspaceGroupProperty(name='OutputWorkspace', defaultValue='',\ direction=Direction.Output), doc='Name of workspace group to group result workspaces into') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py index 21cfd657d717..efc8c7035174 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py @@ -1,4 +1,4 @@ -import mantid.simpleapi as api +#pylint: disable=invalid-name from mantid.api import * from mantid.kernel import * import os @@ -59,7 +59,7 @@ def _load_data(filename, output_ws): alg_props = {"Filename": filename, "OutputWorkspace": output_ws, - "ReductionProperties": property_manager_name, + "ReductionProperties": property_manager_name,\ } if beam_center_x is not None and beam_center_y is not None: alg_props["BeamCenterX"] = beam_center_x @@ -111,7 +111,7 @@ def _load_data(filename, output_ws): # since the beam center may be at a different location alg = _execute("FindDetectorsInShape", {"Workspace": sample_ws, - "ShapeXML": cylXML + "ShapeXML": cylXML\ }) det_list = alg.getProperty("DetectorList").value first_det = det_list[0] @@ -131,7 +131,7 @@ def _normalise(workspace): alg = _execute(p.valueAsStr, {"InputWorkspace": workspace, "OutputWorkspace": workspace, - "ReductionProperties": property_manager_name + "ReductionProperties": property_manager_name\ }, is_name=False) msg = '' @@ -157,19 +157,19 @@ def _normalise(workspace): alg = _execute("ExtractSingleSpectrum", {"InputWorkspace": empty_ws, "OutputWorkspace": '__reference_binning', - "WorkspaceIndex": det_list[0] + "WorkspaceIndex": det_list[0]\ }) reference_ws = alg.getProperty("OutputWorkspace").value alg = _execute("RebinToWorkspace", {"WorkspaceToRebin": empty_ws, "WorkspaceToMatch": reference_ws, - "OutputWorkspace": empty_ws_name + "OutputWorkspace": empty_ws_name\ }) empty_ws = alg.getProperty("OutputWorkspace").value alg = _execute("RebinToWorkspace", {"WorkspaceToRebin": sample_ws, "WorkspaceToMatch": reference_ws, - "OutputWorkspace": sample_ws_name + "OutputWorkspace": sample_ws_name\ }) sample_ws = alg.getProperty("OutputWorkspace").value @@ -177,7 +177,7 @@ def _normalise(workspace): {"InputWorkspace": empty_ws, "OutputWorkspace": empty_mon_ws_name, "DetectorList": det_list, - "KeepUngroupedSpectra": True + "KeepUngroupedSpectra": True\ }) empty_mon_ws = alg.getProperty("OutputWorkspace").value @@ -185,26 +185,26 @@ def _normalise(workspace): {"InputWorkspace": sample_ws, "OutputWorkspace": sample_mon_ws_name, "DetectorList": det_list, - "KeepUngroupedSpectra": True + "KeepUngroupedSpectra": True\ }) sample_mon_ws = alg.getProperty("OutputWorkspace").value alg = _execute("ConvertToMatrixWorkspace", {"InputWorkspace": empty_mon_ws, - "OutputWorkspace": empty_mon_ws_name + "OutputWorkspace": empty_mon_ws_name\ }) empty_mon_ws = alg.getProperty("OutputWorkspace").value alg = _execute("ConvertToMatrixWorkspace", {"InputWorkspace": sample_mon_ws, - "OutputWorkspace": sample_mon_ws_name + "OutputWorkspace": sample_mon_ws_name\ }) sample_mon_ws = alg.getProperty("OutputWorkspace").value alg = _execute("RebinToWorkspace", {"WorkspaceToRebin": empty_mon_ws, "WorkspaceToMatch": sample_mon_ws, - "OutputWorkspace": empty_mon_ws_name + "OutputWorkspace": empty_mon_ws_name\ }) empty_mon_ws = alg.getProperty("OutputWorkspace").value @@ -267,7 +267,7 @@ def apply_transmission(self, workspace, trans_workspace): {"WorkspaceToRebin": trans_workspace, "WorkspaceToMatch": workspace, "OutputWorkspace": '__trans_rebin', - "PreserveEvents": False + "PreserveEvents": False\ }) rebinned_ws = alg.getProperty("OutputWorkspace").value @@ -278,7 +278,7 @@ def apply_transmission(self, workspace, trans_workspace): {"InputWorkspace": workspace, "TransmissionWorkspace": rebinned_ws, "OutputWorkspace": '__corrected_output', - "ThetaDependent": theta_dependent + "ThetaDependent": theta_dependent\ }) output_ws = alg.getProperty("OutputWorkspace").value return output_ws @@ -305,7 +305,7 @@ def _dark(ws, dark_current_property, dark_current_file=None): alg_props = {"InputWorkspace": ws, "PersistentCorrection": False, - "ReductionProperties": property_manager_name + "ReductionProperties": property_manager_name\ } if dark_current_file is not None: alg_props["Filename"] = dark_current_file diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py index 5bbf242df339..c811cd51a5b8 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * @@ -21,7 +22,7 @@ def summary(self): def PyInit(self): arrvalidator = IntArrayBoundedValidator() arrvalidator.setLower(0) - self.declareProperty(IntArrayProperty("RunNumbers", values=[0], validator=arrvalidator, + self.declareProperty(IntArrayProperty("RunNumbers", values=[0], validator=arrvalidator,\ direction=Direction.Input), "Runs to reduce") self.declareProperty("EmptyRun", '', "Run number for the empty run") @@ -99,11 +100,11 @@ def _load_data(self): is_scan = True # Append the info for when we do the reduction - self.data_files.append(self.DataFile(workspace=ws_name, - monitor=ws_name+'_monitors', - empty='__empty', - empty_monitor='__empty_monitors', - is_scan=is_scan, + self.data_files.append(self.DataFile(workspace=ws_name,\ + monitor=ws_name+'_monitors',\ + empty='__empty',\ + empty_monitor='__empty_monitors',\ + is_scan=is_scan,\ max_index=max_index)) total_points += max_index @@ -271,9 +272,9 @@ def _get_intensity(self, sample, empty, sample_monitor, empty_monitor, tof_min, OutputWorkspace='transmission') # Scattering signal - __signal_summed = _execute('SumSpectra', InputWorkspace=sample, - StartWorkspaceIndex=0, - EndWorkspaceIndex=nspecs/2, + __signal_summed = _execute('SumSpectra', InputWorkspace=sample,\ + StartWorkspaceIndex=0,\ + EndWorkspaceIndex=nspecs/2,\ OutputWorkspace='__signal_summed') __point = _execute('CropWorkspace', InputWorkspace=__signal_summed, XMin=tof_min, XMax=tof_max, diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py index 4c0402409f89..9888b80fa8bd 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name #from MantidFramework import * #from mantidsimple import * from mantid.simpleapi import * @@ -7,7 +8,7 @@ PRECISION = 0.020 -class sfCalculator(): +class sfCalculator(object): ref_date = '2014-10-01' # when the detector has been rotated @@ -250,7 +251,7 @@ def _calculateFinalYAxis(self, bNumerator=True): proton_charge = self._getProtonCharge(EventDataWks) print '----> rebinning ' - HistoDataWks = Rebin(InputWorkspace=EventDataWks, + HistoDataWks = Rebin(InputWorkspace=EventDataWks,\ Params=self.rebin_parameters) # mt2 = mtd['HistoDataWks'] @@ -259,9 +260,9 @@ def _calculateFinalYAxis(self, bNumerator=True): x_axis = HistoDataWks.readX(0)[:] self.x_axis = x_axis - OutputWorkspace = self._createIntegratedWorkspace(InputWorkspace=HistoDataWks, - proton_charge=proton_charge, - from_pixel=self.peak_pixel_min, + OutputWorkspace = self._createIntegratedWorkspace(InputWorkspace=HistoDataWks,\ + proton_charge=proton_charge,\ + from_pixel=self.peak_pixel_min,\ to_pixel=self.peak_pixel_max) DataWks = self._removeBackground(InputWorkspace=OutputWorkspace, @@ -329,7 +330,7 @@ def _calculateFinalYAxis(self, bNumerator=True): # mt3 = mtd['DataWks'] - self._calculateFinalAxis(Workspace=DataWks, + self._calculateFinalAxis(Workspace=DataWks,\ bNumerator=bNumerator) print 'done with _calculateFinalAxis and back in calculatefinalaxis' #REMOVEME @@ -429,7 +430,7 @@ def _createIntegratedWorkspace(self, index = int(y+x*304) # y_axis[y, :] += InputWorkspace.readY(index)[:] y_axis[y, :] += InputWorkspace.readY(index)[:] - y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) * + y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) *\ (InputWorkspace.readE(index)[:])) else: @@ -438,7 +439,7 @@ def _createIntegratedWorkspace(self, index = int(y+x*256) # y_axis[y, :] += InputWorkspace.readY(index)[:] y_axis[y, :] += InputWorkspace.readY(index)[:] - y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) * + y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) *\ (InputWorkspace.readE(index)[:])) # #DEBUG @@ -467,9 +468,9 @@ def _createIntegratedWorkspace(self, y_axis /= (proton_charge * 1e-12) y_error_axis /= (proton_charge * 1e-12) - OutputWorkspace = CreateWorkspace(DataX=x_axis, - DataY=y_axis, - DataE=y_error_axis, + OutputWorkspace = CreateWorkspace(DataX=x_axis,\ + DataY=y_axis,\ + DataE=y_error_axis,\ Nspec=self.alpha_pixel_nbr) return OutputWorkspace @@ -624,9 +625,9 @@ def _removeBackground(self, y_axis = peak_array.flatten() y_error_axis = peak_array_error.flatten() - DataWks = CreateWorkspace(DataX=tof_axis[0:-1], - DataY=y_axis, - DataE=y_error_axis, + DataWks = CreateWorkspace(DataX=tof_axis[0:-1],\ + DataY=y_axis,\ + DataE=y_error_axis,\ Nspec=1) # import sys @@ -695,16 +696,16 @@ def fit(self): b coefficients (y=a+bx) """ - DataToFit = CreateWorkspace(DataX=self.x_axis_ratio, - DataY=self.y_axis_ratio, - DataE=self.y_axis_error_ratio, + DataToFit = CreateWorkspace(DataX=self.x_axis_ratio,\ + DataY=self.y_axis_ratio,\ + DataE=self.y_axis_error_ratio,\ Nspec=1) print 'replaceSpecialValues' - DataToFit = ReplaceSpecialValues(InputWorkspace=DataToFit, - NaNValue=0, - NaNError=0, - InfinityValue=0, + DataToFit = ReplaceSpecialValues(InputWorkspace=DataToFit,\ + NaNValue=0,\ + NaNError=0,\ + InfinityValue=0,\ InfinityError=0) # ResetNegatives(InputWorkspace='DataToFit', @@ -743,8 +744,8 @@ def fit(self): xmin = xaxis[0] xmax = xaxis[sz/2] - DataToFit = CropWorkspace(InputWorkspace=DataToFit, - XMin=xmin, + DataToFit = CropWorkspace(InputWorkspace=DataToFit,\ + XMin=xmin,\ XMax=xmax) Fit(InputWorkspace=DataToFit, @@ -1134,7 +1135,7 @@ def getSlitsValueAndLambda(full_list_runs, for i in range(_nbr_files): _full_file_name = full_list_runs[i] print '-> ' + _full_file_name - tmpWks = LoadEventNexus(Filename=_full_file_name, + tmpWks = LoadEventNexus(Filename=_full_file_name,\ MetaDataOnly='1') # mt1 = mtd['tmpWks'] _s1h_value = getS1h(tmpWks) @@ -1218,7 +1219,7 @@ def help(): print ' list_' #if __name__ == '__main__': -def calculate(string_runs=None, +def calculate(string_runs=None,\ # list_attenuator=None, list_peak_back=None, incident_medium=None, @@ -1412,10 +1413,10 @@ def calculate(string_runs=None, print 'Done !' - else: - """ - sort the files - """ - pass +# else: +# """ +# sort the files +# """ +# pass diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py index ec44cf7b469a..af5d9d6d5576 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Spencer Howells, ISIS @date December 05, 2013 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py index 5f5028b06537..26f9af3ac401 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Jose Borreguero, NScD @date October 06, 2013 @@ -161,9 +162,9 @@ def function1D(self, xvals): return intensities_interpolator(xvals) # can we pass by reference? # Required to have Mantid recognize the new function +#pylint: unused-import try: import dsfinterp FunctionFactory.subscribe(DSFinterp1DFit) except: logger.debug('Failed to subscribe fit function DSFinterp1DFit; Python package dsfinterp may be missing (https://pypi.python.org/pypi/dsfinterp)') - pass diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py index 7286ee94c80f..f7d2d7ec287a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name """ This example implements a simple Linear function that could be used as a background. diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py index 2564aacabb9c..86aaa24b0b4b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name """ This example reimplements a Gaussian fitting function. It is not meant to be used in production for fitting, it is simply provided as a relatively complete diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py index 250651bd0a91..a73359b318ea 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Spencer Howells, ISIS @date December 05, 2013 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Guinier.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Guinier.py index 96cc08f561d0..204fcec972c1 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Guinier.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Guinier.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Mathieu Doucet, ORNL @date Oct 10, 2014 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/GuinierPorod.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/GuinierPorod.py index c8ee3122b5dc..491779e40d4a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/GuinierPorod.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/GuinierPorod.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Mathieu Doucet, ORNL @date Oct 13, 2014 @@ -131,7 +132,7 @@ def _first_derivative_rg(self, qval): if qval < q1: return -2.0*Rg*math.pow(qval,-s)*math.exp(-qrg/n)*qval*qval/n else: - return math.pow(qval,-m)*math.exp((s-m)/2.0)*math.pow(((m-s)*n/2.0), + return math.pow(qval,-m)*math.exp((s-m)/2.0)*math.pow(((m-s)*n/2.0),\ ((m-s)/2.0))*(s-m)*math.pow(Rg,(s-m-1)) def function1D(self, xvals): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py index 9c83e34f4822..6d90f26f967a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Spencer Howells, ISIS @date December 05, 2013 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Lorentz.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Lorentz.py index 17835da7dba4..6f0b8956e381 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Lorentz.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Lorentz.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Mathieu Doucet, ORNL @date Oct 13, 2014 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Porod.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Porod.py index 47de2227a9e7..69c6729bd0df 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Porod.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Porod.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Mathieu Doucet, ORNL @date Oct 13, 2014 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py index fec011b8174f..8414056e5218 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name ''' @author Jose Borreguero, NScD @date October 06, 2013 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py index a3ebf62a493b..588c534985ca 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Spencer Howells, ISIS @date December 05, 2013 diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py index 71136bf0bd72..b8b8dd5e86af 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Tube Calibration Demonstration for MAPS instrument. @@ -267,17 +268,17 @@ def improvingCalibrationOfListOfTubes(filename): #CalibInstWS = loadingStep(filename) # it is defined as the mean values around the neighbours - define_peaks = {19:[10, 80.9771, 123.221, 164.993, 245.717], # the first one was bad - 37: [6.36, 80.9347, 122.941, 165.104, 248.32], # the first one was bad - 71: [8.62752, 85.074, 124.919, 164.116, 246.82 ], # the last one was bad - check if we can inprove - 75: [14.4285, 90.087, 128.987, 167.047, 242.62], # the last one was bad - check if we can inprove - 181: [11.726, 94.0496, 137.816, 180, 255], # the third peak was lost - 186:[11.9382, 71.5203, 107, 147.727, 239.041], #lost the second peak - 234: [4.84, 82.7824, 123.125, 163.945, 241.877], # the first one was bad - 235: [4.84, 80.0077, 121.002, 161.098, 238.502], # the first one was bad - 245: [9.88089, 93.0593, 136.911, 179.5, 255], # the third peak was bad - 273: [18.3711, 105.5, 145.5, 181.6, 243.252],# lost first and third peaks - 345: [4.6084, 87.0351, 128.125, 169.923, 245.3] # the last one was bad + define_peaks = {19:[10, 80.9771, 123.221, 164.993, 245.717], # the first one was bad\ + 37: [6.36, 80.9347, 122.941, 165.104, 248.32], # the first one was bad\ + 71: [8.62752, 85.074, 124.919, 164.116, 246.82 ], # the last one was bad - check if we can inprove\ + 75: [14.4285, 90.087, 128.987, 167.047, 242.62], # the last one was bad - check if we can inprove\ + 181: [11.726, 94.0496, 137.816, 180, 255], # the third peak was lost\ + 186:[11.9382, 71.5203, 107, 147.727, 239.041], #lost the second peak\ + 234: [4.84, 82.7824, 123.125, 163.945, 241.877], # the first one was bad\ + 235: [4.84, 80.0077, 121.002, 161.098, 238.502], # the first one was bad\ + 245: [9.88089, 93.0593, 136.911, 179.5, 255], # the third peak was bad\ + 273: [18.3711, 105.5, 145.5, 181.6, 243.252],# lost first and third peaks\ + 345: [4.6084, 87.0351, 128.125, 169.923, 245.3] # the last one was bad\ } calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor, fitPar=fitPar, outputPeak=True, overridePeaks=define_peaks) @@ -317,7 +318,7 @@ def calibrateB2Window(filename): fitPar.setAutomatic(True) # == Get the calibration and put results into calibration table == - calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor, + calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,\ fitPar=fitPar, outputPeak=True, plotTube=[b2_range[0], b2_range[-1]], rangeList=b2_range) ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable) @@ -402,7 +403,7 @@ def findThoseTubesThatNeedSpecialCareForCalibration(filename): print 'Calibrating again only these tubes' #let's confir that our suspect works CalibInstWS = loadingStep(filename) - calibrationTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor, + calibrationTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,\ fitPar=fitPar, rangeList= problematic_tubes, plotTube=problematic_tubes) # plot the FittedTube agains TubePlot for each detector and you will see that there were problems on those tubes. @@ -450,16 +451,16 @@ def completeCalibration(filename): # 245: [9.88089, 93.0593, 136.911, 179.5, 255], # the third peak was bad # 273: [18.3711, 105.5, 145.5, 181.6, 243.252],# lost first and third peaks # 345: [4.6084, 87.0351, 128.125, 169.923, 245.3]} # the last one was bad - define_peaks = {19:[10, 80.9771, 123.221, 164.993, 245.717], - 37: [6.36, 80.9347, 122.941, 165.104, 248.32], - 71: [8.62752, 85.074, 124.919, 164.116, 246.82 ], - 75: [14.4285, 90.087, 128.987, 167.047, 242.62], - 181: [11.726, 94.0496, 137.816, 180, 255], - 186:[11.9382, 71.5203, 107, 147.727, 239.041], - 234: [4.84, 82.7824, 123.125, 163.945, 241.877], - 235: [4.84, 80.0077, 121.002, 161.098, 238.502], - 245: [9.88089, 93.0593, 136.911, 179.5, 255], - 273: [18.3711, 105.5, 145.5, 181.6, 243.252], + define_peaks = {19:[10, 80.9771, 123.221, 164.993, 245.717],\ + 37: [6.36, 80.9347, 122.941, 165.104, 248.32],\ + 71: [8.62752, 85.074, 124.919, 164.116, 246.82 ],\ + 75: [14.4285, 90.087, 128.987, 167.047, 242.62],\ + 181: [11.726, 94.0496, 137.816, 180, 255],\ + 186:[11.9382, 71.5203, 107, 147.727, 239.041],\ + 234: [4.84, 82.7824, 123.125, 163.945, 241.877],\ + 235: [4.84, 80.0077, 121.002, 161.098, 238.502],\ + 245: [9.88089, 93.0593, 136.911, 179.5, 255],\ + 273: [18.3711, 105.5, 145.5, 181.6, 243.252],\ 345: [4.6084, 87.0351, 128.125, 169.923, 245.3]} b2_window = range(196,212) + range(222,233) @@ -472,7 +473,7 @@ def completeCalibration(filename): # the group that have 3 stripts are all the tubes except the b2 window and e window. range_3_strips = numpy.setdiff1d(aux, e1_window) - calibrationTable, peak3Table= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor, + calibrationTable, peak3Table= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,\ fitPar=fitPar, outputPeak=True, overridePeaks=define_peaks, rangeList=range_3_strips) # now calibrate the b2_window REMOVE SECOND PEAK @@ -485,12 +486,12 @@ def completeCalibration(filename): fitPar.setAutomatic(True) # apply the calibration for the b2_window 2 strips values - calibrationTable, peak2Table = tube.calibrate(CalibInstWS, CalibratedComponent, - knownPos, #these parameters now have only 4 points - funcFactor, - fitPar=fitPar, - outputPeak=True, - calibTable = calibrationTable, # it will append to the calibTable + calibrationTable, peak2Table = tube.calibrate(CalibInstWS, CalibratedComponent,\ + knownPos, #these parameters now have only 4 points\ + funcFactor,\ + fitPar=fitPar,\ + outputPeak=True,\ + calibTable = calibrationTable, # it will append to the calibTable\ rangeList = b2_window) ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable) diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py index 6cf35b16c19e..5fd30bafafc5 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this # @@ -43,7 +44,7 @@ # == Get the calibration and put results into calibration table == # also put peaks into PeakFile -calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcForm, +calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcForm,\ fitPar=fitPar, outputPeak=True) print "Got calibration (new positions of detectors) " diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py index b721f3915971..43aa7bb692f6 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this # @@ -44,7 +45,7 @@ # == Get the calibration and put results into calibration table == -calibrationTable, peakTable = tube.calibrate(CalibInstWS, thisTubeSet, knownPos, funcForm, +calibrationTable, peakTable = tube.calibrate(CalibInstWS, thisTubeSet, knownPos, funcForm,\ outputPeak=True) print "Got calibration (new positions of detectors) " diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3C2.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3C2.py index a9ba0154f912..7970f60cea8a 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3C2.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3C2.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this # @@ -34,7 +35,7 @@ # == Get the calibration and put results into calibration table == -calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponents, knownPos, funcForm, +calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponents, knownPos, funcForm,\ outputPeak=True) print "Got calibration (new positions of detectors) " diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py index fbc21f214aa7..758a3ea29bc4 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this # diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2_WideMargins.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2_WideMargins.py index b213d898120b..f0e0a43f1f2f 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2_WideMargins.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2_WideMargins.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this # diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D4.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D4.py index 2ef635744983..297626c6a3eb 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D4.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D4.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this # diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py index 966213c22bcb..251a8a4afefe 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Tube Calibration Demonstration program for MERLIN. @@ -98,10 +99,10 @@ def calibrateMerlin(filename): CalibratedComponent = 'MERLIN/door9' # door9 # == Get the calibration and put results into calibration table == # also put peaks into PeakFile - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door9pos, door9func, - outputPeak=True, - margin=30, - rangeList=range(20) # because 20, 21, 22, 23 are defective detectors + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door9pos, door9func,\ + outputPeak=True,\ + margin=30,\ + rangeList=range(20) # because 20, 21, 22, 23 are defective detectors\ ) print "Got calibration (new positions of detectors) and put slit peaks into file TubeDemoMerlin01.txt" analisePeakTable(peakTable, 'door9_tube1_peaks') @@ -110,10 +111,10 @@ def calibrateMerlin(filename): door8pos = points7 door8func = points7func CalibratedComponent = 'MERLIN/door8' - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door8pos, - door8func, - outputPeak = True, #change to peakTable to append to peakTable - calibTable = calibrationTable, + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door8pos,\ + door8func,\ + outputPeak = True, #change to peakTable to append to peakTable\ + calibTable = calibrationTable,\ margin = 30) analisePeakTable(peakTable, 'door8_peaks') @@ -121,10 +122,10 @@ def calibrateMerlin(filename): doorpos = knownPositions doorfunc = funcForm CalibratedComponent = ['MERLIN/door%d'%(i) for i in [7,6,5,4, 2, 1]] - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, - doorfunc, - outputPeak = True, - calibTable = calibrationTable, + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos,\ + doorfunc,\ + outputPeak = True,\ + calibTable = calibrationTable,\ margin = 30) analisePeakTable(peakTable, 'door1to7_peaks') @@ -159,11 +160,11 @@ def calibrateMerlin(filename): fitPar = TubeCalibFitParams([216, 527, 826, 989]) fitPar.setAutomatic(True) - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, - doorfunc, - outputPeak = True, - fitPar = fitPar, - calibTable = calibrationTable, + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos,\ + doorfunc,\ + outputPeak = True,\ + fitPar = fitPar,\ + calibTable = calibrationTable,\ margin = 30) analisePeakTable(peakTable, 'door3_tube1_peaks') @@ -180,11 +181,11 @@ def calibrateMerlin(filename): fitPar = TubeCalibFitParams([50, 202, 664, 815]) fitPar.setAutomatic(True) - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, - doorfunc, - outputPeak = True, - calibTable = calibrationTable, - fitPar = fitPar, + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos,\ + doorfunc,\ + outputPeak = True,\ + calibTable = calibrationTable,\ + fitPar = fitPar,\ margin = 30) analisePeakTable(peakTable, 'door3_tube2_peaks') @@ -194,10 +195,10 @@ def calibrateMerlin(filename): CalibratedComponent = ['MERLIN/door3/tube_3_%d'%(i) for i in [1,2,3]] doorpos = knownPositions[[0,1,2,3,5,6,7,8]] doorfunc = funcForm[[0,1,2,3,5,6,7,8]] - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, - doorfunc, - outputPeak = True, - calibTable = calibrationTable, + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos,\ + doorfunc,\ + outputPeak = True,\ + calibTable = calibrationTable,\ margin = 30) analisePeakTable(peakTable, 'door3_123_peaks') @@ -209,10 +210,10 @@ def calibrateMerlin(filename): CalibratedComponent = part_3 + part_4 + part_5 doorpos = knownPositions doorfunc = funcForm - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, - doorfunc, - outputPeak = True, - calibTable = calibrationTable, + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos,\ + doorfunc,\ + outputPeak = True,\ + calibTable = calibrationTable,\ margin = 30) analisePeakTable(peakTable, 'door3_peaks') diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin_Simple.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin_Simple.py index b040e44f5390..399335faf64f 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin_Simple.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin_Simple.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MERLIN # @@ -67,7 +68,7 @@ def CalibrateMerlin(RunNumber): # == Get the calibration and put results into calibration table == # also put peaks into PeakFile - calibrationTable,peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcForm, + calibrationTable,peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcForm,\ outputPeak=True, fitPar=fitPar, plotTube=range(0,280,20)) print "Got calibration (new positions of detectors) and put slit peaks into file TubeDemoMerlin01.txt" diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish0.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish0.py index 6fd05fb722c6..515be0cd67a9 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish0.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish0.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM - Execute this # diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish1.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish1.py index 527e692073b5..49b55f4aeb62 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish1.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish1.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM - Execute this # diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py index cc784399c72a..f704352ba7d3 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR WISH # diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py index 4736c9a00f24..2b34e99bde9a 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR WISH # @@ -39,14 +40,14 @@ def CalibrateWish( RunNumber, PanelNumber): # Get the calibration and put it into the calibration table #calibrate the lower tubes - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, lower_tube, funcForm, + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, lower_tube, funcForm,\ rangeList = range(0,76), outputPeak=True) #calibrate the upper tubes - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, upper_tube, funcForm, - rangeList = range(76,152), - calibTable=calibrationTable, #give the calibration table to append data - outputPeak = peakTable #give peak table to append data + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, upper_tube, funcForm,\ + rangeList = range(76,152),\ + calibTable=calibrationTable, #give the calibration table to append data\ + outputPeak = peakTable #give peak table to append data\ ) print "Got calibration (new positions of detectors)" diff --git a/Code/Mantid/scripts/Calibration/tube.py b/Code/Mantid/scripts/Calibration/tube.py index 4fc377c7a44c..263b033675d9 100644 --- a/Code/Mantid/scripts/Calibration/tube.py +++ b/Code/Mantid/scripts/Calibration/tube.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ ========================= Definition of Calibration @@ -555,7 +556,7 @@ def calibrate(ws, tubeSet, knownPositions, funcForm, **kwargs): for i in range(len(idealTube.getArray())): outputPeak.addColumn(type='float',name='Peak%d'%(i+1)) - getCalibration(ws, tubeSet, calibTable, fitPar, idealTube, outputPeak, + getCalibration(ws, tubeSet, calibTable, fitPar, idealTube, outputPeak,\ overridePeaks, excludeShortTubes, plotTube, rangeList, polinFit) if deletePeakTableAfter: diff --git a/Code/Mantid/scripts/Calibration/tube_calib.py b/Code/Mantid/scripts/Calibration/tube_calib.py index 91c3f8fd5b7a..a3b46699b35d 100644 --- a/Code/Mantid/scripts/Calibration/tube_calib.py +++ b/Code/Mantid/scripts/Calibration/tube_calib.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ This file is concerned with calibrating a specified set of tubes @@ -150,7 +151,7 @@ def fitGaussian(fitPar, index, ws, outputWs): fit_msg = 'name=LinearBackground,A0=%f;name=Gaussian,Height=%f,PeakCentre=%f,Sigma=%f'%(background, height, centre, width) - Fit(InputWorkspace=ws, Function=fit_msg, + Fit(InputWorkspace=ws, Function=fit_msg,\ StartX = str(start), EndX=str(end), Output=outputWs) peakIndex = 3 @@ -226,7 +227,7 @@ def getPoints ( IntegratedWorkspace, funcForms, fitParams, whichTube, showPlot=F fitt_x_values.append(copy.copy(ws.dataX(1))) if showPlot: - FittedData = CreateWorkspace(numpy.hstack(fitt_x_values), + FittedData = CreateWorkspace(numpy.hstack(fitt_x_values),\ numpy.hstack(fitt_y_values)) return results diff --git a/Code/Mantid/scripts/Calibration/tube_spec.py b/Code/Mantid/scripts/Calibration/tube_spec.py index 4ce88e2224c2..c699cc3b1edb 100644 --- a/Code/Mantid/scripts/Calibration/tube_spec.py +++ b/Code/Mantid/scripts/Calibration/tube_spec.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from mantid.simpleapi import * from mantid.kernel import * diff --git a/Code/Mantid/scripts/CrystalTools/PeakReport.py b/Code/Mantid/scripts/CrystalTools/PeakReport.py index d7efe450ce81..eb435047225e 100644 --- a/Code/Mantid/scripts/CrystalTools/PeakReport.py +++ b/Code/Mantid/scripts/CrystalTools/PeakReport.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ This is a module for creating peak integration reports. """ diff --git a/Code/Mantid/scripts/DGS_Reduction.py b/Code/Mantid/scripts/DGS_Reduction.py index f0c080f1d434..0413c2158f5f 100644 --- a/Code/Mantid/scripts/DGS_Reduction.py +++ b/Code/Mantid/scripts/DGS_Reduction.py @@ -1,8 +1,8 @@ +#pylint: disable=invalid-name """ Script used to start the DGS reduction GUI from MantidPlot """ from reduction_application import ReductionGUI -from PyQt4 import QtCore, uic reducer = ReductionGUI(instrument_list=["ARCS", "CNCS", "HYSPEC", "MAPS", "MARI", "MERLIN", "SEQUOIA"]) diff --git a/Code/Mantid/scripts/Engineering/EnginXUtils.py b/Code/Mantid/scripts/Engineering/EnginXUtils.py index 15f74b45b94b..dfcd58de7fc8 100644 --- a/Code/Mantid/scripts/Engineering/EnginXUtils.py +++ b/Code/Mantid/scripts/Engineering/EnginXUtils.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import os from mantid.api import * diff --git a/Code/Mantid/scripts/Examples/HRPDDialog_Example.py b/Code/Mantid/scripts/Examples/HRPDDialog_Example.py index ba375bc86c97..80d97b05c2b9 100644 --- a/Code/Mantid/scripts/Examples/HRPDDialog_Example.py +++ b/Code/Mantid/scripts/Examples/HRPDDialog_Example.py @@ -1,6 +1,7 @@ +#pylint: disable=invalid-name # First a function definition for the Loading algorithms which loads the data and immediately aligns the detectors -def LoadAndAlign(type, outputArea): - LoadRawDialog(OutputWorkspace=outputArea, Message = "Enter path to the file containing the " + type) +def LoadAndAlign(_type, outputArea): + LoadRawDialog(OutputWorkspace=outputArea, Message = "Enter path to the file containing the " + _type) AlignDetectorsDialog(InputWorkspace=outputArea, OutputWorkspace=outputArea,Message="Enter path to calibration file") # ========== The script starts here ============ @@ -14,7 +15,8 @@ def LoadAndAlign(type, outputArea): transWorkspace="Transmission" #The input workspace needs to be in units of wavelength for the CylinderAbsorption algorithm ConvertUnits(InputWorkspace=dataWorkspace, OutputWorkspace=dataWorkspace, Target="Wavelength") -CylinderAbsorptionDialog(InputWorkspace=dataWorkspace, OutputWorkspace=transWorkspace,SampleNumberDensity="0.072",ScatteringXSection="5.08",AttenuationXSection="5.1",Message="Enter size parameters") +CylinderAbsorptionDialog(InputWorkspace=dataWorkspace, OutputWorkspace=transWorkspace,SampleNumberDensity="0.072",\ + ScatteringXSection="5.08",AttenuationXSection="5.1",Message="Enter size parameters") Divide(dataWorkspace, transWorkspace, OutputWorkspace=dataWorkspace) # === Save as a Nexus file === diff --git a/Code/Mantid/scripts/Examples/InstrumentView_Example.py b/Code/Mantid/scripts/Examples/InstrumentView_Example.py index d3be938cbe73..0571ba5c39c2 100644 --- a/Code/Mantid/scripts/Examples/InstrumentView_Example.py +++ b/Code/Mantid/scripts/Examples/InstrumentView_Example.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # Example: Instrument view control # diff --git a/Code/Mantid/scripts/Examples/PlotAsymmetryByLogValue_Example.py b/Code/Mantid/scripts/Examples/PlotAsymmetryByLogValue_Example.py index 12c2e9763851..b9ea09ffbcfd 100644 --- a/Code/Mantid/scripts/Examples/PlotAsymmetryByLogValue_Example.py +++ b/Code/Mantid/scripts/Examples/PlotAsymmetryByLogValue_Example.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # ----------------------------------------------------- # Runs PlotAssymetryByLogValue algorithm # and plots the output in MantidPlot using a Python diff --git a/Code/Mantid/scripts/Examples/SampleLogs_Demo.py b/Code/Mantid/scripts/Examples/SampleLogs_Demo.py index 84e9856211da..b1c54bb46fd4 100644 --- a/Code/Mantid/scripts/Examples/SampleLogs_Demo.py +++ b/Code/Mantid/scripts/Examples/SampleLogs_Demo.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # Example: Retrieving log information from a data set # diff --git a/Code/Mantid/scripts/Examples/SimpleMtdCommands_Example.py b/Code/Mantid/scripts/Examples/SimpleMtdCommands_Example.py index 08702ddd09f6..ed5b145a58cd 100644 --- a/Code/Mantid/scripts/Examples/SimpleMtdCommands_Example.py +++ b/Code/Mantid/scripts/Examples/SimpleMtdCommands_Example.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # Example: Basic Mantid commands # diff --git a/Code/Mantid/scripts/Examples/SolidAngle_Example.py b/Code/Mantid/scripts/Examples/SolidAngle_Example.py index 7243aa427424..5b692ebf80a9 100644 --- a/Code/Mantid/scripts/Examples/SolidAngle_Example.py +++ b/Code/Mantid/scripts/Examples/SolidAngle_Example.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name ##------------------------------------------------------------------------- ## ## Example: Calculating the solid angle for a spectrum with respect to the diff --git a/Code/Mantid/scripts/Examples/StripPeaks.py b/Code/Mantid/scripts/Examples/StripPeaks.py index d86bca436fbc..32bd47a83b62 100644 --- a/Code/Mantid/scripts/Examples/StripPeaks.py +++ b/Code/Mantid/scripts/Examples/StripPeaks.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # MantidPlot example script # # Using StripPeaks + dialog boxes diff --git a/Code/Mantid/scripts/Examples/TableWorkspace_Example.py b/Code/Mantid/scripts/Examples/TableWorkspace_Example.py index 6f139c8fff2f..1e92cfbd40cc 100644 --- a/Code/Mantid/scripts/Examples/TableWorkspace_Example.py +++ b/Code/Mantid/scripts/Examples/TableWorkspace_Example.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # Perform some algorithms LoadRaw(Filename="GEM40979.raw",OutputWorkspace="GEM40979") AlignDetectors("GEM40979",OutputWorkspace="aligned",CalibrationFile="offsets_2006_cycle064.cal") diff --git a/Code/Mantid/scripts/FilterEvents.py b/Code/Mantid/scripts/FilterEvents.py index 3b14caff0bfe..f05876cec2c0 100644 --- a/Code/Mantid/scripts/FilterEvents.py +++ b/Code/Mantid/scripts/FilterEvents.py @@ -1,13 +1,14 @@ +#pylint: disable=invalid-name from FilterEvents import eventFilterGUI from PyQt4 import QtGui import sys def qapp(): if QtGui.QApplication.instance(): - app = QtGui.QApplication.instance() + _app = QtGui.QApplication.instance() else: - app = QtGui.QApplication(sys.argv) - return app + _app = QtGui.QApplication(sys.argv) + return _app app = qapp() diff --git a/Code/Mantid/scripts/FilterEvents/MplFigureCanvas.py b/Code/Mantid/scripts/FilterEvents/MplFigureCanvas.py index 70749903430c..509e7462fbea 100644 --- a/Code/Mantid/scripts/FilterEvents/MplFigureCanvas.py +++ b/Code/Mantid/scripts/FilterEvents/MplFigureCanvas.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui import matplotlib @@ -21,7 +22,7 @@ def __init__(self, parent): self.setParent(parent) # Set size policy to be able to expanding and resizable with frame - FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, + FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding,\ QtGui.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) diff --git a/Code/Mantid/scripts/FilterEvents/Ui_ErrorMessage.py b/Code/Mantid/scripts/FilterEvents/Ui_ErrorMessage.py index f041fd467936..19d9b11778f4 100644 --- a/Code/Mantid/scripts/FilterEvents/Ui_ErrorMessage.py +++ b/Code/Mantid/scripts/FilterEvents/Ui_ErrorMessage.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ErrorMessage.ui' diff --git a/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py b/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py index 4f757a818fc9..4825002090f6 100644 --- a/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py +++ b/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'MainWindow.ui' diff --git a/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py b/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py index 5a8a55e32d60..2816abce37c6 100644 --- a/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py +++ b/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import math import numpy @@ -195,9 +196,9 @@ def __init__(self, parent=None): self.ui.lineEdit_8.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_8)) self.ui.lineEdit_9.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_9)) - self.connect(self.ui.lineEdit_5, QtCore.SIGNAL("textChanged(QString)"), + self.connect(self.ui.lineEdit_5, QtCore.SIGNAL("textChanged(QString)"),\ self.set_minLogValue) - self.connect(self.ui.lineEdit_6, QtCore.SIGNAL("textChanged(QString)"), + self.connect(self.ui.lineEdit_6, QtCore.SIGNAL("textChanged(QString)"),\ self.set_maxLogValue) dirchangeops = ["Both", "Increase", "Decrease"] @@ -658,7 +659,7 @@ def set_maxLogValue(self): def browse_File(self): """ Open a file dialog to get file """ - filename = QtGui.QFileDialog.getOpenFileName(self, 'Input File Dialog', + filename = QtGui.QFileDialog.getOpenFileName(self, 'Input File Dialog',\ self._defaultdir, "Data (*.nxs *.dat);;All files (*.*)") self.ui.lineEdit.setText(str(filename)) @@ -959,7 +960,7 @@ def _plotTimeCounts(self, wksp): sumwsname = "_Summed_%s"%(str(wksp)) if AnalysisDataService.doesExist(sumwsname) is False: - sumws = api.RebinByPulseTimes(InputWorkspace=wksp, OutputWorkspace = sumwsname, + sumws = api.RebinByPulseTimes(InputWorkspace=wksp, OutputWorkspace = sumwsname,\ Params="0, %f, %d"%(timeres, timeduration)) sumws = api.SumSpectra(InputWorkspace=sumws, OutputWorkspace=str(sumws)) sumws = api.ConvertToPointData(InputWorkspace=sumws, OutputWorkspace=str(sumws)) diff --git a/Code/Mantid/scripts/ISIS_Reflectometry.py b/Code/Mantid/scripts/ISIS_Reflectometry.py index 223b2c98b0ab..f06283585df5 100644 --- a/Code/Mantid/scripts/ISIS_Reflectometry.py +++ b/Code/Mantid/scripts/ISIS_Reflectometry.py @@ -1,8 +1,7 @@ +#pylint: disable=invalid-name """ Script used to start the ISIS Reflectomery GUI from MantidPlot """ -from PyQt4 import QtGui -#, QtCore from ui.reflectometer import refl_gui ui = refl_gui.ReflGui() diff --git a/Code/Mantid/scripts/Inelastic/Direct/CommonFunctions.py b/Code/Mantid/scripts/Inelastic/Direct/CommonFunctions.py index 26d5a8e749fb..3db587f22559 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/CommonFunctions.py +++ b/Code/Mantid/scripts/Inelastic/Direct/CommonFunctions.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import mantid from mantid.simpleapi import * from mantid import api diff --git a/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py b/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py index 34d660382b0c..dca70d0e2ffc 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py +++ b/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from mantid.simpleapi import * from mantid.kernel import funcreturns from mantid import geometry,api @@ -202,7 +203,7 @@ def diagnose(self, white,diag_sample=None,**kwargs): # stuff and can load masks directly white_data = white.get_ws_clone('white_ws_clone') - diag_mask = LoadMask(Instrument=self.instr_name,InputFile=self.hard_mask_file, + diag_mask = LoadMask(Instrument=self.instr_name,InputFile=self.hard_mask_file,\ OutputWorkspace='hard_mask_ws') MaskDetectors(Workspace=white_data, MaskedWorkspace=diag_mask) DeleteWorkspace(diag_mask) @@ -236,15 +237,15 @@ def diagnose(self, white,diag_sample=None,**kwargs): #>>> here result workspace is being processed -- not touching #result ws bkgd_range = self.background_test_range - background_int = Integration(result_ws, - RangeLower=bkgd_range[0],RangeUpper=bkgd_range[1], + background_int = Integration(result_ws,\ + RangeLower=bkgd_range[0],RangeUpper=bkgd_range[1],\ IncludePartialBins=True) total_counts = Integration(result_ws, IncludePartialBins=True) background_int = ConvertUnits(background_int, Target="Energy",EMode='Elastic', AlignBins=0) self.prop_man.log("Diagnose: finished convertUnits ",'information') background_int *= self.scale_factor - diagnostics.normalise_background(background_int, whiteintegrals, + diagnostics.normalise_background(background_int, whiteintegrals,\ diag_params.get('second_white',None)) diag_params['background_int'] = background_int diag_params['sample_counts'] = total_counts @@ -342,7 +343,7 @@ def convert_to_energy(self,wb_run=None,sample_run=None,ei_guess=None,rebin=None, # if it is set that way if not masks_done: prop_man.log("======== Run diagnose for sample run ===========================",'notice') - masking = self.diagnose(PropertyManager.wb_run,PropertyManager.mask_run, + masking = self.diagnose(PropertyManager.wb_run,PropertyManager.mask_run,\ second_white=None,print_diag_results=True) if prop_man.use_hard_mask_only: header = "*** Hard mask file applied to workspace with {0:d} spectra masked {1:d} spectra" @@ -363,7 +364,7 @@ def convert_to_energy(self,wb_run=None,sample_run=None,ei_guess=None,rebin=None, # solution for that. prop_man.log("======== Run diagnose for monochromatic vanadium run ===========",'notice') - masking2 = self.diagnose(PropertyManager.wb_for_monovan_run,PropertyManager.monovan_run, + masking2 = self.diagnose(PropertyManager.wb_for_monovan_run,PropertyManager.monovan_run,\ second_white = None,print_diag_results=True) masking += masking2 DeleteWorkspace(masking2) @@ -441,7 +442,7 @@ def convert_to_energy(self,wb_run=None,sample_run=None,ei_guess=None,rebin=None, #--------------- #Run the conversion first on the sample - deltaE_ws_sample = self.mono_sample(PropertyManager.sample_run,ei_guess,PropertyManager.wb_run, + deltaE_ws_sample = self.mono_sample(PropertyManager.sample_run,ei_guess,PropertyManager.wb_run,\ self.map_file,masking) # calculate absolute units integral and apply it to the workspace @@ -452,18 +453,18 @@ def convert_to_energy(self,wb_run=None,sample_run=None,ei_guess=None,rebin=None, self.check_background= False # what we want to do with absolute units: if self.mono_correction_factor: # Correction provided. Just apply it - deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run, + deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run,\ ei_guess,PropertyManager.wb_for_monovan_run) elif cashed_mono_int: # Correction cashed from previous run self.mono_correction_factor = cashed_mono_int - deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run, + deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run,\ ei_guess,PropertyManager.wb_for_monovan_run) self.mono_correction_factor = None else: # Calculate corrections if self._multirep_mode and calculate_abs_units: - mono_ws_base = PropertyManager.monovan_run.chop_ws_part(mono_ws_base,tof_range,self._do_early_rebinning, + mono_ws_base = PropertyManager.monovan_run.chop_ws_part(mono_ws_base,tof_range,self._do_early_rebinning,\ cut_ind,num_ei_cuts) - deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run, + deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run,\ ei_guess,PropertyManager.wb_for_monovan_run) self.check_background = current_bkg_opt @@ -542,7 +543,7 @@ def mono_sample(self, mono_run, ei_guess, white_run=None, map_file=None, white_run = self.get_run_descriptor(white_run) - mono_s = self._do_mono(mono_run, ei_guess, + mono_s = self._do_mono(mono_run, ei_guess,\ white_run, map_file, spectra_masks, Tzero) # at this stage we would never need monitors for this workspace if they # were actually there @@ -623,7 +624,7 @@ def get_ei(self, data_run, ei_guess): # case) #Find TOF range, correspondent to incident energy monitor peak energy_rage = self.mon2_norm_energy_range - self._mon2_norm_time_range = self.get_TOF_for_energies(monitor_ws,energy_rage, + self._mon2_norm_time_range = self.get_TOF_for_energies(monitor_ws,energy_rage,\ [self.mon2_norm_spec],None,self._debug_mode) #end if separate_monitors: @@ -658,7 +659,7 @@ def remap(self, result_ws, spec_masks, map_file): if not spec_masks is None: MaskDetectors(Workspace=ws_name, MaskedWorkspace=spec_masks) if not map_file is None: - GroupDetectors(InputWorkspace=ws_name,OutputWorkspace=ws_name, + GroupDetectors(InputWorkspace=ws_name,OutputWorkspace=ws_name,\ MapFile= map_file, KeepUngroupedSpectra=0, Behaviour='Average') return mtd[ws_name] @@ -1149,7 +1150,7 @@ def get_abs_normalization_factor(self,deltaE_wkspaceName,ei_monovan): "--------> Abs norm factors: Sigma^2: {9}\n"\ "--------> Abs norm factors: Poisson: {10}\n"\ "--------> Abs norm factors: TGP : {11}\n"\ - .format(deltaE_wkspaceName,minmax[0],minmax[1],nhist,sum(signal),sum(error),izerc,scale_factor, + .format(deltaE_wkspaceName,minmax[0],minmax[1],nhist,sum(signal),sum(error),izerc,scale_factor,\ norm_factor['LibISIS'],norm_factor['SigSq'],norm_factor['Poisson'],norm_factor['TGP']) log_value = log_value + log1_value propman.log(log_value,'error') @@ -1279,14 +1280,14 @@ def get_run_descriptor(self,run): # mono-vanadium runs # # ------------------------------------------------------------------------------------------- - def _do_mono_SNS(self, data_ws, result_name, ei_guess, + def _do_mono_SNS(self, data_ws, result_name, ei_guess,\ white_run=None, map_file=None, spectra_masks=None, Tzero=None): # does not work -- retrieve from repo and fix raise NotImplementedError("Non currently implemented. Retrieve from repository" " if necessary and fix") return #------------------------------------------------------------------------------- - def _do_mono_ISIS(self, data_run, ei_guess, + def _do_mono_ISIS(self, data_run, ei_guess,\ white_run=None, map_file=None, spectra_masks=None, Tzero=None): # Do ISIS stuff for Ei @@ -1369,7 +1370,7 @@ def _find_or_build_bkgr_ws(self,result_ws,bkg_range_min=None,bkg_range_max=None, # one needs to do appropriate shift here as well CopyInstrumentParameters(result_ws,bkgr_ws) # Adjust the TOF such that the first monitor peak is at t=0 - ScaleX(InputWorkspace=bkgr_ws,OutputWorkspace='bkgr_ws',Operation="Add",Factor=time_shift, + ScaleX(InputWorkspace=bkgr_ws,OutputWorkspace='bkgr_ws',Operation="Add",Factor=time_shift,\ InstrumentParameter="DelayTime",Combine=True) else: bkgr_ws = Rebin(result_ws,Params=[bkg_range_min,(bkg_range_max - bkg_range_min) * 1.001,bkg_range_max],PreserveEvents=False) @@ -1386,11 +1387,11 @@ def _do_mono(self, run, ei_guess, """ if (self._do_ISIS_reduction): - self._do_mono_ISIS(run,ei_guess, + self._do_mono_ISIS(run,ei_guess,\ white_run, map_file, spectra_masks, Tzero) else: result_name = run.set_action_suffix('_spe') - self._do_mono_SNS(run,result_name,ei_guess, + self._do_mono_SNS(run,result_name,ei_guess,\ white_run, map_file, spectra_masks, Tzero) run.synchronize_ws() diff --git a/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py b/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py index 7fcdcf165c34..2e775a0b0f1e 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py +++ b/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PropertiesDescriptors import * from RunDescriptor import RunDescriptor,RunDescriptorDependent diff --git a/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py b/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py index b2efa1f7dcbc..87aadf239b50 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py +++ b/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ File contains collection of Descriptors used to define complex properties in NonIDF_Properties and PropertyManager classes """ @@ -163,16 +164,16 @@ def load_and_sum_runs(self,inst_name,monitors_with_ws): format(ind + 2,num_to_load,run_num)) term_name = '{0}_ADDITIVE_#{1}/{2}'.format(inst_name,ind + 2,num_to_load)# - wsp = self._sample_run.load_file(inst_name,term_name,False, + wsp = self._sample_run.load_file(inst_name,term_name,False,\ monitors_with_ws,False,file_hint=file_h) wsp_name = wsp.name() wsp_mon_name = wsp_name + '_monitors' - Plus(LHSWorkspace=sum_ws_name,RHSWorkspace=wsp_name, + Plus(LHSWorkspace=sum_ws_name,RHSWorkspace=wsp_name,\ OutputWorkspace=sum_ws_name,ClearRHSWorkspace=True) AddedRunNumbers+=',{0}'.format(run_num) if not monitors_with_ws: - Plus(LHSWorkspace=sum_mon_name,RHSWorkspace=wsp_mon_name, + Plus(LHSWorkspace=sum_mon_name,RHSWorkspace=wsp_mon_name,\ OutputWorkspace=sum_mon_name,ClearRHSWorkspace=True) if wsp_name in mtd: DeleteWorkspace(wsp_name) @@ -370,7 +371,7 @@ def get_abs_range(self,instance=None): else: if instance: instance.log("*** WARNING! Got energy_bins specified as absolute values in multirep mode.\n"\ - " Will normalize these values by max value and treat as relative values ", + " Will normalize these values by max value and treat as relative values ",\ "warning") mult = self._range / self._energy_bins[2] rez = self._calc_relative_range(ei,mult) @@ -383,7 +384,7 @@ def get_abs_range(self,instance=None): else: if instance: instance.log("*** WARNING! Requested maximum binning range exceeds incident energy!\n"\ - " Will normalize binning range by max value and treat as relative range", + " Will normalize binning range by max value and treat as relative range",\ "warning") mult = self._range / self._energy_bins[2] ei = self._incident_energy.get_current() @@ -520,7 +521,7 @@ def __set__(self,instance,val): val = self._parce_string2list(val) self.__set__(instance,val) else: - raise KeyError('mon2_norm_energy_range needs to be initialized by two values.\n' + raise KeyError('mon2_norm_energy_range needs to be initialized by two values.\n'\ 'Trying to assign value {0} of unknown type {1}'.format(val,type(val))) # def _check_range(self,val,instance): @@ -727,7 +728,6 @@ def __init__(self,DepType=None): else: self._rel_range = True prop_helpers.ComplexProperty.__init__(self,['monovan_lo_frac','monovan_hi_frac']) - pass def __get__(self,instance,owner): diff --git a/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py b/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py index 9e436d64316f..dbea0fcda92b 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py +++ b/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from NonIDF_Properties import * from collections import OrderedDict diff --git a/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py b/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py index 73c3b8038457..687a731b6f58 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py +++ b/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from mantid import config import os @@ -249,8 +250,7 @@ def gen_setter(keyval_dict,key,val): if isinstance(test_val,ComplexProperty): if not isinstance(val,list): raise KeyError(' You can not assign non-list value to complex property {0}'.format(key)) - pass - # Assigning values for composite function to the function components + # Assigning values for composite function to the function components test_val.__set__(keyval_dict,val) return None else: diff --git a/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py b/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py index fa65b83f4067..ee28a46f9c19 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py +++ b/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from mantid.simpleapi import * from mantid import config,api from mantid.kernel import funcreturns @@ -21,7 +22,6 @@ class var_holder(object): def __init__(self): self.standard_vars = None self.advanced_vars = None - pass def __init__(self,instrumentName,web_var=None): """ sets properties defaults for the instrument with Name @@ -162,8 +162,8 @@ def build_or_validate_result(self,sample_run,validationFile,build_validation=Fal else: if isinstance(reduced,list): # check only first result in multirep reduced = reduced[0] - result = CheckWorkspacesMatch(Workspace1=sample,Workspace2=reduced, - Tolerance=Error,CheckSample=False, + result = CheckWorkspacesMatch(Workspace1=sample,Workspace2=reduced,\ + Tolerance=Error,CheckSample=False,\ CheckInstrument=False,ToleranceRelErr=ToleranceRelErr) self.wait_for_file = current_wait_state diff --git a/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py b/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py index e403133dc79b..a8f3240fb30f 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py +++ b/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ File contains Descriptors used describe run for direct inelastic reduction """ diff --git a/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py b/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py index 67ebb7df6fb5..ac74d3baf48c 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py +++ b/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Empty class temporary left for compatibility with previous interfaces """ import DirectEnergyConversion as DRC import CommonFunctions as common diff --git a/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py b/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py index a48b55901abc..76ba5a12bb48 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py +++ b/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py @@ -90,9 +90,9 @@ def diagnose(white_int,**kwargs): # Second white beam test if 'second_white' in kwargs: - __second_white_masks, num_failed = do_second_white_test(white_int, parser.second_white, parser.tiny, parser.huge, - parser.van_out_lo, parser.van_out_hi, - parser.van_lo, parser.van_hi, parser.variation, + __second_white_masks, num_failed = do_second_white_test(white_int, parser.second_white, parser.tiny, parser.huge,\ + parser.van_out_lo, parser.van_out_hi,\ + parser.van_lo, parser.van_hi, parser.variation,\ parser.van_sig, start_index, end_index) test_results[2] = [str(__second_white_masks), num_failed] add_masking(white_int, __second_white_masks, start_index, end_index) @@ -103,8 +103,8 @@ def diagnose(white_int,**kwargs): zero_count_failures = 0 if kwargs.get('sample_counts',None) is not None and kwargs.get('samp_zero',False): add_masking(parser.sample_counts, white_int) - maskZero, zero_count_failures = FindDetectorsOutsideLimits(InputWorkspace=parser.sample_counts, - StartWorkspaceIndex=start_index, EndWorkspaceIndex=end_index, + maskZero, zero_count_failures = FindDetectorsOutsideLimits(InputWorkspace=parser.sample_counts,\ + StartWorkspaceIndex=start_index, EndWorkspaceIndex=end_index,\ LowThreshold=1e-10, HighThreshold=1e100) add_masking(white_int, maskZero, start_index, end_index) DeleteWorkspace(maskZero) @@ -114,7 +114,7 @@ def diagnose(white_int,**kwargs): # if hasattr(parser, 'background_int'): add_masking(parser.background_int, white_int) - __bkgd_mask, failures = do_background_test(parser.background_int, parser.samp_lo, + __bkgd_mask, failures = do_background_test(parser.background_int, parser.samp_lo,\ parser.samp_hi, parser.samp_sig, parser.samp_zero, start_index, end_index) test_results[3] = [str(__bkgd_mask), zero_count_failures + failures] add_masking(white_int, __bkgd_mask, start_index, end_index) @@ -185,8 +185,8 @@ def do_white_test(white_int, tiny, large, out_lo, out_hi, median_lo, median_hi, # Make sure we are a MatrixWorkspace white_int = ConvertToMatrixWorkspace(InputWorkspace=white_int,OutputWorkspace=white_int) # The output workspace will have the failed detectors masked - white_masks,num_failed = FindDetectorsOutsideLimits(white_int, StartWorkspaceIndex=start_index, - EndWorkspaceIndex=end_index, + white_masks,num_failed = FindDetectorsOutsideLimits(white_int, StartWorkspaceIndex=start_index,\ + EndWorkspaceIndex=end_index,\ HighThreshold=large, LowThreshold=tiny) MaskDetectors(Workspace=white_int, MaskedWorkspace=white_masks, @@ -279,7 +279,7 @@ def normalise_background(background_int, white_int, second_white_int=None): DeleteWorkspace(hmean) #------------------------------------------------------------------------------ -def do_background_test(background_int, median_lo, median_hi, sigma, mask_zero, +def do_background_test(background_int, median_lo, median_hi, sigma, mask_zero,\ start_index=None, end_index=None): """ Run the background tests diff --git a/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py b/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py index 532cf685079a..11a587e4f47e 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py +++ b/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # IDA F2PY Absorption Corrections Wrapper ## Handle selection of .pyd files for absorption corrections import platform, sys @@ -163,7 +164,7 @@ def AbsRun(inputWS, geom, beam, ncan, size, density, sigs, siga, avar, Save): raise ValueError('Number of steps ( ' + str(nstep) + ' ) should be >= 20') angle = det[n] - kill, A1, A2, A3, A4 = cylabs.cylabs(astep, beam, ncan, size, + kill, A1, A2, A3, A4 = cylabs.cylabs(astep, beam, ncan, size,\ density, sigs, siga, angle, wavelas, waves, n, wrk, 0) if kill == 0: diff --git a/Code/Mantid/scripts/Inelastic/IndirectBayes.py b/Code/Mantid/scripts/Inelastic/IndirectBayes.py index a4fb2aacdacf..034439f50f60 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectBayes.py +++ b/Code/Mantid/scripts/Inelastic/IndirectBayes.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # Bayes routines # Fortran programs use fixed length arrays whereas Python has variable lenght lists # Input : the Python list is padded to Fortrans length using procedure PadArray @@ -271,8 +272,8 @@ def QLRun(program,samWS,resWS,resnormWS,erange,nbins,Fit,wfile,Loop,Plot,Save): message = ' Log(prob) : '+str(yprob[0])+' '+str(yprob[1])+' '+str(yprob[2])+' '+str(yprob[3]) logger.information(message) if prog == 'QSe': - nd,xout,yout,eout,yfit,yprob=Qse.qlstexp(numb,Xv,Yv,Ev,reals,fitOp, - Xdat,Xb,Yb,Wy,We,dtn,xsc, + nd,xout,yout,eout,yfit,yprob=Qse.qlstexp(numb,Xv,Yv,Ev,reals,fitOp,\ + Xdat,Xb,Yb,Wy,We,dtn,xsc,\ wrks,wrkr,lwrk) dataX = xout[:nd] dataX = np.append(dataX,2*xout[nd-1]-xout[nd-2]) @@ -315,7 +316,7 @@ def QLRun(program,samWS,resWS,resnormWS,erange,nbins,Fit,wfile,Loop,Plot,Save): fitWS = fname+'_Workspaces' fout = fname+'_Workspace_'+ str(m) - CreateWorkspace(OutputWorkspace=fout, DataX=datX, DataY=datY, DataE=datE, + CreateWorkspace(OutputWorkspace=fout, DataX=datX, DataY=datY, DataE=datE,\ Nspec=nsp, UnitX='DeltaE', VerticalAxisUnit='Text', VerticalAxisValues=names) # append workspace to list of results @@ -334,7 +335,7 @@ def QLRun(program,samWS,resWS,resnormWS,erange,nbins,Fit,wfile,Loop,Plot,Save): yProb = yPr0 yProb = np.append(yProb,yPr1) yProb = np.append(yProb,yPr2) - CreateWorkspace(OutputWorkspace=probWS, DataX=xProb, DataY=yProb, DataE=eProb, + CreateWorkspace(OutputWorkspace=probWS, DataX=xProb, DataY=yProb, DataE=eProb,\ Nspec=3, UnitX='MomentumTransfer') outWS = C2Fw(samWS[:-4],fname) if (Plot != 'None'): @@ -524,7 +525,7 @@ def C2Fw(prog,sname): y = np.asarray(y).flatten() e = np.asarray(e).flatten() - CreateWorkspace(OutputWorkspace=output_workspace, DataX=x, DataY=y, DataE=e, Nspec=num_spectra, + CreateWorkspace(OutputWorkspace=output_workspace, DataX=x, DataY=y, DataE=e, Nspec=num_spectra,\ UnitX='MomentumTransfer', YUnitLabel='', VerticalAxisUnit='Text', VerticalAxisValues=axis_names) return output_workspace @@ -613,7 +614,7 @@ def C2Se(sname): Vaxis.append('f1.Beta') logger.information('Vaxis=' + str(Vaxis)) - CreateWorkspace(OutputWorkspace=outWS, DataX=dataX, DataY=dataY, DataE=dataE, Nspec=nhist, + CreateWorkspace(OutputWorkspace=outWS, DataX=dataX, DataY=dataY, DataE=dataE, Nspec=nhist,\ UnitX='MomentumTransfer', VerticalAxisUnit='Text', VerticalAxisValues=Vaxis, YUnitLabel='') return outWS @@ -735,7 +736,7 @@ def QuestRun(samWS,resWS,nbs,erange,nbins,Fit,Loop,Plot,Save): Nb,Xb,Yb,Eb = GetXYE(resWS,0,array_len) numb = [nsam, nsp, ntc, Ndat, nbin, Imin, Imax, Nb, nrbin, Nbet, Nsig] reals = [efix, theta[m], rscl, bnorm] - xsout,ysout,xbout,ybout,zpout=Que.quest(numb,Xv,Yv,Ev,reals,fitOp, + xsout,ysout,xbout,ybout,zpout=Que.quest(numb,Xv,Yv,Ev,reals,fitOp,\ Xdat,Xb,Yb,wrks,wrkr,lwrk) dataXs = xsout[:Nsig] # reduce from fixed Fortran array dataYs = ysout[:Nsig] @@ -758,7 +759,7 @@ def QuestRun(samWS,resWS,nbs,erange,nbins,Fit,Loop,Plot,Save): dataYz = np.append(dataYz,dataYzp[:Nbet]) dataEz = np.append(dataEz,eBet0) - CreateWorkspace(OutputWorkspace=zpWS, DataX=dataXz, DataY=dataYz, DataE=dataEz, + CreateWorkspace(OutputWorkspace=zpWS, DataX=dataXz, DataY=dataYz, DataE=dataEz,\ Nspec=Nsig, UnitX='MomentumTransfer', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=dataXs) unitx = mtd[zpWS].getAxis(0).setUnit("Label") @@ -784,12 +785,12 @@ def QuestRun(samWS,resWS,nbs,erange,nbins,Fit,Loop,Plot,Save): groupZ = groupZ +','+ zpWS #create workspaces for sigma and beta - CreateWorkspace(OutputWorkspace=fname+'_Sigma', DataX=xSig, DataY=ySig, DataE=eSig, + CreateWorkspace(OutputWorkspace=fname+'_Sigma', DataX=xSig, DataY=ySig, DataE=eSig,\ Nspec=nsam, UnitX='', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=Qaxis) unitx = mtd[fname+'_Sigma'].getAxis(0).setUnit("Label") unitx.setLabel('sigma' , '') - CreateWorkspace(OutputWorkspace=fname+'_Beta', DataX=xBet, DataY=yBet, DataE=eBet, + CreateWorkspace(OutputWorkspace=fname+'_Beta', DataX=xBet, DataY=yBet, DataE=eBet,\ Nspec=nsam, UnitX='', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=Qaxis) unitx = mtd[fname+'_Beta'].getAxis(0).setUnit("Label") unitx.setLabel('beta' , '') @@ -879,7 +880,7 @@ def ResNormRun(vname,rname,erange,nbin,Plot='None',Save=False): nsp = m+1 numb = [nvan, nsp, ntc, Ndat, nbin, Imin, Imax, Nb] reals = [efix, theta[0], rscl, bnorm] - nd,xout,yout,eout,yfit,pfit=resnorm.resnorm(numb,Xv,Yv,Ev,reals, + nd,xout,yout,eout,yfit,pfit=resnorm.resnorm(numb,Xv,Yv,Ev,reals,\ Xdat,Xb,Yb,wrks,wrkr,lwrk) message = ' Fit paras : '+str(pfit[0])+' '+str(pfit[1]) logger.information(message) @@ -888,26 +889,26 @@ def ResNormRun(vname,rname,erange,nbin,Plot='None',Save=False): if m == 0: yPar1 = np.array([pfit[0]]) yPar2 = np.array([pfit[1]]) - CreateWorkspace(OutputWorkspace='Data', DataX=dataX, DataY=yout[:nd], DataE=eout[:nd], + CreateWorkspace(OutputWorkspace='Data', DataX=dataX, DataY=yout[:nd], DataE=eout[:nd],\ NSpec=1, UnitX='DeltaE') - CreateWorkspace(OutputWorkspace='Fit', DataX=dataX, DataY=yfit[:nd], DataE=np.zeros(nd), + CreateWorkspace(OutputWorkspace='Fit', DataX=dataX, DataY=yfit[:nd], DataE=np.zeros(nd),\ NSpec=1, UnitX='DeltaE') else: yPar1 = np.append(yPar1,pfit[0]) yPar2 = np.append(yPar2,pfit[1]) - CreateWorkspace(OutputWorkspace='__datmp', DataX=dataX, DataY=yout[:nd], DataE=eout[:nd], + CreateWorkspace(OutputWorkspace='__datmp', DataX=dataX, DataY=yout[:nd], DataE=eout[:nd],\ NSpec=1, UnitX='DeltaE') ConjoinWorkspaces(InputWorkspace1='Data', InputWorkspace2='__datmp', CheckOverlapping=False) - CreateWorkspace(OutputWorkspace='__f1tmp', DataX=dataX, DataY=yfit[:nd], DataE=np.zeros(nd), + CreateWorkspace(OutputWorkspace='__f1tmp', DataX=dataX, DataY=yfit[:nd], DataE=np.zeros(nd),\ NSpec=1, UnitX='DeltaE') ConjoinWorkspaces(InputWorkspace1='Fit', InputWorkspace2='__f1tmp', CheckOverlapping=False) resnorm_intesity = fname+'_ResNorm_Intensity' resnorm_stretch = fname+'_ResNorm_Stretch' - CreateWorkspace(OutputWorkspace=resnorm_intesity, DataX=xPar, DataY=yPar1, DataE=xPar, + CreateWorkspace(OutputWorkspace=resnorm_intesity, DataX=xPar, DataY=yPar1, DataE=xPar,\ NSpec=1, UnitX='MomentumTransfer') - CreateWorkspace(OutputWorkspace=resnorm_stretch, DataX=xPar, DataY=yPar2, DataE=xPar, + CreateWorkspace(OutputWorkspace=resnorm_stretch, DataX=xPar, DataY=yPar2, DataE=xPar,\ NSpec=1, UnitX='MomentumTransfer') group = resnorm_intesity + ','+ resnorm_stretch diff --git a/Code/Mantid/scripts/Inelastic/IndirectCommon.py b/Code/Mantid/scripts/Inelastic/IndirectCommon.py index fc7993f9e4b3..4388c5992cc3 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectCommon.py +++ b/Code/Mantid/scripts/Inelastic/IndirectCommon.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from mantid.simpleapi import * from mantid.api import TextAxis from mantid import config, logger diff --git a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py index 35fab8fc8043..48b5271f2fea 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py +++ b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from IndirectImport import import_mantidplot mp = import_mantidplot() from IndirectCommon import * @@ -183,7 +184,7 @@ def furyfitSeq(inputWS, func, ftype, startx, endx, spec_min=0, spec_max=None, in input_str = [tmp_fit_workspace + ',i%d' % i for i in range(spec_min, spec_max + 1)] input_str = ';'.join(input_str) - PlotPeakByLogValue(Input=input_str, OutputWorkspace=output_workspace, Function=func, + PlotPeakByLogValue(Input=input_str, OutputWorkspace=output_workspace, Function=func,\ StartX=startx, EndX=endx, FitType='Sequential', CreateOutput=True) #remove unsused workspaces @@ -210,7 +211,7 @@ def furyfitSeq(inputWS, func, ftype, startx, endx, spec_min=0, spec_max=None, in output_ws = output_workspace + '_%d_Workspace' % i RenameWorkspace(ws, OutputWorkspace=output_ws) - sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': fit_type, + sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': fit_type,\ 'intensities_constrained': intensities_constrained, 'beta_constrained': False} CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) @@ -243,10 +244,10 @@ def furyfitMult(inputWS, function, ftype, startx, endx, spec_min=0, spec_max=Non #prepare input workspace for fitting tmp_fit_workspace = "__furyfit_fit_ws" if spec_max is None: - CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx, + CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx,\ StartWorkspaceIndex=spec_min) else: - CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx, + CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx,\ StartWorkspaceIndex=spec_min, EndWorkspaceIndex=spec_max) ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) @@ -254,7 +255,7 @@ def furyfitMult(inputWS, function, ftype, startx, endx, spec_min=0, spec_max=Non #fit multi-domian functino to workspace multi_domain_func, kwargs = createFuryMultiDomainFunction(function, tmp_fit_workspace) - Fit(Function=multi_domain_func, InputWorkspace=tmp_fit_workspace, WorkspaceIndex=0, + Fit(Function=multi_domain_func, InputWorkspace=tmp_fit_workspace, WorkspaceIndex=0,\ Output=output_workspace, CreateOutput=True, **kwargs) params_table = output_workspace + '_Parameters' @@ -278,7 +279,7 @@ def furyfitMult(inputWS, function, ftype, startx, endx, spec_min=0, spec_max=Non result_workspace = output_workspace + '_Result' fit_group = output_workspace + '_Workspaces' - sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': ftype, + sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': ftype,\ 'intensities_constrained': intensities_constrained, 'beta_constrained': True} CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) @@ -557,7 +558,7 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): subractCanWorkspace(CorrectedSampleWS, CorrectedCanWS, CorrectedSampleWS, rebin_can=rebin_can) Assc = CubicFit(corrections[1], i) - PolynomialCorrection(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedSampleWS, + PolynomialCorrection(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedSampleWS,\ Coefficients=Assc, Operation='Divide') if i == 0: CloneWorkspace(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedWS) @@ -604,7 +605,7 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): return CorrectedWS -def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, ScaleOrNotToScale=False, factor=1, Save=False, +def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, ScaleOrNotToScale=False, factor=1, Save=False,\ PlotResult='None', PlotContrib=False): ''' Load up the necessary files and then passes them into the main @@ -676,7 +677,7 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S subractCanWorkspace(sample, scaled_container, sub_result, rebin_can=RebinCan) if not diffraction_run: - ConvertSpectrumAxis(InputWorkspace=sub_result, OutputWorkspace=sub_result+'_rqw', + ConvertSpectrumAxis(InputWorkspace=sub_result, OutputWorkspace=sub_result+'_rqw',\ Target='ElasticQ', EMode='Indirect', EFixed=efixed) red_ws_name = sub_result + '_red' diff --git a/Code/Mantid/scripts/Inelastic/IndirectDiffractionReduction.py b/Code/Mantid/scripts/Inelastic/IndirectDiffractionReduction.py index f41533106ec1..bf7fe6d626d9 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectDiffractionReduction.py +++ b/Code/Mantid/scripts/Inelastic/IndirectDiffractionReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import mantid from msg_reducer import MSGReducer import inelastic_indirect_reduction_steps as steps diff --git a/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py b/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py index c295b1c277de..0bef58b4a212 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py +++ b/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from mantid.simpleapi import * from IndirectCommon import * from IndirectImport import import_mantidplot @@ -6,7 +7,7 @@ import inelastic_indirect_reducer import sys, os.path, numpy as np -def loadData(rawfiles, outWS='RawFile', Sum=False, SpecMin=-1, SpecMax=-1, +def loadData(rawfiles, outWS='RawFile', Sum=False, SpecMin=-1, SpecMax=-1,\ Suffix=''): workspaces = [] for file in rawfiles: @@ -16,7 +17,7 @@ def loadData(rawfiles, outWS='RawFile', Sum=False, SpecMin=-1, SpecMax=-1, if ( SpecMin == -1 ) and ( SpecMax == -1 ): Load(Filename=file, OutputWorkspace=name+Suffix, LoadLogFiles=False) else: - Load(Filename=file, OutputWorkspace=name+Suffix, SpectrumMin=SpecMin, + Load(Filename=file, OutputWorkspace=name+Suffix, SpectrumMin=SpecMin,\ SpectrumMax=SpecMax, LoadLogFiles=False) workspaces.append(name+Suffix) except ValueError, message: diff --git a/Code/Mantid/scripts/Inelastic/IndirectMuscat.py b/Code/Mantid/scripts/Inelastic/IndirectMuscat.py index 379505207530..8dfbabd426c1 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectMuscat.py +++ b/Code/Mantid/scripts/Inelastic/IndirectMuscat.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # MUSIC : Version of Minus for MIDAS from IndirectImport import * @@ -53,7 +54,7 @@ def CalcSqw(q0,nw2,nel,dw,w0): Qaxis += str(q0[i]) else: Qaxis += ','+str(q0[i]) - CreateWorkspace(OutputWorkspace='S(Q,w)', DataX=xSqw, DataY=ySqw, DataE=eSqw, + CreateWorkspace(OutputWorkspace='S(Q,w)', DataX=xSqw, DataY=ySqw, DataE=eSqw,\ Nspec=nq, UnitX='DeltaE', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=Qaxis) def CheckCoeff(disp,coeff): @@ -103,7 +104,7 @@ def CreateSqw(disp,coeff,grid,Verbose): logger.notice('Coefficients : '+str(coeff)) nq,dq,nw,dw = CheckQw(grid) q0,w0,e0 = CalcW0(nq,dq,disp,coeff) - CreateWorkspace(OutputWorkspace=disp, DataX=q0, DataY=w0, DataE=e0, + CreateWorkspace(OutputWorkspace=disp, DataX=q0, DataY=w0, DataE=e0,\ Nspec=1, UnitX='MomentumTransfer') nw2 = 2*nw+1 nel= nw+1 @@ -139,7 +140,7 @@ def ReadSqw(sqw,Verbose): sys.exit(error) if Verbose: logger.notice('Q : '+str(nq)+' points from '+str(Q[0])+' to '+str(Q[nq-1])+' at '+str(dq)) - logger.notice('w : '+str(nw)+' points from '+str(Xw[0])+' to '+str(Xw[nw])+' at '+str(dw) + logger.notice('w : '+str(nw)+' points from '+str(Xw[0])+' to '+str(Xw[nw])+' at '+str(dw)\ +' ; Elastic energy at : '+str(nel)) X0 = [] X0 = PadArray(X0,1000) # zeroes @@ -241,7 +242,7 @@ def MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): # 1 ijeom,rgeom,sam,ims,dqw,Q_in,S_in, # 2 totals,iw,energy,scat1,scatm,RR,S_out) idet = m+1 - kill,totals,iw,energy,scat1,scatm,RR,Sqw=muscat.muscat_data(idet,lpt,llpt,sqw,lsqw,rinstr,nran, + kill,totals,iw,energy,scat1,scatm,RR,Sqw=muscat.muscat_data(idet,lpt,llpt,sqw,lsqw,rinstr,nran,\ ijeom,rgeom,sam,ims,dqw,Q_in,Sqw_in) if (kill != 0): error = 'Muscat error code : '+str(kill) @@ -310,16 +311,16 @@ def MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): logger.notice('yTot : ' + str(len(yTot))) logger.notice('eTot : ' + str(len(eTot))) msname = sname+'_MS' - CreateWorkspace(OutputWorkspace=msname+'_Totals', DataX=xTot, DataY=yTot, DataE=eTot, + CreateWorkspace(OutputWorkspace=msname+'_Totals', DataX=xTot, DataY=yTot, DataE=eTot,\ Nspec=nt, UnitX='MomentumTransfer') # Nspec=nt, UnitX='MomentumTransfer', VerticalAxisUnit='Text', VerticalAxisValues='Taxis') # start output of MultScat eMs = np.zeros(iw*mang) - CreateWorkspace(OutputWorkspace=msname+'_1', DataX=xMs, DataY=yMsc1, DataE=eMs, + CreateWorkspace(OutputWorkspace=msname+'_1', DataX=xMs, DataY=yMsc1, DataE=eMs,\ Nspec=mang, UnitX='DeltaE', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=Qaxis) - CreateWorkspace(OutputWorkspace=msname+'_M', DataX=xMs, DataY=yMscM, DataE=eMs, + CreateWorkspace(OutputWorkspace=msname+'_M', DataX=xMs, DataY=yMscM, DataE=eMs,\ Nspec=mang, UnitX='DeltaE', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=Qaxis) - CreateWorkspace(OutputWorkspace=msname+'_R', DataX=xMs, DataY=yMr, DataE=eMs, + CreateWorkspace(OutputWorkspace=msname+'_R', DataX=xMs, DataY=yMr, DataE=eMs,\ Nspec=mang, UnitX='DeltaE', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=Qaxis) group = msname+'_1,'+ msname+'_M,'+ msname+'_R' GroupWorkspaces(InputWorkspaces=group,OutputWorkspace=msname+'_Scat') diff --git a/Code/Mantid/scripts/Inelastic/IndirectNeutron.py b/Code/Mantid/scripts/Inelastic/IndirectNeutron.py index ca8becb04006..a217d099b527 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectNeutron.py +++ b/Code/Mantid/scripts/Inelastic/IndirectNeutron.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name #Force for ILL backscattering raw # from IndirectImport import * @@ -212,7 +213,7 @@ def IbackStart(instr,run,ana,refl,rejectZ,useM,mapPath,Plot,Save): #Ascii s eOut.append(em[mm]/10.0) xMon.append(2*xMon[new-1]-xMon[new-2]) monWS = '__Mon' - CreateWorkspace(OutputWorkspace=monWS, DataX=xMon, DataY=yOut, DataE=eOut, + CreateWorkspace(OutputWorkspace=monWS, DataX=xMon, DataY=yOut, DataE=eOut,\ Nspec=1, UnitX='DeltaE') # Qaxis = '' @@ -223,7 +224,7 @@ def IbackStart(instr,run,ana,refl,rejectZ,useM,mapPath,Plot,Save): #Ascii s for n in range(0, nsp): next,xd,yd,ed = ReadIbackGroup(asc,next) tot.append(sum(yd)) - logger.information('Spectrum ' + str(n+1) +' at angle '+ str(theta[n])+ + logger.information('Spectrum ' + str(n+1) +' at angle '+ str(theta[n])+\ ' ; Total counts = '+str(sum(yd))) for m in range(0, new+1): mm = m+imin @@ -236,9 +237,9 @@ def IbackStart(instr,run,ana,refl,rejectZ,useM,mapPath,Plot,Save): #Ascii s Qaxis += str(theta[n]) ascWS = fname +'_' +ana+refl +'_asc' outWS = fname +'_' +ana+refl +'_red' - CreateWorkspace(OutputWorkspace=ascWS, DataX=xDat, DataY=yDat, DataE=eDat, + CreateWorkspace(OutputWorkspace=ascWS, DataX=xDat, DataY=yDat, DataE=eDat,\ Nspec=nsp, UnitX='DeltaE') - Divide(LHSWorkspace=ascWS, RHSWorkspace=monWS, OutputWorkspace=ascWS, + Divide(LHSWorkspace=ascWS, RHSWorkspace=monWS, OutputWorkspace=ascWS,\ AllowDifferentNumberSpectra=True) DeleteWorkspace(monWS) # delete monitor WS InstrParas(ascWS,instr,ana,refl) @@ -324,7 +325,7 @@ def InxStart(instr,run,ana,refl,rejectZ,useM,mapPath,Plot,Save): ns += 1 ascWS = fname +'_' +ana+refl +'_inx' outWS = fname +'_' +ana+refl +'_red' - CreateWorkspace(OutputWorkspace=ascWS, DataX=xDat, DataY=yDat, DataE=eDat, + CreateWorkspace(OutputWorkspace=ascWS, DataX=xDat, DataY=yDat, DataE=eDat,\ Nspec=ns, UnitX='DeltaE') InstrParas(ascWS,instr,ana,refl) efixed = RunParas(ascWS,instr,0,title) @@ -359,7 +360,7 @@ def RejectZero(inWS,tot): outWS = inWS[:-3]+'red' for n in range(0, nin): if tot[n] > 0: - ExtractSingleSpectrum(InputWorkspace=inWS, OutputWorkspace='__tmp', + ExtractSingleSpectrum(InputWorkspace=inWS, OutputWorkspace='__tmp',\ WorkspaceIndex=n) if nout == 0: RenameWorkspace(InputWorkspace='__tmp', OutputWorkspace=outWS) @@ -394,7 +395,7 @@ def UseMap(inWS,map): outWS = inWS[:-3]+'red' for n in range(0, nin): if map[n] == 1: - ExtractSingleSpectrum(InputWorkspace=inWS, OutputWorkspace='__tmp', + ExtractSingleSpectrum(InputWorkspace=inWS, OutputWorkspace='__tmp',\ WorkspaceIndex=n) if nout == 0: RenameWorkspace(InputWorkspace='__tmp', OutputWorkspace=outWS) @@ -429,7 +430,7 @@ def ChangeAngles(inWS,instr,theta): handle.write(str(n+1) +' '+ str(theta[n]) +"\n" ) logger.information('Spectrum ' +str(n+1)+ ' = '+str(theta[n])) handle.close() - UpdateInstrumentFromFile(Workspace=inWS, Filename=path, MoveMonitors=False, IgnorePhi=False, + UpdateInstrumentFromFile(Workspace=inWS, Filename=path, MoveMonitors=False, IgnorePhi=False,\ AsciiHeader=head) def InstrParas(ws,instr,ana,refl): @@ -500,9 +501,9 @@ def IN13Read(instr,run,ana,refl,Plot,Save): #Ascii start routine logger.information('No. sub-spectra : ' + str(nsubsp)) logger.information('No. spectra : ' + str(nspec)) - logger.information('Scan type : ' + str(int(Fval[8]))+ + logger.information('Scan type : ' + str(int(Fval[8]))+\ ' ; Average energy : ' + str(Fval[9])) - logger.information('CaF2 lattice : ' + str(Fval[81])+ + logger.information('CaF2 lattice : ' + str(Fval[81])+\ ' ; Graphite lattice : ' + str(Fval[82])) logger.information('Wavelength : ' + str(wave)) logger.information('No. temperatures : ' + str(ntemp)) @@ -584,10 +585,10 @@ def IN13Read(instr,run,ana,refl,Plot,Save): #Ascii start routine xDq = np.append(xDq,sorted_Q) yDq = np.append(yDq,y1Dq) eDq = np.append(eDq,e1Dq) - CreateWorkspace(OutputWorkspace=ascWS, DataX=xData, DataY=yData, DataE=eData, + CreateWorkspace(OutputWorkspace=ascWS, DataX=xData, DataY=yData, DataE=eData,\ Nspec=3, UnitX='MomentumTransfer') IN13Paras(ascWS,run,title,wave) - CreateWorkspace(OutputWorkspace=outWS, DataX=xDq, DataY=yDq, DataE=eDq, + CreateWorkspace(OutputWorkspace=outWS, DataX=xDq, DataY=yDq, DataE=eDq,\ Nspec=3, UnitX='MomentumTransfer') IN13Paras(outWS,run,title,wave) if Save: diff --git a/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py b/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py index 761a14e289ee..9ab1b09ee8d6 100644 --- a/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py +++ b/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name,no-init from reduction.reducer import ReductionStep import mantid @@ -116,10 +117,10 @@ def _load_single_file(self, filename, output_ws): # Quick hack for older BASIS files that only have one side #if (mtd[file].getRun()['run_number'] < 16693): # basis_mask = "BASIS_Mask_before_16693.xml" - basis_mask_filename = os.path.join(config.getString('maskFiles.directory') + basis_mask_filename = os.path.join(config.getString('maskFiles.directory')\ , basis_mask) if os.path.isfile(basis_mask_filename): - LoadMask(Instrument="BASIS", OutputWorkspace="__basis_mask", + LoadMask(Instrument="BASIS", OutputWorkspace="__basis_mask",\ InputFile=basis_mask_filename) MaskDetectors(Workspace=output_ws, MaskedWorkspace="__basis_mask") else: @@ -131,8 +132,8 @@ def _load_single_file(self, filename, output_ws): self._monitor_index = self._reducer._get_monitor_index(mtd[output_ws]) if self._require_chop_data(output_ws): - ChopData(InputWorkspace=output_ws,OutputWorkspace= output_ws,Step= 20000.0,NChops= 5, IntegrationRangeLower=5000.0, - IntegrationRangeUpper=10000.0, + ChopData(InputWorkspace=output_ws,OutputWorkspace= output_ws,Step= 20000.0,NChops= 5, IntegrationRangeLower=5000.0,\ + IntegrationRangeUpper=10000.0,\ MonitorWorkspaceIndex=self._monitor_index) self._multiple_frames = True else: @@ -157,8 +158,8 @@ def _load_single_file(self, filename, output_ws): raise ValueError("Range %d - %d is not a valid detector range." % (self._detector_range_start, self._detector_range_end)) ## Crop the workspace to remove uninteresting detectors - CropWorkspace(InputWorkspace=ws,OutputWorkspace= ws, - StartWorkspaceIndex=self._detector_range_start, + CropWorkspace(InputWorkspace=ws,OutputWorkspace= ws,\ + StartWorkspaceIndex=self._detector_range_start,\ EndWorkspaceIndex=self._detector_range_end) def _load_data(self, filename, output_ws): @@ -316,7 +317,7 @@ def execute(self, reducer, file_ws): for ws in workspaces: ConvertToDistribution(Workspace=ws) - CalculateFlatBackground(InputWorkspace=ws,OutputWorkspace= ws,StartX= self._background_start, + CalculateFlatBackground(InputWorkspace=ws,OutputWorkspace= ws,StartX= self._background_start,\ EndX=self._background_end, Mode='Mean') ConvertFromDistribution(Workspace=ws) @@ -431,7 +432,7 @@ def _unwrap_monitor(self, ws): l_ref = self._get_reference_length(ws, 0) monitor = ws+'_mon' unwrapped_ws, join = UnwrapMonitor(InputWorkspace=monitor, OutputWorkspace=monitor, LRef=l_ref) - RemoveBins(InputWorkspace=monitor,OutputWorkspace= monitor,XMin= join-0.001,XMax= join+0.001, + RemoveBins(InputWorkspace=monitor,OutputWorkspace= monitor,XMin= join-0.001,XMax= join+0.001,\ Interpolation='Linear') try: FFTSmooth(InputWorkspace=monitor,OutputWorkspace=monitor,WorkspaceIndex=0) @@ -458,7 +459,7 @@ def _monitor_efficiency(self, monitor): thickness = inst.getNumberParameter(montiorStr+'-Thickness')[0] attenuation= inst.getNumberParameter(montiorStr+'-Attenuation')[0] except IndexError: - raise ValueError('Unable to retrieve monitor thickness, area and ' + raise ValueError('Unable to retrieve monitor thickness, area and '\ 'attenuation from Instrument Parameter file.') else: if ( area == -1 or thickness == -1 or attenuation == -1): @@ -852,10 +853,10 @@ def _group_data(self, workspace): # Run GroupDetectors with a workspace if we have one # Otherwise try to run it with a mapping file if grouping_workspace is not None: - GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, CopyGroupingFromWorkspace=grouping_workspace, + GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, CopyGroupingFromWorkspace=grouping_workspace,\ Behaviour='Average') elif os.path.isfile(grouping_filename): - GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, MapFile=grouping_filename, + GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, MapFile=grouping_filename,\ Behaviour='Average') return workspace @@ -960,7 +961,7 @@ def _get_ws_name(self, workspace): elif type == 'RunTitle': return self._run_title(workspace) else: - raise NotImplementedError('Unknown \'Workflow.NamingConvention\'' + raise NotImplementedError('Unknown \'Workflow.NamingConvention\''\ ' parameter encountered on workspace: ' + workspace) def _run_title(self, workspace): diff --git a/Code/Mantid/scripts/Inelastic/msg_reducer.py b/Code/Mantid/scripts/Inelastic/msg_reducer.py index e240f2929907..235d88a596a2 100644 --- a/Code/Mantid/scripts/Inelastic/msg_reducer.py +++ b/Code/Mantid/scripts/Inelastic/msg_reducer.py @@ -37,7 +37,7 @@ def pre_process(self): loadData.set_ws_list(self._data_files) loadData.set_sum(self._sum) loadData.set_load_logs(self._load_logs) - loadData.set_detector_range(self._detector_range[0], + loadData.set_detector_range(self._detector_range[0],\ self._detector_range[1]) loadData.set_parameter_file(self._parameter_file) loadData.set_extra_load_opts(self._extra_load_opts) @@ -178,7 +178,7 @@ def get_result_workspaces(self): except AttributeError: pass except IndexError: - raise RuntimeError("None of the reduction steps implement " + raise RuntimeError("None of the reduction steps implement "\ "the get_result_workspaces() method.") def _get_monitor_index(self, workspace): diff --git a/Code/Mantid/scripts/Interface/reduction_application.py b/Code/Mantid/scripts/Interface/reduction_application.py index 817cbe20fbc0..a5c5fdfcfd0c 100644 --- a/Code/Mantid/scripts/Interface/reduction_application.py +++ b/Code/Mantid/scripts/Interface/reduction_application.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Main window for reduction UIs """ @@ -16,7 +17,6 @@ import sip sip.setapi('QString',2) sip.setapi('QVariant',2) - pass from PyQt4 import QtGui, QtCore @@ -392,7 +392,7 @@ def closeEvent(self, event): Executed when the application closes """ if False: - reply = QtGui.QMessageBox.question(self, 'Message', + reply = QtGui.QMessageBox.question(self, 'Message',\ "Are you sure you want to quit this application?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: diff --git a/Code/Mantid/scripts/Interface/reduction_gui/instruments/interface.py b/Code/Mantid/scripts/Interface/reduction_gui/instruments/interface.py index 5d4c44518e9e..a71fab7ed1a4 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/instruments/interface.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/instruments/interface.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Base class for instrument-specific user interface """ diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_adv_setup_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_adv_setup_script.py index ab1f5dad562d..0c202970df84 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_adv_setup_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_adv_setup_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could @@ -15,7 +16,7 @@ def getBooleanElement(instrument_dom, keyname, default): (1) True/False (2) 1/0 """ - tempbool = BaseScriptElement.getStringElement(instrument_dom, + tempbool = BaseScriptElement.getStringElement(instrument_dom,\ keyname, default=default) if tempbool == "True": @@ -30,7 +31,7 @@ def getFloatElement(instrument_dom, keyname, default): return the default value. """ try: - return BaseScriptElement.getFloatElement(instrument_dom, + return BaseScriptElement.getFloatElement(instrument_dom,\ keyname, default=default) except ValueError: return default @@ -182,22 +183,22 @@ def from_xml(self, xml_str): AdvancedSetupScript.removepropmppulsewidth) try: - self.maxchunksize = BaseScriptElement.getIntElement(instrument_dom, + self.maxchunksize = BaseScriptElement.getIntElement(instrument_dom,\ "maxchunksize", default=AdvancedSetupScript.maxchunksize) except ValueError: self.maxchunksize = AdvancedSetupScript.maxchunksize - self.filterbadpulses = getFloatElement(instrument_dom, + self.filterbadpulses = getFloatElement(instrument_dom,\ "filterbadpulses", AdvancedSetupScript.filterbadpulses) - self.bkgdsmoothpars = BaseScriptElement.getStringElement(instrument_dom, + self.bkgdsmoothpars = BaseScriptElement.getStringElement(instrument_dom,\ "bkgdsmoothpars", default=AdvancedSetupScript.bkgdsmoothpars) - self.pushdatapositive = BaseScriptElement.getStringElement(instrument_dom, + self.pushdatapositive = BaseScriptElement.getStringElement(instrument_dom,\ "pushdatapositive", default=AdvancedSetupScript.pushdatapositive) - self.stripvanadiumpeaks = getBooleanElement(instrument_dom, + self.stripvanadiumpeaks = getBooleanElement(instrument_dom,\ "stripvanadiumpeaks", AdvancedSetupScript.stripvanadiumpeaks) self.vanadiumfwhm = getFloatElement(instrument_dom, "vanadiumfwhm", @@ -206,16 +207,16 @@ def from_xml(self, xml_str): self.vanadiumpeaktol = getFloatElement(instrument_dom, "vanadiumpeaktol", AdvancedSetupScript.vanadiumpeaktol) - self.vanadiumsmoothparams = BaseScriptElement.getStringElement(instrument_dom, + self.vanadiumsmoothparams = BaseScriptElement.getStringElement(instrument_dom,\ "vanadiumsmoothparams", default=AdvancedSetupScript.vanadiumsmoothparams) - self.extension = BaseScriptElement.getStringElement(instrument_dom, + self.extension = BaseScriptElement.getStringElement(instrument_dom,\ "extension", default=AdvancedSetupScript.extension) self.preserveevents = getBooleanElement(instrument_dom, "preserveevents", default=AdvancedSetupScript.preserveevents) - self.outputfileprefix = BaseScriptElement.getStringElement(instrument_dom, + self.outputfileprefix = BaseScriptElement.getStringElement(instrument_dom,\ "outputfileprefix", default = AdvancedSetupScript.outputfileprefix) self.scaledata = getFloatElement(instrument_dom, "scaledata", diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_filter_setup_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_filter_setup_script.py index b65ebe31f07c..d31ee3d5a9bd 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_filter_setup_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_filter_setup_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could @@ -172,7 +173,7 @@ def from_xml(self, xml_str): self.minimumlogvalue = self.getFloatElement(instrument_dom, "minimumlogvalue", FilterSetupScript.minimumlogvalue) self.maximumlogvalue = self.getFloatElement(instrument_dom, "maximumlogvalue", FilterSetupScript.maximumlogvalue) self.logvalueinterval = self.getFloatElement(instrument_dom, "logvalueinterval", FilterSetupScript.logvalueinterval) - self.filterlogvaluebychangingdirection = self.getStringElement(instrument_dom, "filterlogvaluebychangingdirection", + self.filterlogvaluebychangingdirection = self.getStringElement(instrument_dom, "filterlogvaluebychangingdirection",\ FilterSetupScript.filterlogvaluebychangingdirection) self.timetolerance = self.getFloatElement(instrument_dom, "timetolerance", FilterSetupScript.timetolerance) self.logboundary = self.getStringElement(instrument_dom, "logboundary", FilterSetupScript.logboundary) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py index 6c7ed3e36314..f2dffcfc13e4 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could @@ -160,7 +161,7 @@ def constructPythonScript(self, paramdict): script += "%sMinimumLogValue = '%s',\n" % (DiffractionReductionScripter.WIDTH, filterdict["MinimumLogValue"]) if filterdict["MaximumLogValue"] != "": script += "%sMaximumLogValue = '%s',\n" % (DiffractionReductionScripter.WIDTH, filterdict["MaximumLogValue"]) - script += "%sFilterLogValueByChangingDirection = '%s',\n" % (DiffractionReductionScripter.WIDTH, + script += "%sFilterLogValueByChangingDirection = '%s',\n" % (DiffractionReductionScripter.WIDTH,\ filterdict["FilterLogValueByChangingDirection"]) if filterdict["LogValueInterval"] != "": # Filter by log value interval @@ -353,7 +354,7 @@ def buildPowderDataReductionScript(self, runsetupdict, advsetupdict, runnumber=N if splitwsname is not None and splitwsname != "": script += "%sSplittersWorkspace = '%s',\n" % (DiffractionReductionScripter.WIDTH, str(splitwsname)) if splitinfowsname is not None and splitinfowsname != "": - script += "%sSplitInformationWorkspace='%s',\n" % (DiffractionReductionScripter.WIDTH, + script += "%sSplitInformationWorkspace='%s',\n" % (DiffractionReductionScripter.WIDTH,\ str(splitinfowsname)) script += "%s)\n" % (DiffractionReductionScripter.WIDTH) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_run_setup_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_run_setup_script.py index dfb474340bf0..91c46724fb6c 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_run_setup_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_run_setup_script.py @@ -160,66 +160,66 @@ def from_xml(self, xml_str): instrument_dom = element_list[0] # - self.runnumbers = BaseScriptElement.getStringElement(instrument_dom, + self.runnumbers = BaseScriptElement.getStringElement(instrument_dom,\ "runnumber", default=RunSetupScript.runnumbers) - tempbool = BaseScriptElement.getStringElement(instrument_dom, + tempbool = BaseScriptElement.getStringElement(instrument_dom,\ "sum", default=str(int(RunSetupScript.dosum))) self.dosum = bool(int(tempbool)) - self.calibfilename = BaseScriptElement.getStringElement(instrument_dom, + self.calibfilename = BaseScriptElement.getStringElement(instrument_dom,\ "calibrationfile", default=RunSetupScript.calibfilename) - self.charfilename = BaseScriptElement.getStringElement(instrument_dom, + self.charfilename = BaseScriptElement.getStringElement(instrument_dom,\ "characterizationrunsfile", default=RunSetupScript.charfilename) - self.binning = BaseScriptElement.getFloatElement(instrument_dom, + self.binning = BaseScriptElement.getFloatElement(instrument_dom,\ "binning", default=RunSetupScript.binning) - tempbool = BaseScriptElement.getStringElement(instrument_dom, + tempbool = BaseScriptElement.getStringElement(instrument_dom,\ "binindspace", default=str(int(RunSetupScript.binindspace))) self.binindspace = bool(int(tempbool)) - self.resamplex = BaseScriptElement.getIntElement(instrument_dom, + self.resamplex = BaseScriptElement.getIntElement(instrument_dom,\ "resamplex", default=RunSetupScript.resamplex) - self.saveas = BaseScriptElement.getStringElement(instrument_dom, + self.saveas = BaseScriptElement.getStringElement(instrument_dom,\ "saveas", default=RunSetupScript.saveas) - self.outputdir = BaseScriptElement.getStringElement(instrument_dom, + self.outputdir = BaseScriptElement.getStringElement(instrument_dom,\ "outputdirectory", default=RunSetupScript.outputdir) - self.finalunits = BaseScriptElement.getStringElement(instrument_dom, + self.finalunits = BaseScriptElement.getStringElement(instrument_dom,\ "finaldataunits", default=RunSetupScript.finalunits) - tempint = BaseScriptElement.getStringElement(instrument_dom, + tempint = BaseScriptElement.getStringElement(instrument_dom,\ "backgroundnumber", default=RunSetupScript.bkgdrunnumber) try: self.bkgdrunnumber = int(tempint) except ValueError: self.bkgdrunnumber = None - tempbool = BaseScriptElement.getStringElement(instrument_dom, + tempbool = BaseScriptElement.getStringElement(instrument_dom,\ "disablebackgroundcorrection", default=str(int(RunSetupScript.disablebkgdcorrection))) self.disablebkgdcorrection = bool(int(tempbool)) - tempint = BaseScriptElement.getStringElement(instrument_dom, + tempint = BaseScriptElement.getStringElement(instrument_dom,\ "vanadiumnumber", default=RunSetupScript.vanrunnumber) try: self.vanrunnumber = int(tempint) except ValueError: self.vanrunnumber = "" - tempbool = BaseScriptElement.getStringElement(instrument_dom, + tempbool = BaseScriptElement.getStringElement(instrument_dom,\ "disablevanadiumcorrection", default=str(int(RunSetupScript.disablevancorrection))) self.disablevancorrection = bool(int(tempbool)) - tempint = BaseScriptElement.getStringElement(instrument_dom, + tempint = BaseScriptElement.getStringElement(instrument_dom,\ "vanadiumbackgroundnumber", default=RunSetupScript.vanbkgdrunnumber) try: self.vanbkgdrunnumber = int(tempint) except ValueError: self.vanbkgdrunnumber = None - tempbool = BaseScriptElement.getStringElement(instrument_dom, + tempbool = BaseScriptElement.getStringElement(instrument_dom,\ "disablevanadiumbackgroundcorrection", default=str(int(RunSetupScript.disablevanbkgdcorrection))) self.disablevanbkgdcorrection = bool(int(tempbool)) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/eqsans_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/eqsans_reduction.py index 899c6b35d6ff..6d2552cdf3b0 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/eqsans_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/eqsans_reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ This class holds all the necessary information to create a reduction script. This is a fake version of the Reducer for testing purposes. diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/hfir_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/hfir_reduction.py index f787756416c7..9b6c63891afb 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/hfir_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/hfir_reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ This class holds all the necessary information to create a reduction script. This is a fake version of the Reducer for testing purposes. diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_absolute_units_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_absolute_units_script.py index 2ecd16e8c1ad..9e89b2a27269 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_absolute_units_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_absolute_units_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_data_corrections_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_data_corrections_script.py index d9772dcbfb68..63bae3d9f3e0 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_data_corrections_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_data_corrections_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could @@ -121,20 +122,20 @@ def from_xml(self, xml_str): self.incident_beam_norm = BaseScriptElement.getStringElement(instrument_dom, "incident_beam_norm", default=DataCorrectionsScript.incident_beam_norm) - self.monitor_int_low = BaseScriptElement.getIntElement(instrument_dom, - "monint_range_low", + self.monitor_int_low = BaseScriptElement.getIntElement(instrument_dom,\ + "monint_range_low",\ default=DataCorrectionsScript.monitor_int_low) - self.monitor_int_high = BaseScriptElement.getIntElement(instrument_dom, - "monint_range_high", + self.monitor_int_high = BaseScriptElement.getIntElement(instrument_dom,\ + "monint_range_high",\ default=DataCorrectionsScript.monitor_int_high) self.tib_subtraction = BaseScriptElement.getBoolElement(instrument_dom, "timeindepbkg_sub", default=DataCorrectionsScript.tib_subtraction) - self.tib_tof_start = BaseScriptElement.getIntElement(instrument_dom, - "tib_tof_range_start", + self.tib_tof_start = BaseScriptElement.getIntElement(instrument_dom,\ + "tib_tof_range_start",\ default=DataCorrectionsScript.tib_tof_start) - self.tib_tof_end = BaseScriptElement.getIntElement(instrument_dom, - "tib_tof_range_end", + self.tib_tof_end = BaseScriptElement.getIntElement(instrument_dom,\ + "tib_tof_range_end",\ default=DataCorrectionsScript.tib_tof_end) self.correct_kikf = BaseScriptElement.getBoolElement(instrument_dom, "correct_kikf", @@ -142,26 +143,26 @@ def from_xml(self, xml_str): self.detector_vanadium = BaseScriptElement.getStringElement(instrument_dom, "detector_vanadium", default=DataCorrectionsScript.detector_vanadium) - self.detvan_integration = BaseScriptElement.getBoolElement(instrument_dom, - "use_bounds_detvan", + self.detvan_integration = BaseScriptElement.getBoolElement(instrument_dom,\ + "use_bounds_detvan",\ default=DataCorrectionsScript.detvan_integration) - self.detvan_int_range_low = BaseScriptElement.getStringElement(instrument_dom, - "detvan_range_low", + self.detvan_int_range_low = BaseScriptElement.getStringElement(instrument_dom,\ + "detvan_range_low",\ default=DataCorrectionsScript.detvan_int_range_low) - self.detvan_int_range_high = BaseScriptElement.getStringElement(instrument_dom, - "detvan_range_high", + self.detvan_int_range_high = BaseScriptElement.getStringElement(instrument_dom,\ + "detvan_range_high",\ default=DataCorrectionsScript.detvan_int_range_high) - self.detvan_int_range_units = BaseScriptElement.getStringElement(instrument_dom, - "detvan_range_units", + self.detvan_int_range_units = BaseScriptElement.getStringElement(instrument_dom,\ + "detvan_range_units",\ default=DataCorrectionsScript.detvan_int_range_units) - self.save_proc_detvan = BaseScriptElement.getBoolElement(instrument_dom, - "save_proc_detvan", + self.save_proc_detvan = BaseScriptElement.getBoolElement(instrument_dom,\ + "save_proc_detvan",\ default=DataCorrectionsScript.save_proc_detvan) - self.save_proc_detvan_file = BaseScriptElement.getStringElement(instrument_dom, - "save_proc_detvan_filename", + self.save_proc_detvan_file = BaseScriptElement.getStringElement(instrument_dom,\ + "save_proc_detvan_filename",\ default=DataCorrectionsScript.save_proc_detvan_file) - self.use_proc_detvan = BaseScriptElement.getBoolElement(instrument_dom, - "use_proc_detvan", + self.use_proc_detvan = BaseScriptElement.getBoolElement(instrument_dom,\ + "use_proc_detvan",\ default=DataCorrectionsScript.use_proc_detvan) def reset(self): diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_diagnose_detectors_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_diagnose_detectors_script.py index 6960fca539c5..05cf070afb81 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_diagnose_detectors_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_diagnose_detectors_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could @@ -175,8 +176,8 @@ def from_xml(self, xml_str): self.sambkg_errorbar_criterion = BaseScriptElement.getFloatElement(instrument_dom, "sambkg_errorbar_criterion", default=DiagnoseDetectorsScript.sambkg_errorbar_criterion) - self.tof_start = BaseScriptElement.getIntElement(instrument_dom, - "background_tof_start", + self.tof_start = BaseScriptElement.getIntElement(instrument_dom,\ + "background_tof_start",\ default=DiagnoseDetectorsScript.tof_start) self.tof_end = BaseScriptElement.getIntElement(instrument_dom, "background_tof_end", diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py index cc1ff2e316dd..4f358fd8caad 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_sample_data_setup_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_sample_data_setup_script.py index 4218d65ea0ae..2390fc5ccbf5 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_sample_data_setup_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_sample_data_setup_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could @@ -128,8 +129,8 @@ def from_xml(self, xml_str): self.sample_file = BaseScriptElement.getStringElement(instrument_dom, "sample_input_file", default=SampleSetupScript.sample_file) - self.live_button = BaseScriptElement.getBoolElement(instrument_dom, - "live_button", + self.live_button = BaseScriptElement.getBoolElement(instrument_dom,\ + "live_button",\ default=SampleSetupScript.live_button) self.output_wsname = BaseScriptElement.getStringElement(instrument_dom, "output_wsname", @@ -176,8 +177,8 @@ def from_xml(self, xml_str): self.show_workspaces = BaseScriptElement.getBoolElement(instrument_dom, "show_workspaces", default=SampleSetupScript.show_workspaces) - self.savedir = BaseScriptElement.getStringElement(instrument_dom, - "savedir", + self.savedir = BaseScriptElement.getStringElement(instrument_dom,\ + "savedir",\ default=SampleSetupScript.savedir) def reset(self): diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/output_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/output_script.py index d5dc1c054f53..761bb0d46dd4 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/output_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/output_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from scripter import BaseScriptElement # Check whether we are running in MantidPlot diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_reduction.py index 7980023fbb2d..c35820136313 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ This class holds all the necessary information to create a reduction script. """ diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py index fa68ff9c5923..80b78fe6cff0 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ This class holds all the necessary information to create a reduction script. This is a fake version of the Reducer for testing purposes. diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/data_cat.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/data_cat.py index efe57b2e28cb..5647e64be5f2 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/data_cat.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/data_cat.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Simple local data catalog for Mantid Gets main information from data files in a directory and stores diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py index 69bf588ea991..8330391948dc 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Data catalog for EQSANS """ diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_options_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_options_script.py index 77425493d07e..edaac8e15d58 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_options_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_options_script.py @@ -216,7 +216,7 @@ def from_xml(self, xml_str): # Resolution self.compute_resolution = BaseScriptElement.getBoolElement(dom, "ComputeResolution", default = ReductionOptions.compute_resolution) - self.sample_aperture_diameter = BaseScriptElement.getFloatElement(dom, "SampleApertureDiameter", + self.sample_aperture_diameter = BaseScriptElement.getFloatElement(dom, "SampleApertureDiameter",\ default = ReductionOptions.sample_aperture_diameter) # TOF correction diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_background_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_background_script.py index ef059d34bc04..545af6a13e5e 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_background_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_background_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the HFIRReduction class could @@ -203,20 +204,20 @@ def from_xml(self, xml_str): default = Background.dark_current_corr) self.dark_current_file = BaseScriptElement.getStringElement(instrument_dom, "dark_current_file") - self.background_corr = BaseScriptElement.getBoolElement(instrument_dom, "background_corr", + self.background_corr = BaseScriptElement.getBoolElement(instrument_dom, "background_corr",\ default = Background.background_corr) self.background_file = BaseScriptElement.getStringElement(instrument_dom, "background_file") - self.bck_transmission_enabled = BaseScriptElement.getBoolElement(instrument_dom, "bck_trans_enabled", + self.bck_transmission_enabled = BaseScriptElement.getBoolElement(instrument_dom, "bck_trans_enabled",\ default = Background.bck_transmission_enabled) - self.bck_transmission = BaseScriptElement.getFloatElement(instrument_dom, "bck_trans", + self.bck_transmission = BaseScriptElement.getFloatElement(instrument_dom, "bck_trans",\ default=Background.bck_transmission) - self.bck_transmission_spread = BaseScriptElement.getFloatElement(instrument_dom, "bck_trans_spread", + self.bck_transmission_spread = BaseScriptElement.getFloatElement(instrument_dom, "bck_trans_spread",\ default=Background.bck_transmission_spread) self.calculate_transmission = BaseScriptElement.getBoolElement(instrument_dom, "calculate_trans", default = Background.calculate_transmission) - self.theta_dependent = BaseScriptElement.getBoolElement(instrument_dom, "theta_dependent", + self.theta_dependent = BaseScriptElement.getBoolElement(instrument_dom, "theta_dependent",\ default = Background.theta_dependent) self.trans_dark_current = BaseScriptElement.getStringElement(instrument_dom, "trans_dark_current") diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_catalog.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_catalog.py index dbb7fd0a4d7e..c768f92cad3a 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_catalog.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_catalog.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Data catalog for HFIR SANS """ diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_data_proxy.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_data_proxy.py index 799a7d325159..4ad3e41978bd 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_data_proxy.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_data_proxy.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import sys # Check whether Mantid is available try: diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_detector_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_detector_script.py index 286e077301f3..6f0c65f526d0 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_detector_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_detector_script.py @@ -181,28 +181,28 @@ def from_xml(self, xml_str): default = Detector.sensitivity_corr) self.sensitivity_data = BaseScriptElement.getStringElement(instrument_dom, "sensitivity_data") self.sensitivity_dark = BaseScriptElement.getStringElement(instrument_dom, "sensitivity_dark") - self.use_sample_dark = BaseScriptElement.getBoolElement(instrument_dom, "use_sample_dark", + self.use_sample_dark = BaseScriptElement.getBoolElement(instrument_dom, "use_sample_dark",\ default = Detector.use_sample_dark) - self.min_sensitivity = BaseScriptElement.getFloatElement(instrument_dom, "sensitivity_min", + self.min_sensitivity = BaseScriptElement.getFloatElement(instrument_dom, "sensitivity_min",\ default=Detector.min_sensitivity) - self.max_sensitivity = BaseScriptElement.getFloatElement(instrument_dom, "sensitivity_max", + self.max_sensitivity = BaseScriptElement.getFloatElement(instrument_dom, "sensitivity_max",\ default=Detector.max_sensitivity) - self.use_sample_beam_center = BaseScriptElement.getBoolElement(instrument_dom, "use_sample_beam_center", + self.use_sample_beam_center = BaseScriptElement.getBoolElement(instrument_dom, "use_sample_beam_center",\ default = Detector.use_sample_beam_center) beam_center_list = instrument_dom.getElementsByTagName("FloodBeamFinder") if len(beam_center_list)>0: beam_finder_dom = beam_center_list[0] - self.flood_x_position = BaseScriptElement.getFloatElement(beam_finder_dom, "x", + self.flood_x_position = BaseScriptElement.getFloatElement(beam_finder_dom, "x",\ default=Detector.flood_x_position) - self.flood_y_position = BaseScriptElement.getFloatElement(beam_finder_dom, "y", + self.flood_y_position = BaseScriptElement.getFloatElement(beam_finder_dom, "y",\ default=Detector.flood_y_position) - self.flood_use_finder = BaseScriptElement.getBoolElement(beam_finder_dom, "use_finder", + self.flood_use_finder = BaseScriptElement.getBoolElement(beam_finder_dom, "use_finder",\ default = Detector.flood_use_finder) self.flood_beam_file = BaseScriptElement.getStringElement(beam_finder_dom, "beam_file") - self.flood_beam_radius = BaseScriptElement.getFloatElement(beam_finder_dom, "beam_radius", + self.flood_beam_radius = BaseScriptElement.getFloatElement(beam_finder_dom, "beam_radius",\ default=Detector.flood_beam_radius) - self.flood_use_direct_beam = BaseScriptElement.getBoolElement(beam_finder_dom, "use_direct_beam", + self.flood_use_direct_beam = BaseScriptElement.getBoolElement(beam_finder_dom, "use_direct_beam",\ default = Detector.flood_use_direct_beam) element_list = dom.getElementsByTagName("BeamFinder") @@ -215,9 +215,9 @@ def from_xml(self, xml_str): self.use_finder = BaseScriptElement.getBoolElement(beam_finder_dom, "use_finder", default = Detector.use_finder) self.beam_file = BaseScriptElement.getStringElement(beam_finder_dom, "beam_file") - self.beam_radius = BaseScriptElement.getFloatElement(beam_finder_dom, "beam_radius", + self.beam_radius = BaseScriptElement.getFloatElement(beam_finder_dom, "beam_radius",\ default=Detector.beam_radius) - self.use_direct_beam = BaseScriptElement.getBoolElement(beam_finder_dom, "use_direct_beam", + self.use_direct_beam = BaseScriptElement.getBoolElement(beam_finder_dom, "use_direct_beam",\ default = Detector.use_direct_beam) def from_setup_info(self, xml_str): @@ -255,19 +255,19 @@ def from_setup_info(self, xml_str): self.flood_y_position = BaseScriptElement.getPropertyValue(alg, "SensitivityBeamCenterY", default=Detector.flood_y_position) self.flood_beam_file = BaseScriptElement.getPropertyValue(alg, "SensitivityBeamCenterFile", default='') - self.flood_beam_radius = BaseScriptElement.getPropertyValue(alg, "SensitivityBeamCenterRadius", + self.flood_beam_radius = BaseScriptElement.getPropertyValue(alg, "SensitivityBeamCenterRadius",\ default=Detector.flood_beam_radius) # Beam center center_method = BaseScriptElement.getPropertyValue(alg, "BeamCenterMethod", default='None') self.use_finder = center_method in ['DirectBeam', 'Scattering'] self.use_direct_beam = center_method=='DirectBeam' - self.x_position = BaseScriptElement.getPropertyValue(alg, "BeamCenterX", + self.x_position = BaseScriptElement.getPropertyValue(alg, "BeamCenterX",\ default=Detector.x_position) - self.y_position = BaseScriptElement.getPropertyValue(alg, "BeamCenterY", + self.y_position = BaseScriptElement.getPropertyValue(alg, "BeamCenterY",\ default=Detector.y_position) self.beam_file = BaseScriptElement.getPropertyValue(alg, "BeamCenterFile", default='') - self.beam_radius = BaseScriptElement.getPropertyValue(alg, "BeamRadius", + self.beam_radius = BaseScriptElement.getPropertyValue(alg, "BeamRadius",\ default=Detector.beam_radius) def reset(self): diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py index 41d57b666ce3..e747eaa22002 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py @@ -261,7 +261,7 @@ def from_xml(self, xml_str): default=ReductionOptions.detector_offset) self.wavelength = BaseScriptElement.getFloatElement(instrument_dom, "wavelength", default=ReductionOptions.wavelength) - self.wavelength_spread = BaseScriptElement.getFloatElement(instrument_dom, "wavelength_spread", + self.wavelength_spread = BaseScriptElement.getFloatElement(instrument_dom, "wavelength_spread",\ default=ReductionOptions.wavelength_spread) self.solid_angle_corr = BaseScriptElement.getBoolElement(instrument_dom, "solid_angle_corr", @@ -278,11 +278,11 @@ def from_xml(self, xml_str): default = ReductionOptions.dark_current_corr) self.dark_current_data = BaseScriptElement.getStringElement(instrument_dom, "dark_current_data") - self.n_q_bins = BaseScriptElement.getIntElement(instrument_dom, "n_q_bins", + self.n_q_bins = BaseScriptElement.getIntElement(instrument_dom, "n_q_bins",\ default=ReductionOptions.n_q_bins) - self.n_sub_pix = BaseScriptElement.getIntElement(instrument_dom, "n_sub_pix", + self.n_sub_pix = BaseScriptElement.getIntElement(instrument_dom, "n_sub_pix",\ default=ReductionOptions.n_sub_pix) - self.log_binning = BaseScriptElement.getBoolElement(instrument_dom, "log_binning", + self.log_binning = BaseScriptElement.getBoolElement(instrument_dom, "log_binning",\ default = ReductionOptions.log_binning) self.align_log_with_decades = BaseScriptElement.getBoolElement(instrument_dom, "align_log_with_decades", default = ReductionOptions.align_log_with_decades) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_sample_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_sample_script.py index 10bce2ea2a88..737f9582d26c 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_sample_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_sample_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the HFIRReduction class could @@ -145,9 +146,9 @@ def from_xml(self, dom): self.sample_spreader = BaseScriptElement.getStringElement(instrument_dom, "sample_spreader") self.direct_scatt = BaseScriptElement.getStringElement(instrument_dom, "direct_scatt") self.direct_spreader = BaseScriptElement.getStringElement(instrument_dom, "direct_spreader") - self.spreader_trans = BaseScriptElement.getFloatElement(instrument_dom, "spreader_trans", + self.spreader_trans = BaseScriptElement.getFloatElement(instrument_dom, "spreader_trans",\ default=SampleData.BeamSpreader.spreader_trans) - self.spreader_trans_spread = BaseScriptElement.getFloatElement(instrument_dom, "spreader_trans_spread", + self.spreader_trans_spread = BaseScriptElement.getFloatElement(instrument_dom, "spreader_trans_spread",\ default=SampleData.BeamSpreader.spreader_trans_spread) def from_setup_info(self, xml_str): @@ -304,11 +305,11 @@ def from_xml(self, xml_str): instrument_dom = element_list[0] self.transmission = BaseScriptElement.getFloatElement(instrument_dom, "trans", default=SampleData.transmission) - self.transmission_spread = BaseScriptElement.getFloatElement(instrument_dom, "trans_spread", + self.transmission_spread = BaseScriptElement.getFloatElement(instrument_dom, "trans_spread",\ default=SampleData.transmission_spread) self.calculate_transmission = BaseScriptElement.getBoolElement(instrument_dom, "calculate_trans", default = SampleData.calculate_transmission) - self.theta_dependent = BaseScriptElement.getBoolElement(instrument_dom, "theta_dependent", + self.theta_dependent = BaseScriptElement.getBoolElement(instrument_dom, "theta_dependent",\ default = SampleData.theta_dependent) self.dark_current = BaseScriptElement.getStringElement(instrument_dom, "dark_current") diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/scripter.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/scripter.py index 9aa957df9d16..daab5c3f4279 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/scripter.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/scripter.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Reduction scripter used to take reduction parameters end produce a Mantid reduction script diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/base_widget.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/base_widget.py index f07c5fc5efe4..3b0f1d46bf4d 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/base_widget.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/base_widget.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import os import types @@ -128,8 +129,8 @@ def data_browse_dialog(self, data_type=None, title=None, multi=False): if title is None: title = "Data file - Choose a data file" if multi: - qflist = QtGui.QFileDialog.getOpenFileNames(self, title, - self._settings.data_path, + qflist = QtGui.QFileDialog.getOpenFileNames(self, title,\ + self._settings.data_path,\ data_type) if len(qflist)>0: flist = [] @@ -141,8 +142,8 @@ def data_browse_dialog(self, data_type=None, title=None, multi=False): else: return None else: - fname = QtCore.QFileInfo(QtGui.QFileDialog.getOpenFileName(self, title, - self._settings.data_path, + fname = QtCore.QFileInfo(QtGui.QFileDialog.getOpenFileName(self, title,\ + self._settings.data_path,\ data_type)).filePath() if fname: # Store the location of the loaded file diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/cluster_status.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/cluster_status.py index f6397ea6c560..099d45abb1a8 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/cluster_status.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/cluster_status.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import os import sys diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_adv_setup.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_adv_setup.py index 8c8315a76363..dfbeb129de7c 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_adv_setup.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_adv_setup.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name ################################################################################ # Advanced Setup Widget ################################################################################ @@ -92,10 +93,10 @@ def initialize_content(self): self._content.filterbadpulses_edit.setText("95.") # Connections from action/event to function to handle - self.connect(self._content.stripvanpeaks_chkbox, QtCore.SIGNAL("clicked()"), + self.connect(self._content.stripvanpeaks_chkbox, QtCore.SIGNAL("clicked()"),\ self._stripvanpeaks_clicked) - self.connect(self._content.help_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.help_button, QtCore.SIGNAL("clicked()"),\ self._show_help) # Hanlder for events # FIXME - Need to add an event hanlder for the change of instrument and facility diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py index 49e6a2bd8bff..8099643ef3e7 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name ################################################################################ # Event Filtering (and advanced) Setup Widget ################################################################################ @@ -111,25 +112,25 @@ def initialize_content(self): # Default states # Connections from action/event to function to handle - self.connect(self._content.timefilter_checkBox, QtCore.SIGNAL("stateChanged(int)"), + self.connect(self._content.timefilter_checkBox, QtCore.SIGNAL("stateChanged(int)"),\ self._filterbytime_statechanged) - self.connect(self._content.logvaluefilter_checkBox, QtCore.SIGNAL("stateChanged(int)"), + self.connect(self._content.logvaluefilter_checkBox, QtCore.SIGNAL("stateChanged(int)"),\ self._filterbylogvalue_statechanged) - self.connect(self._content.load_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.load_button, QtCore.SIGNAL("clicked()"),\ self._run_number_changed) # self.connect(self._content.run_number_edit, QtCore.SIGNAL("textChanged(QString)"), self._run_number_changed) self.connect(self._content.run_number_edit, QtCore.SIGNAL("returnPressed()"), self._run_number_changed) - self.connect(self._content.plot_log_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.plot_log_button, QtCore.SIGNAL("clicked()"),\ self._plot_log_clicked) - self.connect(self._content.syn_logname_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.syn_logname_button, QtCore.SIGNAL("clicked()"),\ self._sync_logname_clicked) - self.connect(self._content.help_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.help_button, QtCore.SIGNAL("clicked()"),\ self._show_help) # Validated widgets @@ -334,15 +335,15 @@ def _plot_log_clicked(self): logproperty = run.getProperty(str(logname)) except RuntimeError: # Unable to plot - msg3 = str("Error! Workspace %s does not contain log %s. " % (str(self._metaws), + msg3 = str("Error! Workspace %s does not contain log %s. " % (str(self._metaws),\ logname)) self._content.info_text_browser.setText(str(msg1+msg3)) return # Construct workspace - output = api.ExportTimeSeriesLog(InputWorkspace = str(self._metaws), - OutputWorkspace = str(logname), - LogName = str(logname), + output = api.ExportTimeSeriesLog(InputWorkspace = str(self._metaws),\ + OutputWorkspace = str(logname),\ + LogName = str(logname),\ IsEventWorkspace = False) #api.DeleteWorkspace(Workspace="PercentStat") @@ -439,7 +440,7 @@ def call_back(xmin, xmax): maxwidget.setText("%-f" % float(xmax)) return - self.logvalue_vs_time_distribution(workspace=ws, + self.logvalue_vs_time_distribution(workspace=ws,\ callback=call_back) return @@ -451,7 +452,7 @@ def logvalue_vs_time_distribution(self, workspace, callback): xmax = workspace.dataX(0)[-1] if callback is not None: from LargeScaleStructures import data_stitching - data_stitching.RangeSelector.connect([workspace], callback, + data_stitching.RangeSelector.connect([workspace], callback,\ xmin=xmin, xmax=xmax) return diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_run_setup.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_run_setup.py index 21e78699c4d2..ebf5f2629f44 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_run_setup.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_run_setup.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name ################################################################################ # This is my first attempt to make a tab from quasi-scratch ################################################################################ @@ -111,15 +112,15 @@ def initialize_content(self): # self._handle_tzero_guess(self._content.use_ei_guess_chkbox.isChecked()) # Connections from action/event to function to handle - self.connect(self._content.calfile_browse, QtCore.SIGNAL("clicked()"), + self.connect(self._content.calfile_browse, QtCore.SIGNAL("clicked()"),\ self._calfile_browse) - self.connect(self._content.charfile_browse, QtCore.SIGNAL("clicked()"), + self.connect(self._content.charfile_browse, QtCore.SIGNAL("clicked()"),\ self._charfile_browse) - self.connect(self._content.outputdir_browse, QtCore.SIGNAL("clicked()"), + self.connect(self._content.outputdir_browse, QtCore.SIGNAL("clicked()"),\ self._outputdir_browse) - self.connect(self._content.binning_edit, QtCore.SIGNAL("valueChanged"), + self.connect(self._content.binning_edit, QtCore.SIGNAL("valueChanged"),\ self._binvalue_edit) - self.connect(self._content.bintype_combo, QtCore.SIGNAL("currentIndexChanged(QString)"), + self.connect(self._content.bintype_combo, QtCore.SIGNAL("currentIndexChanged(QString)"),\ self._bintype_process) #self.connect(self._content.override_emptyrun_checkBox, QtCore.SIGNAL("clicked()"), @@ -129,19 +130,19 @@ def initialize_content(self): #self.connect(self._content.override_vanbkgdrun_checkBox, QtCore.SIGNAL("clicked()"), # self._overridevanbkgdrun_clicked) - self.connect(self._content.disablebkgdcorr_chkbox, QtCore.SIGNAL("clicked()"), + self.connect(self._content.disablebkgdcorr_chkbox, QtCore.SIGNAL("clicked()"),\ self._disablebkgdcorr_clicked) - self.connect(self._content.disablevancorr_chkbox, QtCore.SIGNAL("clicked()"), + self.connect(self._content.disablevancorr_chkbox, QtCore.SIGNAL("clicked()"),\ self._disablevancorr_clicked) - self.connect(self._content.disablevanbkgdcorr_chkbox, QtCore.SIGNAL("clicked()"), + self.connect(self._content.disablevanbkgdcorr_chkbox, QtCore.SIGNAL("clicked()"),\ self._disablevanbkgdcorr_clicked) - self.connect(self._content.usebin_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.usebin_button, QtCore.SIGNAL("clicked()"),\ self._usebin_clicked) - self.connect(self._content.resamplex_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.resamplex_button, QtCore.SIGNAL("clicked()"),\ self._resamplex_clicked) - self.connect(self._content.help_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.help_button, QtCore.SIGNAL("clicked()"),\ self._show_help) # Validated widgets diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_absolute_units.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_absolute_units.py index bf773a667399..a1bd1a8913dd 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_absolute_units.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_absolute_units.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore from functools import partial from reduction_gui.widgets.base_widget import BaseWidget diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_data_corrections.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_data_corrections.py index bcad89d2c524..97fd1f0bf314 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_data_corrections.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_data_corrections.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore from functools import partial from reduction_gui.widgets.base_widget import BaseWidget diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_diagnose_detectors.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_diagnose_detectors.py index bb32beeca1d3..cf561e29be5e 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_diagnose_detectors.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_diagnose_detectors.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore from functools import partial from reduction_gui.widgets.base_widget import BaseWidget diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_pd_sc_conversion.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_pd_sc_conversion.py index 40b9a26ba370..3db7b584dadd 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_pd_sc_conversion.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_pd_sc_conversion.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore from functools import partial from reduction_gui.widgets.base_widget import BaseWidget diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_sample_setup.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_sample_setup.py index 8ec1f100358c..25786527e771 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_sample_setup.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_sample_setup.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore from functools import partial from reduction_gui.widgets.base_widget import BaseWidget @@ -147,9 +148,9 @@ def _grouping_browse(self): self._content.grouping_edit.setText(fname) def _savedir_browse(self): - save_dir = QtGui.QFileDialog.getExistingDirectory(self, "Output Directory - Choose a directory", - os.path.expanduser('~'), - QtGui.QFileDialog.ShowDirsOnly + save_dir = QtGui.QFileDialog.getExistingDirectory(self, "Output Directory - Choose a directory",\ + os.path.expanduser('~'),\ + QtGui.QFileDialog.ShowDirsOnly\ | QtGui.QFileDialog.DontResolveSymlinks) if save_dir: self._content.savedir_edit.setText(save_dir) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py index f2f4319cf527..a2666009a994 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import sys """ diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py index ea4b764e7f2a..9303985ec0d0 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import math @@ -211,8 +212,8 @@ def getMetadata(self,file): This retrieve the metadata from the data event NeXus file """ _full_file_name = file - tmpWks = LoadEventNexus(Filename=_full_file_name, -# OutputWorkspace='tmpWks', + tmpWks = LoadEventNexus(Filename=_full_file_name,\ +# OutputWorkspace='tmpWks',\ MetaDataOnly='1') #mt1 = mtd['tmpWks'] @@ -816,7 +817,7 @@ def _report_error(error=None): f = open(file_path,'w') f.write(content) f.close() - QtGui.QMessageBox.information(self, "Automated reduction script saved", + QtGui.QMessageBox.information(self, "Automated reduction script saved",\ "The automated reduction script has been updated") except: _report_error() @@ -1023,10 +1024,10 @@ def _plot_count_vs_y_bck(self): For REFL, this is Y """ - min, max = self._integrated_plot(True, - self._summary.data_run_number_edit, - self._summary.data_background_from_pixel1, - self._summary.data_background_to_pixel1, + min, max = self._integrated_plot(True,\ + self._summary.data_run_number_edit,\ + self._summary.data_background_from_pixel1,\ + self._summary.data_background_to_pixel1,\ False) def _plot_count_vs_x(self): @@ -1320,7 +1321,7 @@ def _add_data(self): state.geometry_correction_switch = self._summary.geometry_correction_switch.isChecked() #incident medium - _incident_medium_list = [str(self._summary.incident_medium_combobox.itemText(j)) + _incident_medium_list = [str(self._summary.incident_medium_combobox.itemText(j))\ for j in range(self._summary.incident_medium_combobox.count())] _incident_medium_index_selected = self._summary.incident_medium_combobox.currentIndex() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py index 8d7a5d7e4a11..7e781fee6ab0 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # used to parse files more easily from __future__ import with_statement diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py index f888acdcd1d3..6871f9d0befa 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import math @@ -492,7 +493,7 @@ def _report_error(error=None): f = open(file_path,'w') f.write(content) f.close() - QtGui.QMessageBox.information(self, "Automated reduction script saved", + QtGui.QMessageBox.information(self, "Automated reduction script saved",\ "The automated reduction script has been updated") except: _report_error() @@ -1033,7 +1034,7 @@ def get_editing_state(self): m.DataPeakPixels = [int(self._summary.data_peak_from_pixel.text()), int(self._summary.data_peak_to_pixel.text())] - m.data_x_range = [int(self._summary.x_min_edit.text()), + m.data_x_range = [int(self._summary.x_min_edit.text()),\ int(self._summary.x_max_edit.text())] m.data_x_range_flag = self._summary.data_low_res_range_switch.isChecked() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_reduction.py index 4fb464fa0057..decb4f87cd10 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import math @@ -148,7 +149,7 @@ def get_editing_state(self): m.incident_medium_index_selected = self._summary.incident_medium_combobox.currentIndex() - m.data_x_range = [int(self._summary.x_min_edit.text()), + m.data_x_range = [int(self._summary.x_min_edit.text()),\ int(self._summary.x_max_edit.text())] m.data_x_range_flag = self._summary.data_low_res_range_switch.isChecked() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py index d845ccd96107..494bdae69bb5 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import math @@ -314,7 +315,7 @@ def _add_data(self): state.scaling_factor_file = self._summary.cfg_scaling_factor_file_name.text() #incident medium - _incident_medium_list = [str(self._summary.incident_medium_combobox.itemText(j)) + _incident_medium_list = [str(self._summary.incident_medium_combobox.itemText(j))\ for j in range(self._summary.incident_medium_combobox.count())] _incident_medium_index_selected = self._summary.incident_medium_combobox.currentIndex() @@ -429,7 +430,7 @@ def get_state(self): state_list = [] #common incident medium - m.incident_medium_list = [self._summary.incident_medium_combobox.itemText(i) + m.incident_medium_list = [self._summary.incident_medium_combobox.itemText(i)\ for i in range(self._summary.incident_medium_combobox.count())] m.incident_medium_index_selected = self._summary.incident_medium_combobox.currentIndex() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py index 182eafe93435..065345064a76 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import math @@ -359,7 +360,7 @@ def _report_error(error=None): f = open(file_path,'w') f.write(content) f.close() - QtGui.QMessageBox.information(self, "Automated reduction script saved", + QtGui.QMessageBox.information(self, "Automated reduction script saved",\ "The automated reduction script has been updated") except: _report_error() @@ -846,7 +847,7 @@ def get_editing_state(self): m.DataPeakPixels = [int(self._summary.data_peak_from_pixel.text()), int(self._summary.data_peak_to_pixel.text())] - m.data_x_range = [int(self._summary.x_min_edit.text()), + m.data_x_range = [int(self._summary.x_min_edit.text()),\ int(self._summary.x_max_edit.text())] m.data_x_range_flag = self._summary.data_low_res_range_switch.isChecked() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/stitcher.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/stitcher.py index 4ba451ee7e3e..5486443fe023 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/stitcher.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/stitcher.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import sip import os @@ -320,8 +321,8 @@ def _apply(self): message = "Could not scale data\n %s" % sys.exc_value if self._content.scale_to_one_chk.isChecked(): message += "\n\nCheck your Q range near the critical edge" - QtGui.QMessageBox.warning(self, - "Error scaling data", + QtGui.QMessageBox.warning(self,\ + "Error scaling data",\ message) def _pick_specular_ridge(self): @@ -382,8 +383,8 @@ def _scale_data_sets(self): ref_data = item.get_user_data(ref_pol) if ref_data is None: - QtGui.QMessageBox.warning(self, - "Invalid choice of reference cross-section", + QtGui.QMessageBox.warning(self,\ + "Invalid choice of reference cross-section",\ "The selected cross-section is empty, please select another one") return s.append(ref_data) @@ -466,7 +467,7 @@ def _save_result(self, send_email=False): self._stitcher.save_combined(fname, as_canSAS=False) file_list.append(fname) else: - pol_list = ["Off_Off", "On_Off", + pol_list = ["Off_Off", "On_Off",\ "Off_On", "On_On"] for pol in pol_list: try: diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_data.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_data.py index e7ad2b6040b0..bff21bffae1c 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_data.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_data.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import os diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_instrument.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_instrument.py index 7871cb0b37e8..34738beaa8a5 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_instrument.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_instrument.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import math diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_background.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_background.py index 2944e837ece2..c5a77deeb62d 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_background.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_background.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import os diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_detector.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_detector.py index b1151785c73a..42e017168515 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_detector.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_detector.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import os @@ -134,7 +135,7 @@ def _patch_checked(self): def _draw_patch(self): if IS_IN_MANTIDPLOT: - self.show_instrument(self._content.sensitivity_file_edit.text, + self.show_instrument(self._content.sensitivity_file_edit.text,\ workspace=self.patch_ws, tab=2, reload=True, data_proxy=None) def _create_sensitivity(self): diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py index a60f556c2c2f..5c2c1e8879ac 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import math diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_sample_data.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_sample_data.py index 9370179713b7..af57ad1391ad 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_sample_data.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_sample_data.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import os diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py index 0bfeaae8a135..d02ae0d78f49 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import os from reduction_gui.settings.application_settings import GeneralSettings @@ -162,7 +163,7 @@ def _get_catalog(self): self._content.data_set_table.resizeColumnsToContents() def _browse_directory(self): - dir = QtGui.QFileDialog.getExistingDirectory(self, "Open Directory", + dir = QtGui.QFileDialog.getExistingDirectory(self, "Open Directory",\ self._settings.data_path) if dir: # Store the location of the loaded file diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/stitcher.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/stitcher.py index 2b3e26f44914..322e7bad78da 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/stitcher.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/stitcher.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import os from reduction_gui.settings.application_settings import GeneralSettings diff --git a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_adv_setup.py b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_adv_setup.py index b7ce069e2c6e..034e3994dcb1 100644 --- a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_adv_setup.py +++ b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_adv_setup.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'diffraction_adv_setup.ui' @@ -376,7 +377,7 @@ def retranslateUi(self, Frame): self.preserveevents_checkbox.setStatusTip(_translate("Frame", "Check to calculate the absolute scale factor using the direct beam method.", None)) self.preserveevents_checkbox.setText(_translate("Frame", "Preserve Events", None)) self.vanadium_correction_groupbox.setTitle(_translate("Frame", "Strip Vanadium Peaks", None)) - self.mask_help_label.setText(_translate("Frame", "The following input parameters are used to control the algorithm to strip vanadium peaks.\n" + self.mask_help_label.setText(_translate("Frame", "The following input parameters are used to control the algorithm to strip vanadium peaks.\n"\ "", None)) self.stripvanpeaks_chkbox.setToolTip(_translate("Frame", "

Check to subtract fitted vanadium peaks from the known positions.

", None)) self.stripvanpeaks_chkbox.setText(_translate("Frame", "Strip Vanadium Peaks", None)) diff --git a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_filter_setup.py b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_filter_setup.py index eb3a3aa8801f..d88b116c7de1 100644 --- a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_filter_setup.py +++ b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_filter_setup.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'diffraction_filter_setup.ui' @@ -454,7 +455,7 @@ def retranslateUi(self, Frame): self.timeunit_combo.setItemText(1, QtGui.QApplication.translate("Frame", "Nanoseconds", None, QtGui.QApplication.UnicodeUTF8)) self.mask_groupbox.setTitle(QtGui.QApplication.translate("Frame", "Filter By Log Value", None, QtGui.QApplication.UnicodeUTF8)) self.logvaluefilter_checkBox.setToolTip(QtGui.QApplication.translate("Frame", "

Check to enable \'filter by log value\' mode.

", None, QtGui.QApplication.UnicodeUTF8)) - self.mask_help_label.setText(QtGui.QApplication.translate("Frame", "Filtering events by chopping data according to log values.\n" + self.mask_help_label.setText(QtGui.QApplication.translate("Frame", "Filtering events by chopping data according to log values.\n"\ "(1) From user specified log value range;\n" "(2)Log values are separated to equal intervals.", None, QtGui.QApplication.UnicodeUTF8)) self.label_10.setToolTip(QtGui.QApplication.translate("Frame", "

Tolerance of the log value to be included in filter. It is used in the case to filter by multiple values. By default, it is equal to (maxlogvalue-minlogvalue)/interval.

", None, QtGui.QApplication.UnicodeUTF8)) diff --git a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_info.py b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_info.py index 03ce0e29bd70..8db4195d820d 100644 --- a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_info.py +++ b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_info.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'diffraction_info.ui' @@ -51,7 +52,7 @@ def setupUi(self, Dialog): def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "SNSPowderReduction help", None, QtGui.QApplication.UnicodeUTF8)) - self.plainTextEdit.setPlainText(QtGui.QApplication.translate("Dialog", "To use this application, you will need:\n" + self.plainTextEdit.setPlainText(QtGui.QApplication.translate("Dialog", "To use this application, you will need:\n"\ "\n" "- Your Nexus event files (.nxs)\n" "- The corresponding SNS powder diffratomer calibration file for time focussing. \n" diff --git a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_run_setup.py b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_run_setup.py index d6865ca4aae3..cc7c42d4b27e 100644 --- a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_run_setup.py +++ b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_run_setup.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'diffraction_run_setup.ui' @@ -436,7 +437,7 @@ def retranslateUi(self, Frame): self.unit_combo.setItemText(0, _translate("Frame", "dSpacing", None)) self.unit_combo.setItemText(1, _translate("Frame", "MomentumTransfer", None)) self.geometry_options_groupbox.setTitle(_translate("Frame", "Overriding Characterization File", None)) - self.experiment_parameter_help.setText(_translate("Frame", "If characterization file is given, the correction run numbers are given by the file. \n" + self.experiment_parameter_help.setText(_translate("Frame", "If characterization file is given, the correction run numbers are given by the file. \n"\ "The corrections can be overriden and disabled though.", None)) self.disablebkgdcorr_chkbox.setToolTip(_translate("Frame", "

Disable emptry/background correction.

", None)) self.disablebkgdcorr_chkbox.setStatusTip(_translate("Frame", "Select to set the detector distance offset.", None)) @@ -458,7 +459,7 @@ def retranslateUi(self, Frame): self.label_10.setText(_translate("Frame", "Vanadium Run Correction", None)) self.vanbkgdrun_edit.setToolTip(_translate("Frame", "

Enter vanadium background run number.

", None)) self.mask_groupbox.setTitle(_translate("Frame", "Binning", None)) - self.mask_help_label.setText(_translate("Frame", "Choose a file to set your mask. Note that only the mask information, not the data, will be used in the reduction.\n" + self.mask_help_label.setText(_translate("Frame", "Choose a file to set your mask. Note that only the mask information, not the data, will be used in the reduction.\n"\ "The data is only used to help you setting the mask.\n" "The mask information is saved separately so that your data file will NOT be modified.", None)) self.label_9.setToolTip(_translate("Frame", "

User specified maximum TOF of the data.

", None)) diff --git a/Code/Mantid/scripts/Interface/ui/diffraction/ui_filter_info.py b/Code/Mantid/scripts/Interface/ui/diffraction/ui_filter_info.py index 460bdfcbe610..9a448ee278d4 100644 --- a/Code/Mantid/scripts/Interface/ui/diffraction/ui_filter_info.py +++ b/Code/Mantid/scripts/Interface/ui/diffraction/ui_filter_info.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'filter_info.ui' @@ -51,7 +52,7 @@ def setupUi(self, Dialog): def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Filter help", None, QtGui.QApplication.UnicodeUTF8)) - self.plainTextEdit.setPlainText(QtGui.QApplication.translate("Dialog", "To use this application, you will need:\n" + self.plainTextEdit.setPlainText(QtGui.QApplication.translate("Dialog", "To use this application, you will need:\n"\ "\n" "- Your Nexus event files ( _event.nxs)\n" "- The Nexus event file used in this filter setup page must be same to the data reduction page.\n" diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_absolute_units.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_absolute_units.py index e019a1e190d9..4a326237468b 100644 --- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_absolute_units.py +++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_absolute_units.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/inelastic/dgs_absolute_units.ui' diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_data_corrections.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_data_corrections.py index 7f53416ea85e..6ad6b96db96e 100644 --- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_data_corrections.py +++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_data_corrections.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/inelastic/dgs_data_corrections.ui' diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_diagnose_detectors.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_diagnose_detectors.py index c9154b2a56c3..dfbb26eecbe1 100644 --- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_diagnose_detectors.py +++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_diagnose_detectors.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/inelastic/dgs_diagnose_detectors.ui' diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_pd_sc_conversion.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_pd_sc_conversion.py index 816d5f5d01f0..9cd9be763606 100644 --- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_pd_sc_conversion.py +++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_pd_sc_conversion.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/inelastic/dgs_pd_sc_conversion.ui' diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_sample_setup.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_sample_setup.py index ff07c13ee698..88f73ac39881 100644 --- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_sample_setup.py +++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_sample_setup.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file './dgs_sample_setup.ui' diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_choose_col.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_choose_col.py index 73a0a4aa64bd..f231c63e780c 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_choose_col.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_choose_col.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name #This is an extension of refl_columns.py as that is a auto-generated script form pyqt and shouldn't be edited #so this file provides any extra GUI tweaks not easily doable in the designer #for the time being this also includes non-GUI behaviour diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_columns.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_columns.py index 9535885c8cc8..d1fd9c668295 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_columns.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_columns.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'D:\mantid\windows\Code\Mantid\scripts\Interface\ui\reflectometer/refl_columns.ui' diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py index 5e8aabb610e7..128e085c06d4 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import refl_window import refl_save import refl_choose_col diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui_run.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui_run.py index acb98704976e..459c1018ebb7 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui_run.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui_run.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import refl_gui from PyQt4 import QtCore, QtGui diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py index d5b9d9732923..051187316c18 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import refl_options_window from PyQt4 import QtCore, QtGui diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options_window.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options_window.py index 0d4bf0e8273f..a2ab5338fd87 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options_window.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options_window.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'refl_options_window.ui' diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py index 86d774ee8f90..ad186ca6bfdc 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtCore, QtGui import os from mantid.simpleapi import * diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_window.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_window.py index 689e5e4647f9..c4ab20582203 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_window.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_window.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'refl_window.ui' diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_data_refl_simple.py b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_data_refl_simple.py index a4b1339ff18f..4af2bc635311 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_data_refl_simple.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_data_refl_simple.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'data_refl_simple.ui' @@ -1579,7 +1580,7 @@ def retranslateUi(self, Frame): Frame.setWindowTitle(QtGui.QApplication.translate("Frame", "Frame", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_3.setTitle(QtGui.QApplication.translate("Frame", "Angle List", None, QtGui.QApplication.UnicodeUTF8)) self.label_10.setText(QtGui.QApplication.translate("Frame", "List of runs to be stitched together.", None, QtGui.QApplication.UnicodeUTF8)) - self.waiting_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.waiting_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -1685,7 +1686,7 @@ def retranslateUi(self, Frame): self.q_bins_label.setText(QtGui.QApplication.translate("Frame", "Number of bins ", None, QtGui.QApplication.UnicodeUTF8)) self.q_step_label.setText(QtGui.QApplication.translate("Frame", "Q steps ", None, QtGui.QApplication.UnicodeUTF8)) self.q_step_edit.setText(QtGui.QApplication.translate("Frame", "0.02", None, QtGui.QApplication.UnicodeUTF8)) - self.q_step_unit_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.q_step_unit_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -1703,7 +1704,7 @@ def retranslateUi(self, Frame): self.overlapValueLowestErrorRadioButton.setText(QtGui.QApplication.translate("Frame", "use lowest error value", None, QtGui.QApplication.UnicodeUTF8)) self.overlapValueMeanRadioButton.setText(QtGui.QApplication.translate("Frame", "use mean value ", None, QtGui.QApplication.UnicodeUTF8)) self.fourth_column_switch.setText(QtGui.QApplication.translate("Frame", "4th column (precision)", None, QtGui.QApplication.UnicodeUTF8)) - self.dq0_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.dq0_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -1713,14 +1714,14 @@ def retranslateUi(self, Frame): self.dq_over_q_label.setText(QtGui.QApplication.translate("Frame", "dQ/Q", None, QtGui.QApplication.UnicodeUTF8)) self.dq_over_q.setText(QtGui.QApplication.translate("Frame", "0.02", None, QtGui.QApplication.UnicodeUTF8)) self.create_ascii_button.setText(QtGui.QApplication.translate("Frame", "Create ASCII...", None, QtGui.QApplication.UnicodeUTF8)) - self.edited_warning_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.edited_warning_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" "

Click Save To List to apply your changes →

", None, QtGui.QApplication.UnicodeUTF8)) self.add_dataset_btn.setToolTip(QtGui.QApplication.translate("Frame", "Click to add the data set above to the reduction list", None, QtGui.QApplication.UnicodeUTF8)) self.add_dataset_btn.setText(QtGui.QApplication.translate("Frame", "Save to list", None, QtGui.QApplication.UnicodeUTF8)) - self.auto_reduce_help_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.auto_reduce_help_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_sf_calculator.py b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_sf_calculator.py index 4cca295d5af7..622ad2badb72 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_sf_calculator.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_sf_calculator.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'refl_sf_calculator.ui' @@ -536,7 +537,7 @@ def retranslateUi(self, Frame): Frame.setWindowTitle(QtGui.QApplication.translate("Frame", "Frame", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_3.setTitle(QtGui.QApplication.translate("Frame", "Angle List", None, QtGui.QApplication.UnicodeUTF8)) self.label_10.setText(QtGui.QApplication.translate("Frame", "List of direct beam scans for absolute normalization", None, QtGui.QApplication.UnicodeUTF8)) - self.waiting_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.waiting_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -557,7 +558,7 @@ def retranslateUi(self, Frame): self.groupBox.setTitle(QtGui.QApplication.translate("Frame", "Direct beam scan", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("Frame", "Run number", None, QtGui.QApplication.UnicodeUTF8)) self.label_3.setText(QtGui.QApplication.translate("Frame", "Hit [ENTER] to refresh Metadata", None, QtGui.QApplication.UnicodeUTF8)) - self.data_run_number_processing.setText(QtGui.QApplication.translate("Frame", "\n" + self.data_run_number_processing.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -589,7 +590,7 @@ def retranslateUi(self, Frame): self.det_angle_unit_label_7.setText(QtGui.QApplication.translate("Frame", "mm", None, QtGui.QApplication.UnicodeUTF8)) self.label_27.setText(QtGui.QApplication.translate("Frame", "S2 width :", None, QtGui.QApplication.UnicodeUTF8)) self.det_angle_unit_label_3.setText(QtGui.QApplication.translate("Frame", "mm", None, QtGui.QApplication.UnicodeUTF8)) - self.edited_warning_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.edited_warning_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_stitching.py b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_stitching.py index 833bbd096b29..fdc12c8d191b 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_stitching.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refl_stitching.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/reflectometer/refl_stitching.ui' @@ -239,7 +240,7 @@ def setupUi(self, Frame): def retranslateUi(self, Frame): Frame.setWindowTitle(QtGui.QApplication.translate("Frame", "Frame", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_3.setTitle(QtGui.QApplication.translate("Frame", "Angle List", None, QtGui.QApplication.UnicodeUTF8)) - self.label.setText(QtGui.QApplication.translate("Frame", "\n" + self.label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -251,12 +252,12 @@ def retranslateUi(self, Frame): "

\n" "

", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("Frame", "Run", None, QtGui.QApplication.UnicodeUTF8)) - self.label_4.setText(QtGui.QApplication.translate("Frame", "Scaling\n" + self.label_4.setText(QtGui.QApplication.translate("Frame", "Scaling\n"\ "factor", None, QtGui.QApplication.UnicodeUTF8)) - self.label_3.setText(QtGui.QApplication.translate("Frame", "Low-end\n" + self.label_3.setText(QtGui.QApplication.translate("Frame", "Low-end\n"\ "points to\n" "skip", None, QtGui.QApplication.UnicodeUTF8)) - self.label_5.setText(QtGui.QApplication.translate("Frame", "High-end\n" + self.label_5.setText(QtGui.QApplication.translate("Frame", "High-end\n"\ "points to\n" "skip", None, QtGui.QApplication.UnicodeUTF8)) self.scale_to_one_chk.setText(QtGui.QApplication.translate("Frame", "Scale to unity", None, QtGui.QApplication.UnicodeUTF8)) diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refm_reduction.py b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refm_reduction.py index 2d64b50dd307..267934bda984 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refm_reduction.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refm_reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'refm_reduction.ui' @@ -1233,9 +1234,9 @@ def setupUi(self, Frame): def retranslateUi(self, Frame): Frame.setWindowTitle(QtGui.QApplication.translate("Frame", "Frame", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_3.setTitle(QtGui.QApplication.translate("Frame", "Angle List", None, QtGui.QApplication.UnicodeUTF8)) - self.label_10.setText(QtGui.QApplication.translate("Frame", "List of runs to be \n" + self.label_10.setText(QtGui.QApplication.translate("Frame", "List of runs to be \n"\ "stitched together.", None, QtGui.QApplication.UnicodeUTF8)) - self.waiting_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.waiting_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -1319,7 +1320,7 @@ def retranslateUi(self, Frame): self.tof_max_label2.setText(QtGui.QApplication.translate("Frame", " µs", None, QtGui.QApplication.UnicodeUTF8)) self.plot_tof_btn.setToolTip(QtGui.QApplication.translate("Frame", "Plot TOF distribution", None, QtGui.QApplication.UnicodeUTF8)) self.plot_tof_btn.setText(QtGui.QApplication.translate("Frame", "TOF distribution", None, QtGui.QApplication.UnicodeUTF8)) - self.edited_warning_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.edited_warning_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -1342,7 +1343,7 @@ def retranslateUi(self, Frame): self.angle_offset_unit_label.setText(QtGui.QApplication.translate("Frame", " degrees", None, QtGui.QApplication.UnicodeUTF8)) self.outdir_label.setText(QtGui.QApplication.translate("Frame", "Output directory", None, QtGui.QApplication.UnicodeUTF8)) self.outdir_browse_button.setText(QtGui.QApplication.translate("Frame", "Browse", None, QtGui.QApplication.UnicodeUTF8)) - self.auto_reduce_help_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.auto_reduce_help_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_info.py b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_info.py index 721d18f94ac9..49e5bff30d84 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_info.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_info.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/eqsans_info.ui' @@ -46,7 +47,7 @@ def setupUi(self, Dialog): def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "EQSANS help", None, QtGui.QApplication.UnicodeUTF8)) - self.plainTextEdit.setPlainText(QtGui.QApplication.translate("Dialog", "To use this application, you will need:\n" + self.plainTextEdit.setPlainText(QtGui.QApplication.translate("Dialog", "To use this application, you will need:\n"\ "\n" "- Your Nexus event files (.nxs)\n" "- The corresponding eqsans_configuration.xxxx files [optional]\n" diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_instrument.py b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_instrument.py index e591d6a37ced..870b7a7d93c5 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_instrument.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_instrument.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/eqsans_instrument.ui' @@ -576,7 +577,7 @@ def retranslateUi(self, Frame): self.output_dir_edit.setStatusTip(QtGui.QApplication.translate("Frame", "Output directory for reduced data.", None, QtGui.QApplication.UnicodeUTF8)) self.output_dir_browse_button.setText(QtGui.QApplication.translate("Frame", "Browse", None, QtGui.QApplication.UnicodeUTF8)) self.geometry_options_groupbox.setTitle(QtGui.QApplication.translate("Frame", "Experiment Parameters", None, QtGui.QApplication.UnicodeUTF8)) - self.experiment_parameter_help.setText(QtGui.QApplication.translate("Frame", "The sample-detector distance is updated automatically when a sample data file is selected.\n" + self.experiment_parameter_help.setText(QtGui.QApplication.translate("Frame", "The sample-detector distance is updated automatically when a sample data file is selected.\n"\ "Values can be selected by hand by checking the boxes below.", None, QtGui.QApplication.UnicodeUTF8)) self.detector_offset_chk.setToolTip(QtGui.QApplication.translate("Frame", "Select to set the detector distance offset.", None, QtGui.QApplication.UnicodeUTF8)) self.detector_offset_chk.setStatusTip(QtGui.QApplication.translate("Frame", "Select to set the detector distance offset.", None, QtGui.QApplication.UnicodeUTF8)) @@ -592,7 +593,7 @@ def retranslateUi(self, Frame): self.config_mask_chk.setToolTip(QtGui.QApplication.translate("Frame", "Select to mask detectors as specified in the configuration file, as applicable.", None, QtGui.QApplication.UnicodeUTF8)) self.config_mask_chk.setStatusTip(QtGui.QApplication.translate("Frame", "Select to mask detectors as specified in the configuration file, as applicable.", None, QtGui.QApplication.UnicodeUTF8)) self.config_mask_chk.setText(QtGui.QApplication.translate("Frame", "Use mask from configuration file as applicable", None, QtGui.QApplication.UnicodeUTF8)) - self.mask_help_label.setText(QtGui.QApplication.translate("Frame", "Choose a file to set your mask. Note that only the mask information, not the data, will be used in the reduction.\n" + self.mask_help_label.setText(QtGui.QApplication.translate("Frame", "Choose a file to set your mask. Note that only the mask information, not the data, will be used in the reduction.\n"\ "The data is only used to help you setting the mask.\n" "The mask information is saved separately so that your data file will NOT be modified.", None, QtGui.QApplication.UnicodeUTF8)) self.mask_check.setToolTip(QtGui.QApplication.translate("Frame", "Select to apply the mask built from the specified data file.", None, QtGui.QApplication.UnicodeUTF8)) diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_sample_data.py b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_sample_data.py index 1e899ec825c2..c2e42a69e670 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_sample_data.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_sample_data.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/eqsans_sample_data.ui' diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_background.py b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_background.py index 4f12a693d2f8..4ab3d4e4e9d5 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_background.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_background.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/hfir_background.ui' diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_detector.py b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_detector.py index b3733d77fd4b..cf5fc9336376 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_detector.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_detector.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/hfir_detector.ui' diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_instrument.py b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_instrument.py index 7080dd0f3fe3..2224f3ec82bd 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_instrument.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_instrument.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/hfir_instrument.ui' @@ -536,7 +537,7 @@ def retranslateUi(self, Frame): Frame.setWindowTitle(QtGui.QApplication.translate("Frame", "Frame", None, QtGui.QApplication.UnicodeUTF8)) self.instr_name_label.setText(QtGui.QApplication.translate("Frame", "BIOSANS", None, QtGui.QApplication.UnicodeUTF8)) self.reduction_options_group.setTitle(QtGui.QApplication.translate("Frame", "Reduction Options", None, QtGui.QApplication.UnicodeUTF8)) - self.label_6.setText(QtGui.QApplication.translate("Frame", "\n" + self.label_6.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -572,7 +573,7 @@ def retranslateUi(self, Frame): self.label.setText(QtGui.QApplication.translate("Frame", "Number of Q bins ", None, QtGui.QApplication.UnicodeUTF8)) self.n_q_bins_edit.setToolTip(QtGui.QApplication.translate("Frame", "Enter the number of Q bins for the output I(Q) distribution.", None, QtGui.QApplication.UnicodeUTF8)) self.label_3.setText(QtGui.QApplication.translate("Frame", "Number of sub-pixels", None, QtGui.QApplication.UnicodeUTF8)) - self.n_sub_pix_edit.setToolTip(QtGui.QApplication.translate("Frame", "Enter the number of sub-pixels in each direction of a detector pixel to use for the\n" + self.n_sub_pix_edit.setToolTip(QtGui.QApplication.translate("Frame", "Enter the number of sub-pixels in each direction of a detector pixel to use for the\n"\ "radial averaging. For instance, entering 3 will sub-divide each detector pixel by 3\n" "in each direction and will create 9 sub-pixels.", None, QtGui.QApplication.UnicodeUTF8)) self.error_weighting_check.setText(QtGui.QApplication.translate("Frame", "Error weighting", None, QtGui.QApplication.UnicodeUTF8)) @@ -587,7 +588,7 @@ def retranslateUi(self, Frame): self.label_11.setText(QtGui.QApplication.translate("Frame", "Wedge offset [deg]", None, QtGui.QApplication.UnicodeUTF8)) self.wedge_offset_edit.setToolTip(QtGui.QApplication.translate("Frame", "Enter an angular offset for the wedges, in degrees.", None, QtGui.QApplication.UnicodeUTF8)) self.geometry_options_groupbox.setTitle(QtGui.QApplication.translate("Frame", "Experiment Parameters", None, QtGui.QApplication.UnicodeUTF8)) - self.experiment_parameter_help.setText(QtGui.QApplication.translate("Frame", "The sample-detector distance and wavelength are updated automatically when a sample data file is selected.\n" + self.experiment_parameter_help.setText(QtGui.QApplication.translate("Frame", "The sample-detector distance and wavelength are updated automatically when a sample data file is selected.\n"\ "Values can be selected by hand by checking the boxes below.", None, QtGui.QApplication.UnicodeUTF8)) self.detector_offset_chk.setToolTip(QtGui.QApplication.translate("Frame", "Select to set the detector distance offset.", None, QtGui.QApplication.UnicodeUTF8)) self.detector_offset_chk.setText(QtGui.QApplication.translate("Frame", "Detector distance offset [mm]", None, QtGui.QApplication.UnicodeUTF8)) @@ -608,7 +609,7 @@ def retranslateUi(self, Frame): self.mask_side_front_radio.setText(QtGui.QApplication.translate("Frame", "Front", None, QtGui.QApplication.UnicodeUTF8)) self.mask_side_back_radio.setToolTip(QtGui.QApplication.translate("Frame", "Select to mask the back panel of the detector.", None, QtGui.QApplication.UnicodeUTF8)) self.mask_side_back_radio.setText(QtGui.QApplication.translate("Frame", "Back", None, QtGui.QApplication.UnicodeUTF8)) - self.label_5.setText(QtGui.QApplication.translate("Frame", "Choose a file to set your mask. Note that only the mask information, not the data, will be used in the reduction.\n" + self.label_5.setText(QtGui.QApplication.translate("Frame", "Choose a file to set your mask. Note that only the mask information, not the data, will be used in the reduction.\n"\ "The data is only used to help you setting the mask.\n" "The mask information is saved separately so that your data file will NOT be modified.", None, QtGui.QApplication.UnicodeUTF8)) self.mask_check.setToolTip(QtGui.QApplication.translate("Frame", "Select to apply the mask built from the specified data file.", None, QtGui.QApplication.UnicodeUTF8)) diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_sample_data.py b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_sample_data.py index 9f61e3268220..834aa6ef746c 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_sample_data.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_sample_data.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/hfir_sample_data.ui' diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_trans_direct_beam.py b/Code/Mantid/scripts/Interface/ui/sans/ui_trans_direct_beam.py index 2d0f5b0d4cd4..423ff87ff5f5 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_trans_direct_beam.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_trans_direct_beam.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/trans_direct_beam.ui' diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_trans_spreader.py b/Code/Mantid/scripts/Interface/ui/sans/ui_trans_spreader.py index bf6726a520d5..566620ef1ad0 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_trans_spreader.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_trans_spreader.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/trans_spreader.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_cluster_details_dialog.py b/Code/Mantid/scripts/Interface/ui/ui_cluster_details_dialog.py index 5a7723885a96..d29d1c852590 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_cluster_details_dialog.py +++ b/Code/Mantid/scripts/Interface/ui/ui_cluster_details_dialog.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/cluster_details_dialog.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_cluster_status.py b/Code/Mantid/scripts/Interface/ui/ui_cluster_status.py index 09839356ba28..edb55cc71116 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_cluster_status.py +++ b/Code/Mantid/scripts/Interface/ui/ui_cluster_status.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/cluster_status.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_data_catalog.py b/Code/Mantid/scripts/Interface/ui/ui_data_catalog.py index 04b37cdfe961..9893c53b9a45 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_data_catalog.py +++ b/Code/Mantid/scripts/Interface/ui/ui_data_catalog.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/data_catalog.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_hfir_output.py b/Code/Mantid/scripts/Interface/ui/ui_hfir_output.py index 9f0603eb5ead..b779a4dc13d7 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_hfir_output.py +++ b/Code/Mantid/scripts/Interface/ui/ui_hfir_output.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/hfir_output.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_instrument_dialog.py b/Code/Mantid/scripts/Interface/ui/ui_instrument_dialog.py index 5baa1882f8e9..67b3ab66b280 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_instrument_dialog.py +++ b/Code/Mantid/scripts/Interface/ui/ui_instrument_dialog.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/instrument_dialog.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_reduction_main.py b/Code/Mantid/scripts/Interface/ui/ui_reduction_main.py index 5352477c0e49..f3fecebf0c6e 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_reduction_main.py +++ b/Code/Mantid/scripts/Interface/ui/ui_reduction_main.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'reduction_main.ui' @@ -114,7 +115,7 @@ def setupUi(self, SANSReduction): def retranslateUi(self, SANSReduction): SANSReduction.setWindowTitle(_translate("SANSReduction", "SANS Reduction", None)) - self.label.setText(_translate("SANSReduction", "\n" + self.label.setText(_translate("SANSReduction", "\n"\ "\n" diff --git a/Code/Mantid/scripts/Interface/ui/ui_stitcher.py b/Code/Mantid/scripts/Interface/ui/ui_stitcher.py index a06ea1446f35..9ca6c11a4af1 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_stitcher.py +++ b/Code/Mantid/scripts/Interface/ui/ui_stitcher.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/stitcher.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_trans_direct_beam.py b/Code/Mantid/scripts/Interface/ui/ui_trans_direct_beam.py index 77d34dbd9a69..d7a996b26006 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_trans_direct_beam.py +++ b/Code/Mantid/scripts/Interface/ui/ui_trans_direct_beam.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/trans_direct_beam.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_trans_spreader.py b/Code/Mantid/scripts/Interface/ui/ui_trans_spreader.py index 6a2072489a60..d5d5119dbcc1 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_trans_spreader.py +++ b/Code/Mantid/scripts/Interface/ui/ui_trans_spreader.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/trans_spreader.ui' diff --git a/Code/Mantid/scripts/LargeScaleStructures/EQSANS_geometry.py b/Code/Mantid/scripts/LargeScaleStructures/EQSANS_geometry.py index 11c91894edc1..501f59eb7ebf 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/EQSANS_geometry.py +++ b/Code/Mantid/scripts/LargeScaleStructures/EQSANS_geometry.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from geometry_writer import MantidGeom import math @@ -54,8 +55,8 @@ def create_geometry(file_name=None, tube_width=TUBE_WIDTH, tube_length=TUBE_SIZE det.addComponent(id_str, id_str) doc_handle = det.makeTypeElement(id_str) - det.addCylinderPixel("pixel", (0.0, 0.0, 0.0), (0.0, 1.0, 0.0), - (tube_width/2.0), + det.addCylinderPixel("pixel", (0.0, 0.0, 0.0), (0.0, 1.0, 0.0),\ + (tube_width/2.0),\ (tube_length/NUM_PIXELS_PER_TUBE)) for i in range(0, NUM_BANKS/2): diff --git a/Code/Mantid/scripts/LargeScaleStructures/REF_L_geometry.py b/Code/Mantid/scripts/LargeScaleStructures/REF_L_geometry.py index f60a886bf4ca..8dff73421bb4 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/REF_L_geometry.py +++ b/Code/Mantid/scripts/LargeScaleStructures/REF_L_geometry.py @@ -1,5 +1,5 @@ +#pylint: disable=invalid-name from geometry_writer import MantidGeom -import math NUM_PIXELS_PER_TUBE = 304 NUM_TUBES = 256 diff --git a/Code/Mantid/scripts/LargeScaleStructures/ReflectometerCors.py b/Code/Mantid/scripts/LargeScaleStructures/ReflectometerCors.py index 8de9fd47cf73..7e5311c04ec7 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/ReflectometerCors.py +++ b/Code/Mantid/scripts/LargeScaleStructures/ReflectometerCors.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from mantid.simpleapi import * def heliumDetectorEff(workspace): diff --git a/Code/Mantid/scripts/LargeScaleStructures/data_stitching.py b/Code/Mantid/scripts/LargeScaleStructures/data_stitching.py index 43eb1c295419..976d7f45a2ca 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/data_stitching.py +++ b/Code/Mantid/scripts/LargeScaleStructures/data_stitching.py @@ -1,13 +1,12 @@ +#pylint: disable=invalid-name import os -import copy -import math from mantid.simpleapi import * from mantid.kernel import Logger IS_IN_MANTIDPLOT = True try: import mantidplot - from PyQt4 import QtGui, QtCore + from PyQt4 import QtCore except: IS_IN_MANTIDPLOT = False @@ -26,8 +25,8 @@ def __init__(self): def disconnect(self): if IS_IN_MANTIDPLOT: - mantidplot.app.disconnect(mantidplot.app.mantidUI, - QtCore.SIGNAL("x_range_update(double,double)"), + mantidplot.app.disconnect(mantidplot.app.mantidUI,\ + QtCore.SIGNAL("x_range_update(double,double)"),\ self._call_back) def connect(self, ws, call_back, xmin=None, xmax=None, @@ -41,8 +40,8 @@ def connect(self, ws, call_back, xmin=None, xmax=None, self._call_back = call_back self._ws_output_base = ws_output_base - mantidplot.app.connect(mantidplot.app.mantidUI, - QtCore.SIGNAL("x_range_update(double,double)"), + mantidplot.app.connect(mantidplot.app.mantidUI,\ + QtCore.SIGNAL("x_range_update(double,double)"),\ self._call_back) g = mantidplot.graph(self._graph) @@ -226,9 +225,9 @@ def apply_scale(self, xmin=None, xmax=None): y_trim.append(y[i]) e_trim.append(e[i]) - CreateWorkspace(DataX=x_trim, DataY=y_trim, DataE=e_trim, - OutputWorkspace=self._ws_scaled, - UnitX="MomentumTransfer", + CreateWorkspace(DataX=x_trim, DataY=y_trim, DataE=e_trim,\ + OutputWorkspace=self._ws_scaled,\ + UnitX="MomentumTransfer",\ ParentWorkspace=self._ws_name) dq_scaled = mtd[self._ws_scaled].dataDx(0) @@ -525,9 +524,9 @@ def cmp(p1,p2): combined = sorted(zipped, cmp) x,y,e,dx = zip(*combined) - CreateWorkspace(DataX=x, DataY=y, DataE=e, - OutputWorkspace=ws_combined, - UnitX="MomentumTransfer", + CreateWorkspace(DataX=x, DataY=y, DataE=e,\ + OutputWorkspace=ws_combined,\ + UnitX="MomentumTransfer",\ ParentWorkspace=first_ws) dxtmp = mtd[ws_combined].dataDx(0) diff --git a/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py b/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py index 1d68dcbc7ad6..b4e5b77b847f 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py +++ b/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py @@ -1,6 +1,6 @@ +#pylint: disable=invalid-name from xml.dom.minidom import getDOMImplementation from datetime import datetime -from string import split,join import re class MantidGeom: @@ -117,7 +117,7 @@ def addDetectorPixels(self, name, r=[], theta=[], phi=[], names=[], energy=[]): for j in range(len(r[i])): if (str(r[i][j]) != "nan"): basecomponent = self._append_child("component", type_element, type="pixel") - location_element = self._append_child("location", basecomponent,r=str(r[i][j]), + location_element = self._append_child("location", basecomponent,r=str(r[i][j]),\ t=str(theta[i][j]), p=str(phi[i][j]), name=str(names[i][j])) self._append_child("facing", location_element, x="0.0", y="0.0", z="0.0") @@ -332,7 +332,7 @@ def addCylinderPixel(self, name, center_bottom_base, axis, pixel_radius, self._append_child("height", cylinder, val=str(pixel_height)) self._append_child("algebra", type_element, val="cyl-approx") - def addCuboidPixel(self, name, lfb_pt, lft_pt, lbb_pt, rfb_pt, + def addCuboidPixel(self, name, lfb_pt, lft_pt, lbb_pt, rfb_pt,\ is_type="detector"): """ Add a cuboid pixel. The origin of the cuboid is assumed to be the @@ -341,13 +341,13 @@ def addCuboidPixel(self, name, lfb_pt, lft_pt, lbb_pt, rfb_pt, """ type_element = self._append_child("type", self._root, **{"name":name, "is":is_type}) cuboid = self._append_child("cuboid", type_element, id="shape") - self._append_child("left-front-bottom-point", cuboid, x=str(lfb_pt[0]), + self._append_child("left-front-bottom-point", cuboid, x=str(lfb_pt[0]),\ y=str(lfb_pt[1]), z=str(lfb_pt[2])) - self._append_child("left-front-top-point", cuboid, x=str(lft_pt[0]), + self._append_child("left-front-top-point", cuboid, x=str(lft_pt[0]),\ y=str(lft_pt[1]), z=str(lft_pt[2])) - self._append_child("left-back-bottom-point", cuboid, x=str(lbb_pt[0]), + self._append_child("left-back-bottom-point", cuboid, x=str(lbb_pt[0]),\ y=str(lbb_pt[1]), z=str(lbb_pt[2])) - self._append_child("right-front-bottom-point", cuboid, x=str(rfb_pt[0]), + self._append_child("right-front-bottom-point", cuboid, x=str(rfb_pt[0]),\ y=str(rfb_pt[1]), z=str(rfb_pt[2])) self._append_child("algebra", type_element, val="shape") @@ -389,11 +389,11 @@ def addDetectorIds(self, idname, idlist): id_element = self._append_child("idlist", self._root, idname=idname) for i in range(num_ids): if idlist[(i*3)+2] is None: - self._append_child("id", id_element, start=str(idlist[(i*3)]), + self._append_child("id", id_element, start=str(idlist[(i*3)]),\ end=str(idlist[(i*3)+1])) else: - self._append_child("id", id_element, start=str(idlist[(i*3)]), - step=str(idlist[(i*3)+2]), + self._append_child("id", id_element, start=str(idlist[(i*3)]),\ + step=str(idlist[(i*3)+2]),\ end=str(idlist[(i*3)+1])) def addMonitorIds(self, ids=[]): diff --git a/Code/Mantid/scripts/ORNL_SANS.py b/Code/Mantid/scripts/ORNL_SANS.py index b26c507a6d61..c0cb689df6f5 100644 --- a/Code/Mantid/scripts/ORNL_SANS.py +++ b/Code/Mantid/scripts/ORNL_SANS.py @@ -1,8 +1,8 @@ +#pylint: disable=invalid-name """ Script used to start the HFIR SANS reduction gui from Mantidplot """ from reduction_application import ReductionGUI -from PyQt4 import QtCore, uic reducer = ReductionGUI(instrument_list=["BIOSANS", "GPSANS", "EQSANS"]) if reducer.setup_layout(load_last=True): diff --git a/Code/Mantid/scripts/Powder_Diffraction_Reduction.py b/Code/Mantid/scripts/Powder_Diffraction_Reduction.py index dd74e42e4e07..e803a5898f5e 100644 --- a/Code/Mantid/scripts/Powder_Diffraction_Reduction.py +++ b/Code/Mantid/scripts/Powder_Diffraction_Reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Script used to start the DGS reduction GUI from MantidPlot """ diff --git a/Code/Mantid/scripts/PyChop.py b/Code/Mantid/scripts/PyChop.py index e349285143ae..650936bba2ea 100644 --- a/Code/Mantid/scripts/PyChop.py +++ b/Code/Mantid/scripts/PyChop.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from mantid import config from PyChop import fluxGUI from PyChop import PyChopGUI @@ -7,10 +8,10 @@ def qapp(): if QtGui.QApplication.instance(): - app = QtGui.QApplication.instance() + _app = QtGui.QApplication.instance() else: - app = QtGui.QApplication(sys.argv) - return app + _app = QtGui.QApplication(sys.argv) + return _app app = qapp() instr_name = config['default.instrument'] diff --git a/Code/Mantid/scripts/PyChop/PyChop.py b/Code/Mantid/scripts/PyChop/PyChop.py index 9c9874475f83..9498d3a32069 100644 --- a/Code/Mantid/scripts/PyChop/PyChop.py +++ b/Code/Mantid/scripts/PyChop/PyChop.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import time as time import math import numpy diff --git a/Code/Mantid/scripts/PyChop/PyChopGUI.py b/Code/Mantid/scripts/PyChop/PyChopGUI.py index 67c4801132ef..73140bc45410 100644 --- a/Code/Mantid/scripts/PyChop/PyChopGUI.py +++ b/Code/Mantid/scripts/PyChop/PyChopGUI.py @@ -1,16 +1,10 @@ +#pylint: disable=invalid-name -import sys from PyChopUI import Ui_MainWindow -from PyQt4 import QtCore, uic,QtGui -#from DirectEnergyConversion import * -import time as time +from PyQt4 import QtCore, QtGui from mantidplot import * -import dgreduce -import inspect -import numpy from mantid import * from mantid.simpleapi import * -import math import PyChop class MainWindow(QtGui.QMainWindow): diff --git a/Code/Mantid/scripts/PyChop/PyChopUI.py b/Code/Mantid/scripts/PyChop/PyChopUI.py index 4c56ae2ec080..a36624b4cf51 100644 --- a/Code/Mantid/scripts/PyChop/PyChopUI.py +++ b/Code/Mantid/scripts/PyChop/PyChopUI.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/Users/jon/QtSDK/pychopui.ui' diff --git a/Code/Mantid/scripts/PyChop/PyChop_LET_UI.py b/Code/Mantid/scripts/PyChop/PyChop_LET_UI.py index 2470ecff8724..b25f6b025567 100644 --- a/Code/Mantid/scripts/PyChop/PyChop_LET_UI.py +++ b/Code/Mantid/scripts/PyChop/PyChop_LET_UI.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Mantid\Code\Mantid\scripts\PyChop\PyChop_LET_UI.ui' diff --git a/Code/Mantid/scripts/PyChop/fluxGUI.py b/Code/Mantid/scripts/PyChop/fluxGUI.py index 989aff9fd9bd..df654459f675 100644 --- a/Code/Mantid/scripts/PyChop/fluxGUI.py +++ b/Code/Mantid/scripts/PyChop/fluxGUI.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import sys from PyChop_LET_UI import Ui_MainWindow #import line for the UI python class from PyQt4 import QtCore, QtGui #import others if needed @@ -111,7 +112,7 @@ def letSelected(self): QtGui.QMessageBox.warning(self, "Currently You have to switch gui to select another instrument") self.ui.actionLET.setChecked(True) def otherInstrumentSelected(self,INAME): - reply = QtGui.QMessageBox.question(self, 'Selecting : '+INAME, + reply = QtGui.QMessageBox.question(self, 'Selecting : '+INAME,\ "Do you want to switch GUI?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: config['default.instrument'] = INAME diff --git a/Code/Mantid/scripts/REFL_Reduction.py b/Code/Mantid/scripts/REFL_Reduction.py index ef1b36bd3c63..8038e3f00867 100644 --- a/Code/Mantid/scripts/REFL_Reduction.py +++ b/Code/Mantid/scripts/REFL_Reduction.py @@ -1,8 +1,8 @@ +#pylint: disable=invalid-name """ Script used to start the REFL reduction gui from Mantidplot """ from reduction_application import ReductionGUI -from PyQt4 import QtCore, uic reducer = ReductionGUI(instrument="REFL", instrument_list=["REFL"]) if reducer.setup_layout(load_last=True): diff --git a/Code/Mantid/scripts/REFL_SF_Calculator.py b/Code/Mantid/scripts/REFL_SF_Calculator.py index eb094088327c..eabf63819a2d 100644 --- a/Code/Mantid/scripts/REFL_SF_Calculator.py +++ b/Code/Mantid/scripts/REFL_SF_Calculator.py @@ -1,8 +1,8 @@ +#pylint: disable=invalid-name """ Script used to start the REFL SF calculator gui from Mantidplot """ from reduction_application import ReductionGUI -from PyQt4 import QtCore, uic reducer = ReductionGUI(instrument="REFLSF", instrument_list=["REFLSF"]) if reducer.setup_layout(load_last=True): diff --git a/Code/Mantid/scripts/REFM_Reduction.py b/Code/Mantid/scripts/REFM_Reduction.py index f56996b14c9b..d589aa0b2c13 100644 --- a/Code/Mantid/scripts/REFM_Reduction.py +++ b/Code/Mantid/scripts/REFM_Reduction.py @@ -1,8 +1,8 @@ +#pylint: disable=invalid-name """ Script used to start the REFL reduction gui from Mantidplot """ from reduction_application import ReductionGUI -from PyQt4 import QtCore, uic reducer = ReductionGUI(instrument="REFM", instrument_list=["REFM"]) if reducer.setup_layout(load_last=True): diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/combineMulti.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/combineMulti.py index 81467796e337..39c88637742e 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/combineMulti.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/combineMulti.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from l2q import * from mantid.simpleapi import * import math @@ -75,9 +76,9 @@ def stitch2(ws1, ws2, output_ws_name, begoverlap,endoverlap,Qmin,Qmax,binning,sc manual_scalefactor = False scalefactor = 1.0 # Interally use the Stitch1D algorithm. - outputs = Stitch1D(LHSWorkspace=ws1, RHSWorkspace=ws2, - OutputWorkspace=output_ws_name, StartOverlap=begoverlap, EndOverlap=endoverlap, - UseManualScaleFactor=manual_scalefactor, + outputs = Stitch1D(LHSWorkspace=ws1, RHSWorkspace=ws2,\ + OutputWorkspace=output_ws_name, StartOverlap=begoverlap, EndOverlap=endoverlap,\ + UseManualScaleFactor=manual_scalefactor,\ ManualScaleFactor=scalefactor, Params="%f,%f,%f" % (Qmin, binning, Qmax)) return outputs @@ -104,9 +105,9 @@ def combine2(wksp1,wksp2,outputwksp,begoverlap,endoverlap,Qmin,Qmax,binning,scal manual_scalefactor = False scalefactor = 1.0 # Interally use the Stitch1D algorithm. - outputs = Stitch1D(LHSWorkspace=mtd[wksp1], RHSWorkspace=mtd[wksp2], - OutputWorkspace=outputwksp, StartOverlap=begoverlap, EndOverlap=endoverlap, - UseManualScaleFactor=manual_scalefactor, + outputs = Stitch1D(LHSWorkspace=mtd[wksp1], RHSWorkspace=mtd[wksp2],\ + OutputWorkspace=outputwksp, StartOverlap=begoverlap, EndOverlap=endoverlap,\ + UseManualScaleFactor=manual_scalefactor,\ ManualScaleFactor=scalefactor, Params="%f,%f,%f" % (Qmin, binning, Qmax)) outscalefactor = outputs[1] diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py index 5507b75bff15..5b8bf98c7498 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import mantid.simpleapi as msi import mantid.api from mantid.kernel import logger diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/l2q.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/l2q.py index a05e5ae10332..f5954ab46c0b 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/l2q.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/l2q.py @@ -1,7 +1,7 @@ +#pylint: disable=invalid-name import math from mantid.simpleapi import * # New API -from mantid.geometry import ReferenceFrame def l2q(ws,whichDet,theta, sample_component_name): ''' diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/load_live_runs.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/load_live_runs.py index 8627309e7403..4af7dc825f57 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/load_live_runs.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/load_live_runs.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from mantid.simpleapi import * def get_live_data(instrument_name, frequency = 60, accumulation = "Add", output_name = "live"): StartLiveData(Instrument=str(instrument_name), UpdateEvery = frequency, Outputworkspace=str(output_name), AccumulationMethod = accumulation) diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py index f2fac19542b9..1e2a4500e629 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from math import * try: diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py index 7034bf842664..742d1b04520c 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name ''' SVN Info: The variables below will only get subsituted at svn checkout if the repository is configured for variable subsitution. @@ -91,12 +92,12 @@ def quick(run, theta=None, pointdet=True,roi=[0,0], db=[0,0], trans='', polcorr= cPp = idf_defaults['cPp'] - return quick_explicit(run=run, i0_monitor_index = i0_monitor_index, lambda_min = lambda_min, lambda_max = lambda_max, - point_detector_start = point_detector_start, point_detector_stop = point_detector_stop, - multi_detector_start = multi_detector_start, background_min = background_min, background_max = background_max, - int_min = int_min, int_max = int_max, theta = theta, pointdet = pointdet, roi = roi, db = db, trans = trans, - debug = debug, correction_strategy = correction_strategy, stitch_start_overlap=stitch_start_overlap, - stitch_end_overlap=stitch_end_overlap, stitch_params=stitch_params, polcorr=polcorr, crho=crho, calpha=calpha, cAp=cAp, cPp=cPp, + return quick_explicit(run=run, i0_monitor_index = i0_monitor_index, lambda_min = lambda_min, lambda_max = lambda_max,\ + point_detector_start = point_detector_start, point_detector_stop = point_detector_stop,\ + multi_detector_start = multi_detector_start, background_min = background_min, background_max = background_max,\ + int_min = int_min, int_max = int_max, theta = theta, pointdet = pointdet, roi = roi, db = db, trans = trans,\ + debug = debug, correction_strategy = correction_strategy, stitch_start_overlap=stitch_start_overlap,\ + stitch_end_overlap=stitch_end_overlap, stitch_params=stitch_params, polcorr=polcorr, crho=crho, calpha=calpha, cAp=cAp, cPp=cPp,\ detector_component_name=detector_component_name, sample_component_name=sample_component_name, correct_positions=correct_positions) @@ -290,7 +291,7 @@ def make_trans_corr(transrun, stitch_start_overlap, stitch_end_overlap, stitch_p _detector_ws_llam = Divide(LHSWorkspace=_detector_ws_llam, RHSWorkspace=_mon_int_trans) print stitch_start_overlap, stitch_end_overlap, stitch_params - transWS, outputScaling = Stitch1D(LHSWorkspace=_detector_ws_slam, RHSWorkspace=_detector_ws_llam, StartOverlap=stitch_start_overlap, + transWS, outputScaling = Stitch1D(LHSWorkspace=_detector_ws_slam, RHSWorkspace=_detector_ws_llam, StartOverlap=stitch_start_overlap,\ EndOverlap=stitch_end_overlap, Params=stitch_params) transWS = RenameWorkspace(InputWorkspace=transWS, OutputWorkspace="TRANS_" + slam + "_" + llam) @@ -319,8 +320,8 @@ def transCorr(transrun, i_vs_lam, lambda_min, lambda_max, background_min, backgr else: logger.debug("Creating new transmission correction workspace.") # Make the transmission correction workspace. - _transWS = make_trans_corr(transrun, stitch_start_overlap, stitch_end_overlap, stitch_params, - lambda_min, lambda_max, background_min, background_max, + _transWS = make_trans_corr(transrun, stitch_start_overlap, stitch_end_overlap, stitch_params,\ + lambda_min, lambda_max, background_min, background_max,\ int_min, int_max, detector_index_ranges, i0_monitor_index,) #got sometimes very slight binning diferences, so do this again: diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/saveModule.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/saveModule.py index 2aba6a0cad54..46b5f7866b8b 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/saveModule.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/saveModule.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtCore from mantid.simpleapi import * import numpy as n diff --git a/Code/Mantid/scripts/SANS/ISISCommandInterface.py b/Code/Mantid/scripts/SANS/ISISCommandInterface.py index d7c2bbee8be0..7c181d5918a6 100644 --- a/Code/Mantid/scripts/SANS/ISISCommandInterface.py +++ b/Code/Mantid/scripts/SANS/ISISCommandInterface.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Enables the SANS commands (listed at http://www.mantidproject.org/SANS) to be run diff --git a/Code/Mantid/scripts/SANS/SANSBatchMode.py b/Code/Mantid/scripts/SANS/SANSBatchMode.py index d1a15a85f1dd..58ba1a1287e5 100644 --- a/Code/Mantid/scripts/SANS/SANSBatchMode.py +++ b/Code/Mantid/scripts/SANS/SANSBatchMode.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # SANSBatchMode.py # diff --git a/Code/Mantid/scripts/SANS/SANSUtility.py b/Code/Mantid/scripts/SANS/SANSUtility.py index 48fb6cef0dd2..f0d604f2ff49 100644 --- a/Code/Mantid/scripts/SANS/SANSUtility.py +++ b/Code/Mantid/scripts/SANS/SANSUtility.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name ######################################################### # This module contains utility functions common to the # SANS data reduction scripts diff --git a/Code/Mantid/scripts/SANS/SANSadd2.py b/Code/Mantid/scripts/SANS/SANSadd2.py index 6f9fbb481586..8a878d45dad2 100644 --- a/Code/Mantid/scripts/SANS/SANSadd2.py +++ b/Code/Mantid/scripts/SANS/SANSadd2.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import os from mantid.simpleapi import * from mantid.kernel import Logger @@ -218,7 +219,7 @@ def _loadWS(entry, ext, inst, wsName, rawTypes, period=_NO_INDIVIDUAL_PERIODS) : # cal time dif in seconds timeDif = (timeArray[i+1].total_nanoseconds()-timeArray[i].total_nanoseconds())*1e-9 if timeDif > 172800: - sanslog.warning('Time increments in the proton charge log of ' + filename + ' are suspicious large.' + + sanslog.warning('Time increments in the proton charge log of ' + filename + ' are suspicious large.' +\ ' For example a time difference of ' + str(timeDif) + " seconds has been observed.") break diff --git a/Code/Mantid/scripts/SANS/centre_finder.py b/Code/Mantid/scripts/SANS/centre_finder.py index caec3403e946..a3f2e4ca4658 100644 --- a/Code/Mantid/scripts/SANS/centre_finder.py +++ b/Code/Mantid/scripts/SANS/centre_finder.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import isis_reducer from isis_reduction_steps import StripEndNans from mantid.simpleapi import * @@ -98,10 +99,10 @@ def move(self, setup, x, y): """ x = -x y = -y - MoveInstrumentComponent(Workspace=setup.get_sample().wksp_name, + MoveInstrumentComponent(Workspace=setup.get_sample().wksp_name,\ ComponentName=self.detector, X=x, Y=y, RelativePosition=True) if setup.get_can(): - MoveInstrumentComponent(Workspace=setup.get_can().wksp_name, + MoveInstrumentComponent(Workspace=setup.get_can().wksp_name,\ ComponentName=self.detector, X=x, Y=y, RelativePosition=True) # Create a workspace with a quadrant value in it diff --git a/Code/Mantid/scripts/SANS/isis_instrument.py b/Code/Mantid/scripts/SANS/isis_instrument.py index 3257193467a4..8fdd32688fb0 100644 --- a/Code/Mantid/scripts/SANS/isis_instrument.py +++ b/Code/Mantid/scripts/SANS/isis_instrument.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import datetime import math import os diff --git a/Code/Mantid/scripts/SANS/isis_reducer.py b/Code/Mantid/scripts/SANS/isis_reducer.py index b81d902301fe..30e9ab5afdda 100644 --- a/Code/Mantid/scripts/SANS/isis_reducer.py +++ b/Code/Mantid/scripts/SANS/isis_reducer.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ ISIS-specific implementation of the SANS Reducer. diff --git a/Code/Mantid/scripts/SANS/isis_reduction_steps.py b/Code/Mantid/scripts/SANS/isis_reduction_steps.py index c56ae0991fe4..6d09cf983533 100644 --- a/Code/Mantid/scripts/SANS/isis_reduction_steps.py +++ b/Code/Mantid/scripts/SANS/isis_reduction_steps.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ This file defines what happens in each step in the data reduction, it's the guts of the reduction. See ISISReducer for order the steps are run @@ -847,7 +848,7 @@ def _mask_line(self, startPoint, length, width, angle): @param angle: angle of line in xy-plane in units of degrees @return: return xml shape string ''' - return self._finite_cylinder(startPoint, width/2000.0, length, + return self._finite_cylinder(startPoint, width/2000.0, length,\ [math.cos(angle*math.pi/180.0),math.sin(angle*math.pi/180.0),0.0], "arm") @@ -950,7 +951,7 @@ def execute(self, reducer, workspace): det = ws.getInstrument().getComponentByName('rear-detector') det_Z = det.getPos().getZ() start_point = [self.arm_x, self.arm_y, det_Z] - MaskDetectorsInShape(Workspace=workspace,ShapeXML= + MaskDetectorsInShape(Workspace=workspace,ShapeXML=\ self._mask_line(start_point, 1e6, self.arm_width, self.arm_angle)) output_ws, detector_list = ExtractMask(InputWorkspace=workspace, OutputWorkspace="__mask") @@ -1288,8 +1289,8 @@ def setup_wksp(self, inputWS, inst, wavbining, pre_monitor, post_monitor): #exclude unused spectra because the sometimes empty/sometimes not spectra can cause errors with interpolate spectrum1 = min(pre_monitor, post_monitor) spectrum2 = max(pre_monitor, post_monitor) - CropWorkspace(InputWorkspace=inputWS,OutputWorkspace= tmpWS, - StartWorkspaceIndex=self._get_index(spectrum1), + CropWorkspace(InputWorkspace=inputWS,OutputWorkspace= tmpWS,\ + StartWorkspaceIndex=self._get_index(spectrum1),\ EndWorkspaceIndex=self._get_index(spectrum2)) if inst.name() == 'LOQ': @@ -1300,7 +1301,7 @@ def setup_wksp(self, inputWS, inst, wavbining, pre_monitor, post_monitor): back_start, back_end = inst.get_TOFs(spectra_number) if back_start and back_end: index = spectra_number - spectrum1 - CalculateFlatBackground(InputWorkspace=tmpWS,OutputWorkspace= tmpWS, StartX=back_start, EndX=back_end, + CalculateFlatBackground(InputWorkspace=tmpWS,OutputWorkspace= tmpWS, StartX=back_start, EndX=back_end,\ WorkspaceIndexList=index, Mode='Mean') ConvertUnits(InputWorkspace=tmpWS,OutputWorkspace= tmpWS,Target="Wavelength") @@ -1399,9 +1400,9 @@ def calculate(self, reducer): wavbin +=','+str(translambda_max) #set up the input workspaces - trans_tmp_out = self.setup_wksp(trans_raw, reducer.instrument, + trans_tmp_out = self.setup_wksp(trans_raw, reducer.instrument,\ wavbin, pre_sample, post_sample) - direct_tmp_out = self.setup_wksp(direct_raw, reducer.instrument, + direct_tmp_out = self.setup_wksp(direct_raw, reducer.instrument,\ wavbin, pre_sample, post_sample) fittedtransws, unfittedtransws = self.get_wksp_names( @@ -1709,8 +1710,8 @@ def execute(self, reducer, workspace): if (reducer.wide_angle_correction and reducer.transmission_calculator.output_wksp): #calculate the transmission wide angle correction _issueWarning("sans solid angle correction execution") - SANSWideAngleCorrection(SampleData=workspace, - TransmissionData = reducer.transmission_calculator.output_wksp, + SANSWideAngleCorrection(SampleData=workspace,\ + TransmissionData = reducer.transmission_calculator.output_wksp,\ OutputWorkspace='transmissionWorkspace') wavepixeladj = 'transmissionWorkspace' #create normalization workspaces diff --git a/Code/Mantid/scripts/SCD_Reduction/ReduceDictionary.py b/Code/Mantid/scripts/SCD_Reduction/ReduceDictionary.py index 1997b44f22ec..7702c2297123 100644 --- a/Code/Mantid/scripts/SCD_Reduction/ReduceDictionary.py +++ b/Code/Mantid/scripts/SCD_Reduction/ReduceDictionary.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # File: ReduceDictionary.py # diff --git a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py index 4ba4a06d53fb..3be9f366704a 100644 --- a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py +++ b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # File: ReduceOneSCD_Run.py # # Version 2.0, modified to work with Mantid's new python interface. @@ -161,7 +162,7 @@ calibration_file_1 = "" if (calibration_file_2 is None ): calibration_file_2 = "" - LoadIsawDetCal( event_ws, + LoadIsawDetCal( event_ws,\ Filename=calibration_file_1, Filename2=calibration_file_2 ) monitor_ws = LoadNexusMonitors( Filename=full_name ) @@ -181,7 +182,7 @@ # Make MD workspace using Lorentz correction, to find peaks # MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D", - dEAnalysisMode="Elastic", QConversionScales="Q in A^-1", + dEAnalysisMode="Elastic", QConversionScales="Q in A^-1",\ LorentzCorrection='1', MinValues=minVals, MaxValues=maxVals, SplitInto='2', SplitThreshold='50',MaxRecursionDepth='11' ) # @@ -228,9 +229,9 @@ # if integrate_predicted_peaks: print "PREDICTING peaks to integrate...." - peaks_ws = PredictPeaks( InputWorkspace=peaks_ws, - WavelengthMin=min_pred_wl, WavelengthMax=max_pred_wl, - MinDSpacing=min_pred_dspacing, MaxDSpacing=max_pred_dspacing, + peaks_ws = PredictPeaks( InputWorkspace=peaks_ws,\ + WavelengthMin=min_pred_wl, WavelengthMax=max_pred_wl,\ + MinDSpacing=min_pred_dspacing, MaxDSpacing=max_pred_dspacing,\ ReflectionCondition='Primitive' ) else: print "Only integrating FOUND peaks ...." @@ -256,16 +257,16 @@ # workspace to do raw integration (we don't need high resolution or # LorentzCorrection to do the raw sphere integration ) # - MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D", - dEAnalysisMode="Elastic", QConversionScales="Q in A^-1", - LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals, + MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D",\ + dEAnalysisMode="Elastic", QConversionScales="Q in A^-1",\ + LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals,\ SplitInto='2', SplitThreshold='500',MaxRecursionDepth='10' ) - peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=peak_radius, - CoordinatesToUse="Q (sample frame)", - BackgroundOuterRadius=bkg_outer_radius, - BackgroundInnerRadius=bkg_inner_radius, - PeaksWorkspace=peaks_ws, + peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=peak_radius,\ + CoordinatesToUse="Q (sample frame)",\ + BackgroundOuterRadius=bkg_outer_radius,\ + BackgroundInnerRadius=bkg_inner_radius,\ + PeaksWorkspace=peaks_ws,\ IntegrateIfOnEdge=integrate_if_edge_peak ) elif use_cylindrical_integration: # @@ -274,51 +275,51 @@ # workspace to do raw integration (we don't need high resolution or # LorentzCorrection to do the raw sphere integration ) # - MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D", - dEAnalysisMode="Elastic", QConversionScales="Q in A^-1", - LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals, + MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D",\ + dEAnalysisMode="Elastic", QConversionScales="Q in A^-1",\ + LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals,\ SplitInto='2', SplitThreshold='500',MaxRecursionDepth='10' ) - peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=peak_radius, - CoordinatesToUse="Q (sample frame)", - BackgroundOuterRadius=bkg_outer_radius, - BackgroundInnerRadius=bkg_inner_radius, - PeaksWorkspace=peaks_ws, - IntegrateIfOnEdge=integrate_if_edge_peak, - Cylinder=use_cylindrical_integration,CylinderLength=cylinder_length, - PercentBackground=cylinder_percent_bkg, - IntegrationOption=cylinder_int_option, + peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=peak_radius,\ + CoordinatesToUse="Q (sample frame)",\ + BackgroundOuterRadius=bkg_outer_radius,\ + BackgroundInnerRadius=bkg_inner_radius,\ + PeaksWorkspace=peaks_ws,\ + IntegrateIfOnEdge=integrate_if_edge_peak,\ + Cylinder=use_cylindrical_integration,CylinderLength=cylinder_length,\ + PercentBackground=cylinder_percent_bkg,\ + IntegrationOption=cylinder_int_option,\ ProfileFunction=cylinder_profile_fit) elif use_fit_peaks_integration: - event_ws = Rebin( InputWorkspace=event_ws, + event_ws = Rebin( InputWorkspace=event_ws,\ Params=rebin_params, PreserveEvents=preserve_events ) - peaks_ws = PeakIntegration( InPeaksWorkspace=peaks_ws, InputWorkspace=event_ws, - IkedaCarpenterTOF=use_ikeda_carpenter, - MatchingRunNo=True, + peaks_ws = PeakIntegration( InPeaksWorkspace=peaks_ws, InputWorkspace=event_ws,\ + IkedaCarpenterTOF=use_ikeda_carpenter,\ + MatchingRunNo=True,\ NBadEdgePixels=n_bad_edge_pixels ) elif use_ellipse_integration: - peaks_ws= IntegrateEllipsoids( InputWorkspace=event_ws, PeaksWorkspace = peaks_ws, - RegionRadius = ellipse_region_radius, - SpecifySize = ellipse_size_specified, - PeakSize = peak_radius, - BackgroundOuterSize = bkg_outer_radius, + peaks_ws= IntegrateEllipsoids( InputWorkspace=event_ws, PeaksWorkspace = peaks_ws,\ + RegionRadius = ellipse_region_radius,\ + SpecifySize = ellipse_size_specified,\ + PeakSize = peak_radius,\ + BackgroundOuterSize = bkg_outer_radius,\ BackgroundInnerSize = bkg_inner_radius ) elif use_cylindrical_integration: profiles_filename = output_directory + "/" + instrument_name + '_' + run + '.profiles' - MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D", - dEAnalysisMode="Elastic", QConversionScales="Q in A^-1", - LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals, + MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D",\ + dEAnalysisMode="Elastic", QConversionScales="Q in A^-1",\ + LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals,\ SplitInto='2', SplitThreshold='500',MaxRecursionDepth='10' ) - peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=cylinder_radius, - CoordinatesToUse="Q (sample frame)", - Cylinder='1', CylinderLength = cylinder_length, - PercentBackground = '20', ProfileFunction = 'NoFit', - ProfilesFile = profiles_filename, - PeaksWorkspace=peaks_ws, + peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=cylinder_radius,\ + CoordinatesToUse="Q (sample frame)",\ + Cylinder='1', CylinderLength = cylinder_length,\ + PercentBackground = '20', ProfileFunction = 'NoFit',\ + ProfilesFile = profiles_filename,\ + PeaksWorkspace=peaks_ws,\ ) # @@ -343,11 +344,11 @@ cell_type + "_" + centering + ".mat" run_conventional_integrate_file = output_directory + "/" + run + "_" + \ cell_type + "_" + centering + ".integrate" - SelectCellOfType( PeaksWorkspace=peaks_ws, - CellType=cell_type, Centering=centering, - AllowPermutations=allow_perm, + SelectCellOfType( PeaksWorkspace=peaks_ws,\ + CellType=cell_type, Centering=centering,\ + AllowPermutations=allow_perm,\ Apply=True, Tolerance=tolerance ) - SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, + SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False,\ Filename=run_conventional_integrate_file ) SaveIsawUB( InputWorkspace=peaks_ws, Filename=run_conventional_matrix_file ) diff --git a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py index c9526a94b1e5..296beb0688c7 100644 --- a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py +++ b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # File: ReduceSCD_Parallel.py # @@ -218,7 +219,7 @@ def run ( self ): conventional_integrate_file = conv_name + ".integrate" conventional_matrix_file = conv_name + ".mat" - SelectCellOfType( PeaksWorkspace=peaks_ws, CellType=cell_type, Centering=centering, + SelectCellOfType( PeaksWorkspace=peaks_ws, CellType=cell_type, Centering=centering,\ AllowPermutations=allow_perm, Apply=True, Tolerance=tolerance ) SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=conventional_integrate_file ) SaveIsawUB( InputWorkspace=peaks_ws, Filename=conventional_matrix_file ) diff --git a/Code/Mantid/scripts/TofConverter.py b/Code/Mantid/scripts/TofConverter.py index 4cee4a0aa5d9..51002010f8e1 100644 --- a/Code/Mantid/scripts/TofConverter.py +++ b/Code/Mantid/scripts/TofConverter.py @@ -1,13 +1,14 @@ +#pylint: disable=invalid-name from TofConverter import converterGUI from PyQt4 import QtGui import sys def qapp(): if QtGui.QApplication.instance(): - app = QtGui.QApplication.instance() + _app = QtGui.QApplication.instance() else: - app = QtGui.QApplication(sys.argv) - return app + _app = QtGui.QApplication(sys.argv) + return _app app = qapp() reducer = converterGUI.MainWindow()#the main ui class in this file is called MainWindow diff --git a/Code/Mantid/scripts/TofConverter/Ui_MainWindow.py b/Code/Mantid/scripts/TofConverter/Ui_MainWindow.py index 44bc763c0eff..4b89ca9c0aa9 100644 --- a/Code/Mantid/scripts/TofConverter/Ui_MainWindow.py +++ b/Code/Mantid/scripts/TofConverter/Ui_MainWindow.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'CONVERTER.ui' diff --git a/Code/Mantid/scripts/TofConverter/converterGUI.py b/Code/Mantid/scripts/TofConverter/converterGUI.py index ae01ad13ad93..23a0a7bd3bee 100644 --- a/Code/Mantid/scripts/TofConverter/converterGUI.py +++ b/Code/Mantid/scripts/TofConverter/converterGUI.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from Ui_MainWindow import Ui_MainWindow #import line for the UI python class from PyQt4 import QtCore, QtGui import math diff --git a/Code/Mantid/scripts/Vates/Diffraction_Workflow.py b/Code/Mantid/scripts/Vates/Diffraction_Workflow.py index 42c36224f254..657bb13c6a3f 100644 --- a/Code/Mantid/scripts/Vates/Diffraction_Workflow.py +++ b/Code/Mantid/scripts/Vates/Diffraction_Workflow.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # Basic parameters for Triphylite Crystal #Name of the workspaces to create ws_name = "TOPAZ_3132" @@ -11,26 +12,26 @@ ws = AnvredCorrection(InputWorkspace=ws, LinearScatteringCoef=0.451, LinearAbsorptionCoef=0.993, Radius=0.14) # Convert to Q space -LabQ = ConvertToDiffractionMDWorkspace(InputWorkspace=ws, LorentzCorrection='0', +LabQ = ConvertToDiffractionMDWorkspace(InputWorkspace=ws, LorentzCorrection='0',\ OutputDimensions='Q (lab frame)', SplitInto=2, SplitThreshold=150) # Find peaks PeaksLattice = FindPeaksMD(InputWorkspace=LabQ,MaxPeaks=100) # 3d integration to centroid peaks -PeaksLattice = CentroidPeaksMD(InputWorkspace=LabQ, +PeaksLattice = CentroidPeaksMD(InputWorkspace=LabQ,\ PeakRadius=0.12, PeaksWorkspace=PeaksLattice) # Find the UB matrix using the peaks and known lattice parameters -FindUBUsingLatticeParameters(PeaksWorkspace=PeaksLattice, a=10.3522, b=6.0768, c=4.7276, +FindUBUsingLatticeParameters(PeaksWorkspace=PeaksLattice, a=10.3522, b=6.0768, c=4.7276,\ alpha=90, beta=90, gamma=90, NumInitial=20, Tolerance=0.12) # And index to HKL IndexPeaks(PeaksWorkspace=PeaksLattice, Tolerance=0.12) # Integrate peaks in Q space using spheres -PeaksLattice_Integrated = IntegratePeaksMD(InputWorkspace=LabQ,PeakRadius=0.12, - BackgroundOuterRadius=0.18,BackgroundInnerRadius=0.15, +PeaksLattice_Integrated = IntegratePeaksMD(InputWorkspace=LabQ,PeakRadius=0.12,\ + BackgroundOuterRadius=0.18,BackgroundInnerRadius=0.15,\ PeaksWorkspace=PeaksLattice) # Save for SHELX @@ -44,7 +45,7 @@ PeaksLatticeFFT = FindPeaksMD(InputWorkspace=LabQ, MaxPeaks=100) # 3d integration to centroid peaks -PeaksLatticeFFT = CentroidPeaksMD(InputWorkspace=LabQ, +PeaksLatticeFFT = CentroidPeaksMD(InputWorkspace=LabQ,\ PeakRadius=0.12, PeaksWorkspace=PeaksLatticeFFT) # Find the UB matrix using FFT @@ -54,8 +55,8 @@ IndexPeaks(PeaksWorkspace=PeaksLatticeFFT, Tolerance=0.12) # Integrate peaks in Q space using spheres -PeaksLatticeFFT = IntegratePeaksMD(InputWorkspace=LabQ, PeakRadius=0.12, - BackgroundOuterRadius=0.18,BackgroundInnerRadius=0.15, +PeaksLatticeFFT = IntegratePeaksMD(InputWorkspace=LabQ, PeakRadius=0.12,\ + BackgroundOuterRadius=0.18,BackgroundInnerRadius=0.15,\ PeaksWorkspace=PeaksLatticeFFT) # Save for SHELX @@ -65,11 +66,11 @@ # Part 3. Utilising the UB # Copy the UB matrix back to the original workspace -CopySample(InputWorkspace=PeaksLattice, OutputWorkspace=ws, +CopySample(InputWorkspace=PeaksLattice, OutputWorkspace=ws,\ CopyName='0',CopyMaterial='0',CopyEnvironment='0',CopyShape='0', CopyLattice=1) # Convert to reciprocal space, in the sample frame -HKL = ConvertToDiffractionMDWorkspace(InputWorkspace=ws, +HKL = ConvertToDiffractionMDWorkspace(InputWorkspace=ws,\ OutputDimensions='HKL',LorentzCorrection='0', SplitInto='2',SplitThreshold='150') # ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/Code/Mantid/scripts/Vates/Inelastic_Workflow.py b/Code/Mantid/scripts/Vates/Inelastic_Workflow.py index de2512098123..ecdb520d355a 100644 --- a/Code/Mantid/scripts/Vates/Inelastic_Workflow.py +++ b/Code/Mantid/scripts/Vates/Inelastic_Workflow.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name #Common names filename = 'fe_demo_30.sqw' ws_in ='fe_demo_30' @@ -7,17 +8,17 @@ LoadSQW(filename, OutputWorkspace=ws_in) #Bin the workspace in an axis aligned manner. Creates a Histogrammed MD workspace. -BinMD(InputWorkspace=ws_in,OutputWorkspace='binned_axis_aligned',AxisAligned=True, -AlignedDim0='Q_\\zeta,-1.5,5,100', -AlignedDim1='Q_\\xi,-6,6,100', -AlignedDim2='Q_\\eta,-6,6,100', +BinMD(InputWorkspace=ws_in,OutputWorkspace='binned_axis_aligned',AxisAligned=True,\ +AlignedDim0='Q_\\zeta,-1.5,5,100',\ +AlignedDim1='Q_\\xi,-6,6,100',\ +AlignedDim2='Q_\\eta,-6,6,100',\ AlignedDim3='E,0,150,30') #Bin the workpace using a coordinate transformation to rotate the output.. Creates a Histogrammed MD workspace. -BinMD(InputWorkspace=ws_in,OutputWorkspace='binned_rotated',AxisAligned=False, -BasisVector0='Qx,Ang,1,0.5,0,0,1,100', -BasisVector1='Qy,Ang,-0.5,1,0,0,1,100', -BasisVector2='Qz,Ang,0,0,1.25,0,1,100', +BinMD(InputWorkspace=ws_in,OutputWorkspace='binned_rotated',AxisAligned=False,\ +BasisVector0='Qx,Ang,1,0.5,0,0,1,100',\ +BasisVector1='Qy,Ang,-0.5,1,0,0,1,100',\ +BasisVector2='Qz,Ang,0,0,1.25,0,1,100',\ Origin='0,0,0,0') #Save the MDEW workspace in the MDEW nexus format. diff --git a/Code/Mantid/scripts/Vates/SXD_NaCl.py b/Code/Mantid/scripts/Vates/SXD_NaCl.py index 15f343be3c33..409c422541ef 100644 --- a/Code/Mantid/scripts/Vates/SXD_NaCl.py +++ b/Code/Mantid/scripts/Vates/SXD_NaCl.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name def reportUnitCell(peaks_ws): latt = peaks_ws.sample().getOrientedLattice() print "-- Unit Cell --" diff --git a/Code/Mantid/scripts/reducer_singleton.py b/Code/Mantid/scripts/reducer_singleton.py index 4e0e18910a4e..fa786b1ac71b 100644 --- a/Code/Mantid/scripts/reducer_singleton.py +++ b/Code/Mantid/scripts/reducer_singleton.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import random import string import os diff --git a/Code/Mantid/scripts/reduction/command_interface.py b/Code/Mantid/scripts/reduction/command_interface.py index 7b6f2150cf5c..8c48534ccdbb 100644 --- a/Code/Mantid/scripts/reduction/command_interface.py +++ b/Code/Mantid/scripts/reduction/command_interface.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ List of user commands. """ diff --git a/Code/Mantid/scripts/reduction/find_data.py b/Code/Mantid/scripts/reduction/find_data.py index 9e3a01832851..b8c98059fe35 100644 --- a/Code/Mantid/scripts/reduction/find_data.py +++ b/Code/Mantid/scripts/reduction/find_data.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import os import mantid.api as api from mantid.simpleapi import * diff --git a/Code/Mantid/scripts/reduction/instruments/example/ExampleRedStep.py b/Code/Mantid/scripts/reduction/instruments/example/ExampleRedStep.py index 78a7973d0534..29ce2d2ac9fc 100644 --- a/Code/Mantid/scripts/reduction/instruments/example/ExampleRedStep.py +++ b/Code/Mantid/scripts/reduction/instruments/example/ExampleRedStep.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * diff --git a/Code/Mantid/scripts/reduction/instruments/example/example_reducer.py b/Code/Mantid/scripts/reduction/instruments/example/example_reducer.py index 3f4a197f88fd..8d8f5be12b32 100644 --- a/Code/Mantid/scripts/reduction/instruments/example/example_reducer.py +++ b/Code/Mantid/scripts/reduction/instruments/example/example_reducer.py @@ -1,9 +1,9 @@ +#pylint: disable=invalid-name """ Simple Reducer example """ 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 diff --git a/Code/Mantid/scripts/reduction/instruments/inelastic/direct_command_interface.py b/Code/Mantid/scripts/reduction/instruments/inelastic/direct_command_interface.py index 23cd9fd62229..4f74c10fd217 100644 --- a/Code/Mantid/scripts/reduction/instruments/inelastic/direct_command_interface.py +++ b/Code/Mantid/scripts/reduction/instruments/inelastic/direct_command_interface.py @@ -1,8 +1,8 @@ +#pylint: disable=invalid-name """ Command set for Direct Geometry reduction """ # Import the specific commands that we need -import mantid from mantid.api import AlgorithmManager from reduction.command_interface import * from inelastic_reducer import InelasticReducer @@ -10,35 +10,26 @@ def ARCS(): Clear(InelasticReducer) - pass - def CNCS(): Clear(InelasticReducer) - pass def HYSPEC(): Clear(InelasticReducer) - pass def LET(): Clear(InelasticReducer) - pass def MAPS(): Clear(InelasticReducer) - pass def MARI(): Clear(InelasticReducer) - pass def MERLIN(): Clear(InelasticReducer) - pass def SEQUOIA(): Clear(InelasticReducer) - pass def DefaultLoader(): step = InelasticLoader() diff --git a/Code/Mantid/scripts/reduction/instruments/inelastic/inelastic_reducer.py b/Code/Mantid/scripts/reduction/instruments/inelastic/inelastic_reducer.py index 937313415847..4a508855dd0b 100644 --- a/Code/Mantid/scripts/reduction/instruments/inelastic/inelastic_reducer.py +++ b/Code/Mantid/scripts/reduction/instruments/inelastic/inelastic_reducer.py @@ -1,7 +1,7 @@ +#pylint: disable=invalid-name """ Inelastic specific implementation of the Reducer. """ -import mantid from reduction import Reducer # Validate_step is a decorator that allows both Python algorithms and # ReductionStep objects to be passed to the Reducer. diff --git a/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py b/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py index 16a0e2baba2d..8f8345eae747 100644 --- a/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py +++ b/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py @@ -1,5 +1,4 @@ -import mantidplot -import mantid +#pylint: disable=invalid-name import os from mantid.simpleapi import * @@ -138,12 +137,12 @@ def _load_entry(entry, ws, title=""): if is_pixel_y: grouping_file = os.path.join(instr_dir, "Grouping", "REFL_Detector_Grouping_Sum_X.xml") - output_2d = GroupDetectors(InputWorkspace=output_2d, + output_2d = GroupDetectors(InputWorkspace=output_2d,\ MapFile=grouping_file) else: grouping_file = os.path.join(instr_dir, "Grouping", "REFL_Detector_Grouping_Sum_Y.xml") - output_2d = GroupDetectors(InputWorkspace=output_2d, + output_2d = GroupDetectors(InputWorkspace=output_2d,\ MapFile=grouping_file) if instrument=="REFM": diff --git a/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py b/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py index 21993d251ff0..0f7fcb029383 100644 --- a/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py +++ b/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py @@ -1,9 +1,9 @@ -from numpy import zeros, ones, arctan2, arange, shape, sqrt, fliplr, asfarray, where, mean, sum, empty, NAN +#pylint: disable=invalid-name +from numpy import zeros, arctan2, arange, shape, sqrt, fliplr, asfarray, mean, sum, NAN from mantid.simpleapi import * # from MantidFramework import * import math import os.path -import sys h = 6.626e-34 #m^2 kg s^-1 m = 1.675e-27 #kg @@ -414,7 +414,7 @@ def convertWorkspaceToQ(ws_data, outputWorkspace.setDistribution(True) - outputWorkspace = Rebin(InputWorkspace=outputWorkspace, + outputWorkspace = Rebin(InputWorkspace=outputWorkspace,\ Params=q_binning) else: @@ -459,7 +459,7 @@ def convertWorkspaceToQ(ws_data, outputWorkspace.setDistribution(True) - outputWorkspace = Rebin(InputWorkspace=outputWorkspace, + outputWorkspace = Rebin(InputWorkspace=outputWorkspace,\ Params=q_binning) return outputWorkspace @@ -1014,8 +1014,8 @@ def cropTOF(inputWorkspace, min, max, type): used here to crop the TOF range """ print '--> crop ' , type , ' workspace in TOF' - ws_histo_data = CropWorkspace(InputWorkspace = inputWorkspace, - XMin = min, + ws_histo_data = CropWorkspace(InputWorkspace = inputWorkspace,\ + XMin = min,\ XMax = max) return ws_histo_data @@ -1027,9 +1027,9 @@ def normalizeNeXus(inputWorkspace, type): ws_histo_data = NormaliseByCurrent(InputWorkspace=inputWorkspace) return ws_histo_data -def integrateOverLowResRange(mt1, - dataLowResRange, - type, +def integrateOverLowResRange(mt1,\ + dataLowResRange,\ + type,\ is_nexus_detector_rotated_flag): """ This creates the integrated workspace over the low resolution range leaving @@ -1133,7 +1133,7 @@ def substractBackground(tof_axis, y_axis, y_error_axis, bMinBack = True _backMinArray = y_axis[backMin:peakMin, t] _backMinErrorArray = y_error_axis[backMin:peakMin, t] - [_backMin, _backMinError] = weightedMean(_backMinArray, + [_backMin, _backMinError] = weightedMean(_backMinArray,\ _backMinErrorArray, error_0) if (peakMax) < backMax: @@ -1361,9 +1361,9 @@ def ouput_big_ascii_file(file_name, -def ouput_big_Q_ascii_file(file_name, - x_axis, - y_axis, +def ouput_big_Q_ascii_file(file_name,\ + x_axis,\ + y_axis,\ y_error_axis): f=open(file_name,'w') @@ -1787,14 +1787,14 @@ def convertToQ(tof_axis, return [q_axis_reverse, _y_axis, _y_error_axis] -def convertToQWithoutCorrection(tof_axis, - y_axis, - y_error_axis, - peak_range = None, - source_to_detector_distance = None, - sample_to_detector_distance = None, - theta = None, - first_slit_size = None, +def convertToQWithoutCorrection(tof_axis,\ + y_axis,\ + y_error_axis,\ + peak_range = None,\ + source_to_detector_distance = None,\ + sample_to_detector_distance = None,\ + theta = None,\ + first_slit_size = None,\ last_slit_size = None): """ will convert the tof_axis into q_axis according to q range specified @@ -1927,10 +1927,10 @@ def createQworkspace(q_axis, y_axis, y_error_axis): y_axis_1d = y_axis.flatten() y_error_axis_1d = y_error_axis.flatten() - q_workspace = CreateWorkspace(DataX=q_axis_1d, - DataY=y_axis_1d, - DataE=y_error_axis_1d, - Nspec=nbr_pixel, + q_workspace = CreateWorkspace(DataX=q_axis_1d,\ + DataY=y_axis_1d,\ + DataE=y_error_axis_1d,\ + Nspec=nbr_pixel,\ UnitX="Wavelength") q_workspace.setDistribution(True) diff --git a/Code/Mantid/scripts/reduction/instruments/sans/sans_reducer.py b/Code/Mantid/scripts/reduction/instruments/sans/sans_reducer.py index 06af14e2fb0c..14ccf1aaa321 100644 --- a/Code/Mantid/scripts/reduction/instruments/sans/sans_reducer.py +++ b/Code/Mantid/scripts/reduction/instruments/sans/sans_reducer.py @@ -8,7 +8,6 @@ from reduction import validate_step import sans_reduction_steps import mantid.simpleapi as api -from mantid import simpleapi import warnings import inspect @@ -152,7 +151,8 @@ def set_mask(self, mask): """ self._mask = mask - def get_mask(self): return self._mask + def get_mask(self): + return self._mask def get_beam_center(self): """ @@ -186,7 +186,8 @@ def set_data_loader(self, loader): else: raise RuntimeError, "Reducer.set_data_loader expects an object of class ReductionStep" - def get_data_loader(self): return self._data_loader + def get_data_loader(self): + return self._data_loader @validate_step def set_sensitivity_correcter(self, correcter): @@ -259,7 +260,8 @@ def set_bck_transmission(self, trans): @param trans: ReductionStep object """ lineno = inspect.currentframe().f_code.co_firstlineno - warnings.warn_explicit("SANSReducer.set_bck_transmission id deprecated: use get_background().set_transmission()", DeprecationWarning, __file__, lineno) + warnings.warn_explicit("SANSReducer.set_bck_transmission id deprecated: use get_background().set_transmission()",\ + DeprecationWarning, __file__, lineno) if issubclass(trans.__class__, sans_reduction_steps.BaseTransmission) or trans is None: self._background_subtracter.set_transmission(trans) diff --git a/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py b/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py index f6bf12837a0a..8a767a6cae39 100644 --- a/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py +++ b/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py @@ -1,14 +1,11 @@ +#pylint: disable=invalid-name """ Implementation of reduction steps for SANS """ -import os -import sys import math import pickle from reduction import ReductionStep -from reduction import extract_workspace_name, find_data from reduction import validate_step -import warnings # Mantid imports import mantid @@ -56,10 +53,10 @@ def _find_beam(self, direct_beam, reducer, workspace=None): if self._beam_center_x is not None and self._beam_center_y is not None: return "Using Beam Center at: %g %g" % (self._beam_center_x, self._beam_center_y) - beam_x,beam_y,msg = SANSBeamFinder(Filename=self._datafile, - UseDirectBeamMethod=direct_beam, - BeamRadius=self._beam_radius, - PersistentCorrection=self._persistent, + beam_x,beam_y,msg = SANSBeamFinder(Filename=self._datafile,\ + UseDirectBeamMethod=direct_beam,\ + BeamRadius=self._beam_radius,\ + PersistentCorrection=self._persistent,\ ReductionProperties=reducer.get_reduction_table_name()) self._beam_center_x = beam_x diff --git a/Code/Mantid/scripts/reduction/reducer.py b/Code/Mantid/scripts/reduction/reducer.py index 71c901353107..a8c388058e45 100644 --- a/Code/Mantid/scripts/reduction/reducer.py +++ b/Code/Mantid/scripts/reduction/reducer.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Base reduction class. Hold a list of data and a list of reduction steps to apply to them. diff --git a/Code/Mantid/scripts/reduction_workflow/command_interface.py b/Code/Mantid/scripts/reduction_workflow/command_interface.py index 20306ab30c4a..3b18688874a0 100644 --- a/Code/Mantid/scripts/reduction_workflow/command_interface.py +++ b/Code/Mantid/scripts/reduction_workflow/command_interface.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ List of user commands. """ diff --git a/Code/Mantid/scripts/reduction_workflow/find_data.py b/Code/Mantid/scripts/reduction_workflow/find_data.py index e6701e647799..0ecd916bf341 100644 --- a/Code/Mantid/scripts/reduction_workflow/find_data.py +++ b/Code/Mantid/scripts/reduction_workflow/find_data.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import os from mantid.kernel import ConfigService, Logger from mantid.api import FileFinder diff --git a/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_command_interface.py b/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_command_interface.py index 75518979f283..b3ef207a81c9 100644 --- a/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_command_interface.py +++ b/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_command_interface.py @@ -1,12 +1,11 @@ +#pylint: disable=invalid-name """ List of common user commands for HFIR SANS """ from reduction_workflow.command_interface import * from reduction_workflow.find_data import * from reduction_workflow.instruments.sans import hfir_instrument -from mantid.api import AlgorithmManager from mantid.kernel import Logger -import mantid.simpleapi as simpleapi import os ## List of user commands ###################################################### @@ -236,9 +235,9 @@ def BckDirectBeamTransmission(sample_file, empty_file, beam_radius=3.0, theta_de ReductionSingleton().reduction_properties["BckTransmissionEmptyDataFile"] = empty_file ReductionSingleton().reduction_properties["BckThetaDependentTransmission"] = theta_dependent -def BckBeamSpreaderTransmission(sample_spreader, direct_spreader, - sample_scattering, direct_scattering, - spreader_transmission=1.0, spreader_transmission_err=0.0, +def BckBeamSpreaderTransmission(sample_spreader, direct_spreader,\ + sample_scattering, direct_scattering,\ + spreader_transmission=1.0, spreader_transmission_err=0.0,\ theta_dependent=True ): sample_spreader = find_data(sample_spreader, instrument=ReductionSingleton().get_instrument()) direct_spreader = find_data(direct_spreader, instrument=ReductionSingleton().get_instrument()) diff --git a/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_instrument.py b/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_instrument.py index aeb9d3dc9b83..f22af8ef87cf 100644 --- a/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_instrument.py +++ b/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_instrument.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import sys def get_default_beam_center(workspace=None): @@ -53,7 +54,7 @@ def get_masked_pixels(nx_low, nx_high, ny_low, ny_high, workspace): @param ny_high: number of pixels to mask on the higher-y side of the detector @param workspace: the pixel number and size info will be taken from the workspace """ - nx_pixels, ny_pixels, pixel_size_x, pixel_size_y = _get_pixel_info(workspace) + nx_pixels, ny_pixels, dummy_pixel_size_x, dummy_pixel_size_y = _get_pixel_info(workspace) if nx_low<0 or nx_high<0 or ny_low<0 or ny_high<0: raise RuntimeError, "Pixel edges should be greater than zero" diff --git a/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_command_interface.py b/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_command_interface.py index ccf511c21708..1911ed5c3943 100644 --- a/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_command_interface.py +++ b/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_command_interface.py @@ -1,38 +1,39 @@ +#pylint: disable=invalid-name """ Command set for EQSANS reduction """ # Import the specific commands that we need from reduction_workflow.command_interface import * -from hfir_command_interface import DarkCurrent, NoDarkCurrent, NoNormalization -from hfir_command_interface import SolidAngle, NoSolidAngle -from hfir_command_interface import DirectBeamCenter, ScatteringBeamCenter +#from hfir_command_interface import DarkCurrent, NoDarkCurrent, NoNormalization +from hfir_command_interface import SolidAngle#, NoSolidAngle +#from hfir_command_interface import DirectBeamCenter, ScatteringBeamCenter from hfir_command_interface import SetBeamCenter as BaseSetBeamCenter -from hfir_command_interface import SensitivityCorrection, SetSensitivityBeamCenter -from hfir_command_interface import SensitivityDirectBeamCenter, SensitivityScatteringBeamCenter -from hfir_command_interface import NoSensitivityCorrection, DivideByThickness +#from hfir_command_interface import SensitivityCorrection, SetSensitivityBeamCenter +#from hfir_command_interface import SensitivityDirectBeamCenter, SensitivityScatteringBeamCenter +#from hfir_command_interface import NoSensitivityCorrection, DivideByThickness -from hfir_command_interface import IQxQy, NoIQxQy, SaveIq, NoSaveIq, SaveIqAscii +#from hfir_command_interface import IQxQy, NoIQxQy, SaveIq, NoSaveIq, SaveIqAscii -from hfir_command_interface import DirectBeamTransmission, TransmissionDarkCurrent -from hfir_command_interface import ThetaDependentTransmission -from hfir_command_interface import SetTransmissionBeamCenter, TransmissionDirectBeamCenter -from hfir_command_interface import SetTransmission, NoTransmission +#from hfir_command_interface import DirectBeamTransmission, TransmissionDarkCurrent +#from hfir_command_interface import ThetaDependentTransmission +#from hfir_command_interface import SetTransmissionBeamCenter, TransmissionDirectBeamCenter +#from hfir_command_interface import SetTransmission, NoTransmission -from hfir_command_interface import Background, NoBackground, NoBckTransmission -from hfir_command_interface import SetBckTransmission, BckDirectBeamTransmission -from hfir_command_interface import SetBckTransmissionBeamCenter, BckThetaDependentTransmission -from hfir_command_interface import BckTransmissionDirectBeamCenter, BckTransmissionDarkCurrent +#from hfir_command_interface import Background, NoBackground, NoBckTransmission +#from hfir_command_interface import SetBckTransmission, BckDirectBeamTransmission +#from hfir_command_interface import SetBckTransmissionBeamCenter, BckThetaDependentTransmission +#from hfir_command_interface import BckTransmissionDirectBeamCenter, BckTransmissionDarkCurrent -from hfir_command_interface import SetSampleDetectorOffset, SetSampleDetectorDistance -from hfir_command_interface import Mask, MaskRectangle, MaskDetectors, MaskDetectorSide -from hfir_command_interface import SetAbsoluteScale, SetDirectBeamAbsoluteScale -from hfir_command_interface import Stitch +#from hfir_command_interface import SetSampleDetectorOffset, SetSampleDetectorDistance +#from hfir_command_interface import Mask, MaskRectangle, MaskDetectors, MaskDetectorSide +#from hfir_command_interface import SetAbsoluteScale, SetDirectBeamAbsoluteScale +#from hfir_command_interface import Stitch -from mantid.api import AlgorithmManager -from mantid.kernel import Logger -import mantid.simpleapi as simpleapi +#from mantid.api import AlgorithmManager +#from mantid.kernel import Logger +#import mantid.simpleapi as simpleapi from reduction_workflow.find_data import find_data def EQSANS(keep_events=False, property_manager=None): diff --git a/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_instrument.py b/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_instrument.py index 7536177cf452..3d26584fb37f 100644 --- a/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_instrument.py +++ b/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_instrument.py @@ -1,9 +1,9 @@ +#pylint: disable=invalid-name """ Instrument-specific utility functions for EQSANS """ -from hfir_instrument import get_default_beam_center, _get_pixel_info +from hfir_instrument import _get_pixel_info -import sys def get_pixel_from_coordinate(x, y, workspace): """ diff --git a/Code/Mantid/scripts/reduction_workflow/reducer.py b/Code/Mantid/scripts/reduction_workflow/reducer.py index 5b9a5ab4ba6f..d9cbdad20735 100644 --- a/Code/Mantid/scripts/reduction_workflow/reducer.py +++ b/Code/Mantid/scripts/reduction_workflow/reducer.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Base reduction class. Uses version 2 python API. """ @@ -6,10 +7,8 @@ import time import random import string -import mantid.simpleapi as simpleapi from mantid.api import AlgorithmManager, AnalysisDataService from mantid.kernel import ConfigService, Logger -from find_data import find_data class Reducer(object): """ From 27cea9acab820dc158c7408d741cf3b19866f0b4 Mon Sep 17 00:00:00 2001 From: Andrei Savici Date: Thu, 19 Feb 2015 21:12:20 -0500 Subject: [PATCH 319/414] Remove parentheses and fixed continuations. Refs #11134 --- .../plugins/algorithms/BASISReduction.py | 2 +- .../plugins/algorithms/BASISReduction311.py | 2 +- .../algorithms/CalculateSampleTransmission.py | 4 +- .../CalibrateRectangularDetectors.py | 4 +- .../plugins/algorithms/ConjoinSpectra.py | 12 +-- .../algorithms/CreateLeBailFitInput.py | 6 +- .../plugins/algorithms/DakotaChiSquared.py | 7 +- .../plugins/algorithms/EnginXFitPeaks.py | 2 +- .../algorithms/ExaminePowderDiffProfile.py | 84 ++++++++-------- .../GenerateGroupingSNSInelastic.py | 2 +- .../algorithms/LoadLogPropertyTable.py | 28 +++--- .../plugins/algorithms/MaskBTP.py | 40 ++++---- .../plugins/algorithms/MergeCalFiles.py | 8 +- .../plugins/algorithms/PoldiMerge.py | 2 +- .../plugins/algorithms/PoldiProjectAddDir.py | 6 +- .../plugins/algorithms/PoldiProjectAddFile.py | 4 +- .../plugins/algorithms/PoldiProjectRun.py | 8 +- .../plugins/algorithms/RefLReduction.py | 4 +- .../algorithms/RefinePowderDiffProfileSeq.py | 98 +++++++++---------- .../algorithms/SANSWideAngleCorrection.py | 2 +- .../plugins/algorithms/SNSPowderReduction.py | 6 +- .../plugins/algorithms/SuggestTibCNCS.py | 6 +- .../plugins/algorithms/USANSSimulation.py | 2 +- .../algorithms/WorkflowAlgorithms/CutMD.py | 2 +- .../EQSANSAzimuthalAverage1D.py | 1 - .../EQSANSDirectBeamTransmission.py | 1 - .../WorkflowAlgorithms/FuryFitMultiple.py | 2 +- .../OSIRISDiffractionReduction.py | 39 ++++---- .../WorkflowAlgorithms/REFLReprocess.py | 4 +- .../SANSBeamSpreaderTransmission.py | 1 - .../plugins/algorithms/sfCalculator.py | 43 ++++---- .../Examples/TubeCalibDemoMaps_All.py | 36 +++---- .../Examples/TubeCalibDemoMaps_B1.py | 3 +- .../Examples/TubeCalibDemoMerlin.py | 4 +- .../Examples/TubeCalibDemoWish_Simple.py | 5 +- Code/Mantid/scripts/Calibration/ideal_tube.py | 5 +- Code/Mantid/scripts/Calibration/tube_calib.py | 38 +++---- Code/Mantid/scripts/Calibration/tube_spec.py | 54 +++++----- .../Mantid/scripts/Engineering/EnginXUtils.py | 2 +- .../scripts/FilterEvents/eventFilterGUI.py | 51 +++++----- .../Direct/DirectEnergyConversion.py | 14 +-- .../Inelastic/Direct/NonIDF_Properties.py | 2 +- .../Inelastic/Direct/PropertiesDescriptors.py | 14 +-- .../Inelastic/Direct/PropertyManager.py | 18 ++-- .../Inelastic/Direct/ReductionHelpers.py | 10 +- .../scripts/Inelastic/Direct/RunDescriptor.py | 6 +- .../scripts/Inelastic/Direct/dgreduce.py | 5 +- .../scripts/Inelastic/IndirectAbsCor.py | 8 +- .../Mantid/scripts/Inelastic/IndirectBayes.py | 28 +++--- .../scripts/Inelastic/IndirectCommon.py | 4 +- .../scripts/Inelastic/IndirectDataAnalysis.py | 2 +- .../Inelastic/IndirectEnergyConversion.py | 6 +- .../scripts/Inelastic/IndirectMuscat.py | 16 +-- .../scripts/Inelastic/IndirectNeutron.py | 14 +-- .../Inelastic/inelastic_indirect_reducer.py | 2 +- .../inelastic_indirect_reduction_steps.py | 44 ++++----- Code/Mantid/scripts/Inelastic/msg_reducer.py | 4 +- .../reflectometer/refl_data_script.py | 6 +- .../reduction/sans/hfir_options_script.py | 2 +- .../diffraction/diffraction_filter_setup.py | 2 +- .../widgets/inelastic/dgs_absolute_units.py | 23 +++-- .../inelastic/dgs_diagnose_detectors.py | 23 +++-- .../widgets/reflectometer/LoadSNSRoi.py | 2 +- .../reflectometer/base_ref_reduction.py | 38 ++++--- .../launch_peak_back_selection_1d.py | 6 +- .../widgets/reflectometer/refl_data_simple.py | 4 +- .../reflectometer/refl_sf_calculator.py | 6 +- .../widgets/reflectometer/refm_reduction.py | 4 +- .../Interface/reduction_gui/widgets/util.py | 2 +- .../Interface/ui/reflectometer/refl_gui.py | 46 ++++----- .../ui/reflectometer/refl_options.py | 2 +- .../Interface/ui/reflectometer/refl_save.py | 26 ++--- .../LargeScaleStructures/geometry_writer.py | 4 +- Code/Mantid/scripts/PyChop/PyChop.py | 12 +-- Code/Mantid/scripts/PyChop/fluxGUI.py | 2 - .../convert_to_wavelength.py | 2 +- .../isis_reflectometry/load_live_runs.py | 2 +- .../isis_reflectometry/procedures.py | 54 +++++----- .../Reflectometry/isis_reflectometry/quick.py | 18 ++-- .../scripts/SANS/ISISCommandInterface.py | 26 ++--- Code/Mantid/scripts/SANS/SANSUtility.py | 4 +- Code/Mantid/scripts/SANS/SANSadd2.py | 8 +- Code/Mantid/scripts/SANS/isis_instrument.py | 12 +-- Code/Mantid/scripts/SANS/isis_reducer.py | 6 +- .../scripts/SANS/isis_reduction_steps.py | 22 ++--- .../scripts/SCD_Reduction/ReduceSCD_OneRun.py | 6 +- .../SCD_Reduction/ReduceSCD_Parallel.py | 4 +- .../reflectometer/data_manipulation.py | 2 +- .../instruments/reflectometer/wks_utility.py | 46 ++++----- .../instruments/sans/sans_reduction_steps.py | 6 +- 90 files changed, 619 insertions(+), 636 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py index 17ad01df8e7c..ee9de2e8d78c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py @@ -60,7 +60,7 @@ def PyExec(self): self._groupDetOpt = self.getProperty("GroupDetectors").value datasearch = config["datasearch.searcharchive"] - if (datasearch != "On"): + if datasearch != "On": config["datasearch.searcharchive"] = "On" # Handle masking file override if necessary diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py index 63c8e0f525da..f0768df7473f 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py @@ -63,7 +63,7 @@ def PyExec(self): self._groupDetOpt = self.getProperty("GroupDetectors").value datasearch = config["datasearch.searcharchive"] - if (datasearch != "On"): + if datasearch != "On": config["datasearch.searcharchive"] = "On" # Handle masking file override if necessary diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py index 3621eb7fa21e..8da0ac465e18 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py @@ -37,11 +37,11 @@ def validateInputs(self): issues = dict() density = self.getProperty('NumberDensity').value - if(density < 0.0): + if density < 0.0: issues['NumberDensity'] = 'NumberDensity must be positive' thickness = self.getProperty('Thickness').value - if(thickness < 0.0): + if thickness < 0.0: issues['Thickness'] = 'Thickness must be positive' return issues diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py index c30f020a18b1..d641f58596fb 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py @@ -149,7 +149,7 @@ def _loadPreNeXusData(self, runnumber, extension, **kwargs): wksp = LoadPreNexus(Filename=filename, OutputWorkspace=name, **mykwargs) # add the logs to it - if (str(self._instrument) == "SNAP"): + if str(self._instrument) == "SNAP": LoadInstrument(Workspace=wksp, InstrumentName=self._instrument, RewriteSpectraMap=False) return wksp @@ -516,7 +516,7 @@ def PyExec(self): for (samNum, backNum) in zip(samRuns, backRuns): # first round of processing the sample samRun = self._loadData(samNum, SUFFIX, filterWall) - if (backNum > 0): + if backNum > 0: backRun = self._loadData(backNum, SUFFIX, filterWall) samRun -= backRun DeleteWorkspace(backRun) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py index 0213ee542467..1980cb4f440d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py @@ -62,9 +62,9 @@ def PyExec(self): ExtractSingleSpectrum(InputWorkspace=wsName,OutputWorkspace=wsTemp,WorkspaceIndex=wsIndex) labelString ="" - if (labelUsing != ""): + if labelUsing != "": labelString = self.GetLogValue(mtd[wsName.strip()],labelUsing,labelValue) - if (labelString == ""): + if labelString == "": labelString =wsName+"_"+str(wsIndex) ta.setLabel(loopIndex,labelString) loopIndex += 1 @@ -89,13 +89,13 @@ def GetLogValue(self,ws,labelUsing,labelValue): prop = run.getProperty(labelUsing) try: stats = prop.getStatistics() - if (labelValue == "Mean"): + if labelValue == "Mean": labelString = str(stats.mean) - elif (labelValue == "Median"): + elif labelValue == "Median": labelString = str(stats.median) - elif (labelValue == "Maximum"): + elif labelValue == "Maximum": labelString = str(stats.maximum) - elif (labelValue == "Minimum"): + elif labelValue == "Minimum": labelString = str(stats.minimum) else: labelString = str(prop.value[0]) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py index d86dce9610f8..780b8e1a355d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py @@ -113,9 +113,9 @@ def importFullProfHKLFile(self, hklfilename, hklwsname): # api.DeleteWorkspace(Workspace=dummyws) # api.DeleteWorkspace(Workspace="TempXXX") - api.LoadFullprofFile( - Filename=hklfilename, - PeakParameterWorkspace = hklwsname, + api.LoadFullprofFile(\ + Filename=hklfilename,\ + PeakParameterWorkspace = hklwsname,\ OutputWorkspace = dummywsname) hklws = AnalysisDataService.retrieve(hklwsname) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py index b50f41e1db4e..f097ed09e653 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py @@ -31,7 +31,8 @@ def PyInit(self): fout=mantid.api.FileProperty("OutputFile","",mantid.api.FileAction.Save,".xml") self.declareProperty(fout,"Output filename containing chi^2.") self.declareProperty("ChiSquared",0.0,Direction.Output) - self.declareProperty(MatrixWorkspaceProperty("ResidualsWorkspace", "",Direction.Output,PropertyMode.Optional), "The name of the workspace that will contain residuals.") + self.declareProperty(MatrixWorkspaceProperty("ResidualsWorkspace", "",Direction.Output,PropertyMode.Optional),\ + "The name of the workspace that will contain residuals.") return def PyExec(self): @@ -59,7 +60,7 @@ def PyExec(self): #calculate chi^2 soeName = self.getPropertyValue("ResidualsWorkspace") - if (len(soeName)>0): + if len(soeName)>0: mantid.simpleapi.SignalOverError(__w1-__w2,OutputWorkspace=soeName) self.setProperty("ResidualsWorkspace",soeName) __soe=mantid.mtd[soeName] @@ -83,7 +84,7 @@ def PyExec(self): mantid.simpleapi.DeleteWorkspace(__w1.getName()) mantid.simpleapi.DeleteWorkspace(__w2.getName()) mantid.simpleapi.DeleteWorkspace(__soe2.getName()) - if (len(soeName)==0): + if len(soeName)==0: mantid.simpleapi.DeleteWorkspace(__soe.getName()) AlgorithmFactory.subscribe(DakotaChiSquared) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py index 96c1ae6844d1..5c75e97626e3 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py @@ -49,7 +49,7 @@ def PyExec(self): findPeaksAlg.execute() foundPeaks = findPeaksAlg.getProperty('PeaksList').value - if (foundPeaks.rowCount() < len(expectedPeaksTof)): + if foundPeaks.rowCount() < len(expectedPeaksTof): raise Exception("Some peaks were not found") fittedPeaks = self._createFittedPeaksTable() diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py index 856b430c91c7..fde9c27489df 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py @@ -134,10 +134,10 @@ def mainExec(self): # Load data optionally if self.loaddata is True: # Load data file - api.LoadAscii( - Filename = self.datafilename, - OutputWorkspace = self.datawsname, - Unit = 'TOF' + api.LoadAscii(\ + Filename = self.datafilename,\ + OutputWorkspace = self.datawsname,\ + Unit = 'TOF'\ ) # Load .irf file and .hkl file optionally @@ -145,60 +145,60 @@ def mainExec(self): if dir(self).count('latticesize') == 0 or self.latticesize is None: raise NotImplementedError("Lattice size is not defined. Unable to use option 'LoadInfo'") - api.CreateLeBailFitInput( - FullprofParameterFile = self.irffilename, - MaxHKL = [13, 13, 13], - LatticeConstant = float(self.latticesize), - Bank = self.bankid, - GenerateBraggReflections = True, - InstrumentParameterWorkspace = str(self.inputparamws), - BraggPeakParameterWorkspace = str(self.inputbraggws) + api.CreateLeBailFitInput(\ + FullprofParameterFile = self.irffilename,\ + MaxHKL = [13, 13, 13],\ + LatticeConstant = float(self.latticesize),\ + Bank = self.bankid,\ + GenerateBraggReflections = True,\ + InstrumentParameterWorkspace = str(self.inputparamws),\ + BraggPeakParameterWorkspace = str(self.inputbraggws)\ ) # Process background optionally if self.process_bkgd is True: # [Background] # Remove peaks and get pure background (hopefully) - api.ProcessBackground( - Options = 'SelectBackgroundPoints', - InputWorkspace = self.dataws, - OutputWorkspace = self.bkgdwsname, - LowerBound = self.startx, - UpperBound = self.endx, - BackgroundType = self.backgroundtype, - BackgroundPoints= self.usrbkgdpoints, + api.ProcessBackground(\ + Options = 'SelectBackgroundPoints',\ + InputWorkspace = self.dataws,\ + OutputWorkspace = self.bkgdwsname,\ + LowerBound = self.startx,\ + UpperBound = self.endx,\ + BackgroundType = self.backgroundtype,\ + BackgroundPoints= self.usrbkgdpoints,\ NoiseTolerance = '0.10000000000000001') # Fit background points functionstr = "name=%s,n=%d" % (self.backgroundtype, self.backgroundorder) for iborder in xrange(self.backgroundorder+1): functionstr = "%s,A%d=%.5f" % (functionstr, iborder, 0.0) - api.Fit( - Function = functionstr, - InputWorkspace = self.bkgdwsname, - Output = self.bkgdwsname, - MaxIterations = '1000', - Minimizer = 'Levenberg-MarquardtMD', - CreateOutput = '1', - StartX = self.startx, + api.Fit(\ + Function = functionstr,\ + InputWorkspace = self.bkgdwsname,\ + Output = self.bkgdwsname,\ + MaxIterations = '1000',\ + Minimizer = 'Levenberg-MarquardtMD',\ + CreateOutput = '1',\ + StartX = self.startx,\ EndX = self.endx) # [Le Bail calculation] self.log().debug("Fit range: %f , %f, Outputworkspace = %s" % (self.startx, self.endx, self.outwsname)) - api.LeBailFit( - Function = 'Calculation', - InputWorkspace = self.dataws, - OutputWorkspace = self.outwsname, - InputParameterWorkspace = self.inputparamws, - OutputParameterWorkspace= str(self.inputparamws), - InputHKLWorkspace = self.inputbraggws, - OutputPeaksWorkspace = str(self.inputbraggws), - FitRegion = '%f, %f' % (self.startx, self.endx), - BackgroundType = self.backgroundtype, - UseInputPeakHeights = False, - PeakRadius = '7', - BackgroundParametersWorkspace = self.bkgdtablews, - PeakType = self.profiletype, + api.LeBailFit(\ + Function = 'Calculation',\ + InputWorkspace = self.dataws,\ + OutputWorkspace = self.outwsname,\ + InputParameterWorkspace = self.inputparamws,\ + OutputParameterWorkspace= str(self.inputparamws),\ + InputHKLWorkspace = self.inputbraggws,\ + OutputPeaksWorkspace = str(self.inputbraggws),\ + FitRegion = '%f, %f' % (self.startx, self.endx),\ + BackgroundType = self.backgroundtype,\ + UseInputPeakHeights = False,\ + PeakRadius = '7',\ + BackgroundParametersWorkspace = self.bkgdtablews,\ + PeakType = self.profiletype,\ ) return diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py index 890767754914..c01f61cbfe01 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py @@ -55,7 +55,7 @@ def PyExec(self): __w = mantid.simpleapi.LoadEmptyInstrument(Filename=IDF) i=0 - while(__w.getDetector(i).isMonitor()): + while __w.getDetector(i).isMonitor(): i += 1 #i is the index of the first true detector #now, crop the workspace of the monitors diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py index a5b924fcc228..0184eefad649 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py @@ -37,7 +37,7 @@ def getGeneralLogValue(self,ws,name,begin): # get log value # average time series over run # for beamlog, etc return flag=true and value to push into previous run - if(name=="comment"): + if name=="comment": return (ws.getComment(),False,0) try: @@ -49,7 +49,7 @@ def getGeneralLogValue(self,ws,name,begin): raise ValueError(message) try: times2=[] - if (hasattr(v,"unfiltered")): + if hasattr(v,"unfiltered"): v=v.unfiltered() for tt in v.times: times2.append((datetime.datetime(*(time.strptime(str(tt),"%Y-%m-%dT%H:%M:%S")[0:6]))-begin).total_seconds()) @@ -57,11 +57,11 @@ def getGeneralLogValue(self,ws,name,begin): #print "probably not a time series" pass - if(name[0:8]=="Beamlog_" and (name.find("Counts")>0 or name.find("Frames")>0)): + if name[0:8]=="Beamlog_" and (name.find("Counts")>0 or name.find("Frames")>0): i=bisect.bisect_right(times2,2) # allowance for "slow" clearing of DAE #print "returning max beam log, list cut 0:",i,":",len(times2) return (numpy.amax(v.value[i:]),True,numpy.amax(v.value[:i])) - if(v.__class__.__name__ =="TimeSeriesProperty_dbl" or v.__class__.__name__ =="FloatTimeSeriesProperty"): + if v.__class__.__name__ =="TimeSeriesProperty_dbl" or v.__class__.__name__ =="FloatTimeSeriesProperty": i=bisect.bisect_left(times2,0) return (numpy.average(v.value[i:]),False,0) return (v.value,False,0) @@ -80,13 +80,13 @@ def PyExec(self): while file9[j9-1].isdigit(): j9=j9-1 lastnum=int(file9[j9:i9]) - if(file1[:j9] != file9[:j9]): + if file1[:j9] != file9[:j9]: raise Exception("Files from different directories or instruments") - if(file1[i1:] != file9[i9:]): + if file1[i1:] != file9[i9:]: raise Exception("Files of different types") - if(i1-j1 != i9-j9): + if i1-j1 != i9-j9: raise Exception("File numbering error") - if(lastnum < firstnum): + if lastnum < firstnum: raise Exception("Run numbers must increase") # table. Rows=runs, columns=logs (col 0 = run number) @@ -104,14 +104,14 @@ def PyExec(self): continue #check if the return type is atuple - if (type(returnTuple) == tuple): + if type(returnTuple) == tuple: loadedWs=returnTuple[0] else: loadedWs = returnTuple #check if the ws is a group ws = loadedWs - if (ws.id() == 'WorkspaceGroup'): + if ws.id() == 'WorkspaceGroup': ws=ws[0] begin=datetime.datetime(*(time.strptime(ws.getRun().getProperty("run_start").value,"%Y-%m-%dT%H:%M:%S")[0:6])) # start of day @@ -124,13 +124,13 @@ def PyExec(self): DeleteWorkspace(loadedWs) raise vallist.append(cv) - if(ff==firstnum): - if(isinstance(cv, numbers.Number)): + if ff==firstnum: + if isinstance(cv, numbers.Number): ows.addColumn("double",cc) else: ows.addColumn("str",cc) - if(leftover and ff>firstnum): - if(lval>ows.cell(cc,ff-firstnum-1)): + if leftover and ff>firstnum: + if lval>ows.cell(cc,ff-firstnum-1): ows.setCell(cc,ff-firstnum-1,lval) ows.addRow(vallist) DeleteWorkspace(loadedWs) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py index fb9ced964035..75d0f4a119d1 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py @@ -61,28 +61,28 @@ def PyExec(self): except: raise ValueError("Instrument "+self.instname+" not in the allowed list") - if (self.instrument==None): + if self.instrument==None: IDF=mantid.api.ExperimentInfo.getInstrumentFilename(self.instname) if mantid.mtd.doesExist(self.instname+"MaskBTP"): mantid.simpleapi.DeleteWorkspace(self.instname+"MaskBTP") ws=mantid.simpleapi.LoadEmptyInstrument(IDF,OutputWorkspace=self.instname+"MaskBTP") self.instrument=ws.getInstrument() - if (bankString == ""): + if bankString == "": banks=numpy.arange(self.bankmax[self.instname]-self.bankmin[self.instname]+1)+self.bankmin[self.instname] else: banks=self._parseBTPlist(bankString) - if (tubeString == ""): + if tubeString == "": tubes=numpy.arange(tubemax[self.instname]-tubemin[self.instname]+1)+tubemin[self.instname] - elif (tubeString == "edges"): + elif tubeString == "edges": tubes=[tubemin[self.instname],tubemax[self.instname]] else: tubes=self._parseBTPlist(tubeString) - if(pixelString == ""): + if pixelString == "": pixels=numpy.arange(pixmax[self.instname]-pixmin[self.instname]+1)+pixmin[self.instname] - elif (pixelString == "edges"): + elif pixelString == "edges": pixels=[pixmin[self.instname],pixmax[self.instname]] else: pixels=self._parseBTPlist(pixelString) @@ -94,11 +94,11 @@ def PyExec(self): ep=self._getEightPackHandle(b) if ep!=None: for t in tubes: - if ((ttubemax[self.instname])): + if (ttubemax[self.instname]): raise ValueError("Out of range index for tube number") else: for p in pixels: - if ((ppixmax[self.instname])): + if (ppixmax[self.instname]): raise ValueError("Out of range index for pixel number") else: try: @@ -143,39 +143,39 @@ def _getEightPackHandle(self,banknum): """ banknum=int(banknum) if self.instname=="ARCS": - if (self.bankmin[self.instname]<=banknum<= 38): + if self.bankmin[self.instname]<=banknum<= 38: return self.instrument.getComponentByName("B row")[banknum-1][0] - elif(39<=banknum<= 77): + elif 39<=banknum<= 77: return self.instrument.getComponentByName("M row")[banknum-39][0] - elif(78<=banknum<=self.bankmax[self.instname]): + elif 78<=banknum<=self.bankmax[self.instname]: return self.instrument.getComponentByName("T row")[banknum-78][0] else: raise ValueError("Out of range index for ARCS instrument bank numbers") elif self.instname=="CORELLI": - if (self.bankmin[self.instname]<=banknum<= 29): + if self.bankmin[self.instname]<=banknum<= 29: return self.instrument.getComponentByName("A row")[banknum-1][0] - elif(30<=banknum<=62): + elif 30<=banknum<=62: return self.instrument.getComponentByName("B row")[banknum-30][0] - elif(63<=banknum<=self.bankmax[self.instname]): + elif 63<=banknum<=self.bankmax[self.instname]: return self.instrument.getComponentByName("C row")[banknum-63][0] else: raise ValueError("Out of range index for CORELLI instrument bank numbers") elif self.instname=="SEQUOIA": - if (self.bankmin[self.instname]<=banknum<= 74): + if self.bankmin[self.instname]<=banknum<= 74: return self.instrument.getComponentByName("B row")[banknum-38][0] - elif(75<=banknum<= 113): + elif 75<=banknum<= 113: return self.instrument.getComponentByName("C row")[banknum-75][0] - elif(114<=banknum<=self.bankmax[self.instname]): + elif 114<=banknum<=self.bankmax[self.instname]: return self.instrument.getComponentByName("D row")[banknum-114][0] else: raise ValueError("Out of range index for SEQUOIA instrument bank numbers") elif self.instname=="CNCS" or self.instname=="HYSPEC": - if (self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]): + if self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]: return self.instrument.getComponentByName("bank"+str(banknum))[0] else: raise ValueError("Out of range index for "+str(self.instname)+" instrument bank numbers") elif self.instname=="WISH": - if (self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]): + if self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]: try: return self.instrument.getComponentByName("panel"+"%02d" % banknum)[0] except: @@ -183,7 +183,7 @@ def _getEightPackHandle(self,banknum): else: raise ValueError("Out of range index for "+str(self.instname)+" instrument bank numbers") else: - if (self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]): + if self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]: return self.instrument.getComponentByName("bank"+str(banknum)) else: raise ValueError("Out of range index for "+str(self.instname)+" instrument bank numbers") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py index aefeec5a8ba2..03a92e3885cf 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py @@ -32,7 +32,7 @@ def PyExec(self): outputFileName = self.getPropertyValue("OutputFile") - if (masterFileName == outputFileName) : + if masterFileName == outputFileName : raise RuntimeError('The output file must be different to the master file.') self.DisplayMessage(mergeOffsets,mergeSelections,mergeGroups,updateFileName,masterFileName) @@ -102,11 +102,11 @@ def PyExec(self): def DisplayMessage(self,mergeOffsets,mergeSelections,mergeGroups,fileName1,fileName2): #Log the settings string outputString = "Merging " - if (mergeOffsets): + if mergeOffsets: outputString+= "offsets, " - if (mergeSelections): + if mergeSelections: outputString+= "selections, " - if (mergeGroups): + if mergeGroups: outputString+= "groups, " #strip the final comma outputString = outputString [0:len(outputString)-2] diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py index 10aa59a5b53e..c85c7c2795d4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py @@ -103,7 +103,7 @@ def instrumentsMatch(self, leftWorkspace, rightWorkspace): return (not self.checkInstruments) or self.instrumentParametersMatch(leftInstrument, rightInstrument) def instrumentParametersMatch(self, leftInstrument, rightInstrument): - if not (leftInstrument.getDetector(0).getPos() == rightInstrument.getDetector(0).getPos()): + if not leftInstrument.getDetector(0).getPos() == rightInstrument.getDetector(0).getPos(): raise RuntimeError("Detector positions are not equal") for parameterTuple in self.comparedInstrumentParameters: diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py index 515631e1685e..5e17cbbf85a8 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py @@ -69,7 +69,7 @@ def PyExec(self): try: sample_info_ws_name = self.getProperty("PoldiAnalysis").value - if(sample_info_ws_name == ""): + if sample_info_ws_name == "": sample_info_ws_name = "PoldiAnalysis" self.log().debug('Poldi Data Analysis ---- %s'%(sample_info_ws_name)) sample_info_ws = mtd["PoldiAnalysis"] @@ -108,7 +108,7 @@ def PyExec(self): - if("hdf" in sampleExt): + if "hdf" in sampleExt: self.log().error('Poldi - samples : %s' %(sample_name)) file_path = join(directory,dataFile) sample_name_log = "%sLog" %sample_name @@ -128,7 +128,7 @@ def PyExec(self): - if(load_data_at_the_end): + if load_data_at_the_end: self.setProperty("PoldiAnalysis", sample_info_ws) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py index 5559c8cd5ef3..5236eaadf166 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py @@ -57,7 +57,7 @@ def PyExec(self): try: sample_info_ws_name = self.getProperty("OutputWorkspace").valueAsStr - if(sample_info_ws_name == ""): + if sample_info_ws_name == "": sample_info_ws_name = "PoldiAnalysis" self.log().debug('Poldi Data Analysis ---- %s'%(sample_info_ws_name)) sample_info_ws = mtd[sample_info_ws_name] @@ -83,7 +83,7 @@ def PyExec(self): self.log().error('Poldi - : %s' %(sample_name)) self.log().error('Poldi - : %s' %(sampleExt)) - if("hdf" in sampleExt): + if "hdf" in sampleExt: self.log().error('Poldi - samples : %s' %(sample_name)) file_path = dataFile sample_name_log = "%sLog" %sample_name diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py index 5d090b0e2b30..50d42c59855c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py @@ -77,7 +77,7 @@ def PyExec(self): load_data_at_the_end = False try: sample_ipp_ws_name = self.getProperty("OutputWorkspace").value - if(sample_ipp_ws_name == ""): + if sample_ipp_ws_name == "": sample_ipp_ws_name = "PoldiIPPmanager" self.log().debug('Poldi IPP manager ---- %s'%(sample_info_ws_name)) sample_ipp_ws = mtd["PoldiIPPmanager"] @@ -142,9 +142,9 @@ def PyExec(self): add_this_ipp = True for ipp in range(sample_ipp_ws.rowCount()): - if(sample_ipp_ws.column("ipp version")[ipp] == ipp_version): + if sample_ipp_ws.column("ipp version")[ipp] == ipp_version: add_this_ipp = False - if(add_this_ipp): + if add_this_ipp: sample_ipp_ws.addRow([sampleName, ipp_version]) @@ -195,7 +195,7 @@ def PyExec(self): RenameWorkspace(InputWorkspace=groupedResults, OutputWorkspace="%s_Metadata" % sampleName) - if(load_data_at_the_end): + if load_data_at_the_end: self.setProperty("OutputWorkspace", sample_ipp_ws) AlgorithmFactory.subscribe(PoldiProjectRun) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py index e4dff3b3c1de..c20e85d085bd 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py @@ -125,7 +125,7 @@ def PyExec(self): #GENERAL TOFrangeFlag = self.getProperty("TofRangeFlag") - if (TOFrangeFlag): + if TOFrangeFlag: TOFrange = self.getProperty("TOFRange").value #microS else: TOFrange = [0, 200000] @@ -138,7 +138,7 @@ def PyExec(self): qMin = self.getProperty("QMin").value qStep = self.getProperty("QStep").value - if (qStep > 0): #force logarithmic binning + if qStep > 0: #force logarithmic binning qStep = -qStep # angle offset diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py index 54a5880695c3..b2bb76c6dad0 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py @@ -783,20 +783,20 @@ def calculate(self, startx, endx): self.glog.information("**** Profile workspace = %s, Reflection workspace = %s" % ( self.inprofilewsname, self.inreflectionwsname)) - api.LeBailFit( - Function = 'Calculation', - InputWorkspace = self.datawsname, - OutputWorkspace = self.outwsname, - InputParameterWorkspace = self.inprofilewsname, - OutputParameterWorkspace= self.outprofilewsname, - InputHKLWorkspace = self.inreflectionwsname, - OutputPeaksWorkspace = self.outreflectionwsname, - FitRegion = '%f, %f' % (startx, endx), - PeakType = self.peaktype, - BackgroundType = self.bkgdtype, - UseInputPeakHeights = False, - PeakRadius = '8', - BackgroundParametersWorkspace = self.bkgdtablewsname + api.LeBailFit(\ + Function = 'Calculation',\ + InputWorkspace = self.datawsname,\ + OutputWorkspace = self.outwsname,\ + InputParameterWorkspace = self.inprofilewsname,\ + OutputParameterWorkspace= self.outprofilewsname,\ + InputHKLWorkspace = self.inreflectionwsname,\ + OutputPeaksWorkspace = self.outreflectionwsname,\ + FitRegion = '%f, %f' % (startx, endx),\ + PeakType = self.peaktype,\ + BackgroundType = self.bkgdtype,\ + UseInputPeakHeights = False,\ + PeakRadius = '8',\ + BackgroundParametersWorkspace = self.bkgdtablewsname\ ) return @@ -820,29 +820,29 @@ def refine(self, numsteps, parameternames, startx, endx): # UpdatePeakParameterTableValue(). It is not a real new table workspace, but a link # to the 'inprofilewsname' # There must be something wrong in AnalysisDataService. - api.UpdatePeakParameterTableValue( - InputWorkspace = self.inprofilewsname, - Column = "FitOrTie", + api.UpdatePeakParameterTableValue(\ + InputWorkspace = self.inprofilewsname,\ + Column = "FitOrTie",\ NewStringValue = "tie") - api.UpdatePeakParameterTableValue( - InputWorkspace = self.inprofilewsname, - Column = "FitOrTie", - ParameterNames = parameternames, + api.UpdatePeakParameterTableValue(\ + InputWorkspace = self.inprofilewsname,\ + Column = "FitOrTie",\ + ParameterNames = parameternames,\ NewStringValue = "fit") # Limit the range of MC if parameternames.count("Width") > 0: #self.cwl = 1.33 - UpdatePeakParameterTableValue( - InputWorkspace = self.inprofilewsname, - Column = "Min", - ParameterNames = ["Width"], + UpdatePeakParameterTableValue(\ + InputWorkspace = self.inprofilewsname,\ + Column = "Min",\ + ParameterNames = ["Width"],\ NewFloatValue = 0.50) #cwl*0.25) - UpdatePeakParameterTableValue( - InputWorkspace = self.inprofilewsname, - Column = "Max", - ParameterNames = ["Width"], + UpdatePeakParameterTableValue(\ + InputWorkspace = self.inprofilewsname,\ + Column = "Max",\ + ParameterNames = ["Width"],\ NewFloatValue = 1.25) #cwl*4.0) # Generate Monte carlo table @@ -854,26 +854,26 @@ def refine(self, numsteps, parameternames, startx, endx): else: raise NotImplementedError("Peak type %s is not supported to set up MC table." % (self.peaktype)) - api.LeBailFit( - InputWorkspace = self.datawsname, - OutputWorkspace = self.outwsname, - InputParameterWorkspace = self.inprofilewsname, - OutputParameterWorkspace = self.outprofilewsname, - InputHKLWorkspace = self.inreflectionwsname, - OutputPeaksWorkspace = self.outreflectionwsname, - FitRegion = '%f, %f' % (startx, endx), - Function = 'MonteCarlo', - NumberMinimizeSteps = numsteps, - PeakType = self.peaktype, - BackgroundType = self.bkgdtype, - BackgroundParametersWorkspace = self.bkgdtablewsname, - UseInputPeakHeights = False, - PeakRadius ='8', - Minimizer = 'Levenberg-Marquardt', - MCSetupWorkspace = str(wsname), - Damping = '5.0', - RandomSeed = 0, - AnnealingTemperature = 100.0, + api.LeBailFit(\ + InputWorkspace = self.datawsname,\ + OutputWorkspace = self.outwsname,\ + InputParameterWorkspace = self.inprofilewsname,\ + OutputParameterWorkspace = self.outprofilewsname,\ + InputHKLWorkspace = self.inreflectionwsname,\ + OutputPeaksWorkspace = self.outreflectionwsname,\ + FitRegion = '%f, %f' % (startx, endx),\ + Function = 'MonteCarlo',\ + NumberMinimizeSteps = numsteps,\ + PeakType = self.peaktype,\ + BackgroundType = self.bkgdtype,\ + BackgroundParametersWorkspace = self.bkgdtablewsname,\ + UseInputPeakHeights = False,\ + PeakRadius ='8',\ + Minimizer = 'Levenberg-Marquardt',\ + MCSetupWorkspace = str(wsname),\ + Damping = '5.0',\ + RandomSeed = 0,\ + AnnealingTemperature = 100.0,\ DrunkenWalk = True) # ENDIF (step) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py index faf8e2681369..eb63a744ec1d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py @@ -33,7 +33,7 @@ def PyExec(self): trans = self.getProperty("TransmissionData").value # check transmission input workspace - if (len(trans.dataX(0)) != len(wd.dataX(0))): + if len(trans.dataX(0)) != len(wd.dataX(0)): raise RuntimeError("Uncompatible sizes. Transmission must have the same bins of sample values") if min(trans.dataY(0)) < 0: raise RuntimeError("Invalid workspace for transmission, it does not accept negative values.") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py index 60b3fa2c264a..305f27c46000 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py @@ -296,7 +296,7 @@ def PyExec(self): canFilterWall = timeFilterWall else: canFilterWall = (0., 0.) - if ("%s_%d" % (self._instrument, canRun)) in mtd: + if "%s_%d" % (self._instrument, canRun) in mtd: canRun = mtd["%s_%d" % (self._instrument, canRun)] else: canRun = self._focusChunks(canRun, SUFFIX, canFilterWall, calib,\ @@ -319,7 +319,7 @@ def PyExec(self): vanFilterWall = timeFilterWall else: vanFilterWall = (0., 0.) - if ("%s_%d" % (self._instrument, vanRun)) in mtd: + if "%s_%d" % (self._instrument, vanRun) in mtd: vanRun = mtd["%s_%d" % (self._instrument, vanRun)] vanRun = api.ConvertUnits(InputWorkspace=vanRun, OutputWorkspace=vanRun, Target="TOF") else: @@ -505,7 +505,7 @@ def _loadData(self, runnumber, extension, filterWall=None, outname=None, **chunk if isEventWS is True: # Event workspace - self.log().information("FilterBadPulses reduces number of events from %d to %d (under %s percent) of workspace %s." % ( + self.log().information("FilterBadPulses reduces number of events from %d to %d (under %s percent) of workspace %s." % (\ numeventsbefore, wksp.getNumberEvents(), str(self._filterBadPulses), str(wksp))) return wksp diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py index acee867295a5..b7e025ec22cb 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py @@ -11,11 +11,11 @@ def __init__(self,minv,maxv): self.min=minv self.max=maxv def overlap(self, other): - if (other.max >self.min and other.max self.min and other.max self.min and other.minself.min and other.minself.max): + if other.minself.max: return True return False diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/USANSSimulation.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/USANSSimulation.py index 14bd8682f2e1..dab3299894d9 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/USANSSimulation.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/USANSSimulation.py @@ -141,7 +141,7 @@ def _sphere_model(self, q, scale): bes = 3.0*(math.sin(qr)-qr*math.cos(qr))/(qr*qr*qr) if not qr == 0.0 else 1.0 vol = 4.0*math.pi/3.0*radius*radius*radius f2 = vol*bes*bes*1.0e-6 - return(scale*f2+bck) + return scale*f2+bck ############################################################################################# AlgorithmFactory.subscribe(USANSSimulation()) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py index 5ae861013969..da015d751386 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py @@ -241,7 +241,7 @@ def PyExec(self): extents, bins = self.__calculate_steps( extents, ( p1_bins, p2_bins, p3_bins ) ) if not p4_bins_property.isDefault: - if (ndims == 4): + if ndims == 4: n_args = len(p4_bins) min, max = self.__extents_in_current_projection(to_cut, 3) d_range = max - min diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py index 7ad7e03b6a55..6fe0dcb95ec4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py @@ -1,7 +1,6 @@ #pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * -from mantid.simpleapi import Scale import math class EQSANSAzimuthalAverage1D(PythonAlgorithm): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py index c2111ba25e62..31b11d3eaf20 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py @@ -1,7 +1,6 @@ #pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * -import mantid.simpleapi as api import os class EQSANSDirectBeamTransmission(PythonAlgorithm): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py index 4f4a9c2d8d40..f51ed8dfce84 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py @@ -1,5 +1,5 @@ #pylint: disable=no-init -from mantid import config, logger, mtd, AlgorithmFactory +from mantid import config, logger, AlgorithmFactory from mantid.api import * from mantid.kernel import * from mantid.simpleapi import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py index fb5aa4f3dc57..6808073efe3c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py @@ -4,20 +4,19 @@ from mantid.simpleapi import * import itertools -import os - -timeRegimeToDRange = { - 1.17e4: tuple([ 0.7, 2.5]), - 2.94e4: tuple([ 2.1, 3.3]), - 4.71e4: tuple([ 3.1, 4.3]), - 6.48e4: tuple([ 4.1, 5.3]), - 8.25e4: tuple([ 5.2, 6.2]), - 10.02e4: tuple([ 6.2, 7.3]), - 11.79e4: tuple([ 7.3, 8.3]), - 13.55e4: tuple([ 8.3, 9.5]), - 15.32e4: tuple([ 9.4, 10.6]), - 17.09e4: tuple([10.4, 11.6]), - 18.86e4: tuple([11.0, 12.5])} + +timeRegimeToDRange = {\ + 1.17e4: tuple([ 0.7, 2.5]),\ + 2.94e4: tuple([ 2.1, 3.3]),\ + 4.71e4: tuple([ 3.1, 4.3]),\ + 6.48e4: tuple([ 4.1, 5.3]),\ + 8.25e4: tuple([ 5.2, 6.2]),\ + 10.02e4: tuple([ 6.2, 7.3]),\ + 11.79e4: tuple([ 7.3, 8.3]),\ + 13.55e4: tuple([ 8.3, 9.5]),\ + 15.32e4: tuple([ 9.4, 10.6]),\ + 17.09e4: tuple([10.4, 11.6]),\ + 18.86e4: tuple([11.0, 12.5])}\ """ A "wrapper" class for a map, which maps workspaces from their corresponding time regimes. @@ -99,17 +98,17 @@ def findIntersectionOfTwoRanges(rangeA, rangeB): assert rangeA[0] < rangeA[1], "Malformed range." assert rangeB[0] < rangeB[1], "Malformed range." - if( rangeA[0] <= rangeA[1] <= rangeB[0] <= rangeB[1]): + if rangeA[0] <= rangeA[1] <= rangeB[0] <= rangeB[1]: return - if( rangeB[0] <= rangeB[1] <= rangeA[0] <= rangeA[1]): + if rangeB[0] <= rangeB[1] <= rangeA[0] <= rangeA[1]: return - if( rangeA[0] <= rangeB[0] <= rangeB[1] <= rangeA[1] ): + if rangeA[0] <= rangeB[0] <= rangeB[1] <= rangeA[1] : return rangeB - if( rangeB[0] <= rangeA[0] <= rangeA[1] <= rangeB[1] ): + if rangeB[0] <= rangeA[0] <= rangeA[1] <= rangeB[1] : return rangeA - if( rangeA[0] <= rangeB[0] <= rangeA[1] <= rangeB[1] ): + if rangeA[0] <= rangeB[0] <= rangeA[1] <= rangeB[1] : return [rangeB[0], rangeA[1]] - if( rangeB[0] <= rangeA[0] <= rangeB[1] <= rangeA[1] ): + if rangeB[0] <= rangeA[0] <= rangeB[1] <= rangeA[1] : return [rangeA[0], rangeB[1]] assert False, "We should never reach here ..." diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py index b25b90a721c7..b9968c731e6d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py @@ -150,14 +150,14 @@ def weightedMean(data_array, error_array): # calculate the numerator of mean dataNum = 0 for i in range(sz): - if not (data_array[i] == 0): + if not data_array[i] == 0: tmpFactor = float(data_array[i]) / float((pow(error_array[i],2))) dataNum += tmpFactor # calculate denominator dataDen = 0 for i in range(sz): - if not (error_array[i] == 0): + if not error_array[i] == 0: tmpFactor = 1./float((pow(error_array[i],2))) dataDen += tmpFactor diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py index afbe6031ab5e..128f77083a97 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py @@ -3,7 +3,6 @@ from mantid.api import * from mantid.kernel import * import os -import sys from reduction_workflow.find_data import find_data class SANSBeamSpreaderTransmission(PythonAlgorithm): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py index 9888b80fa8bd..6d4abb895598 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py @@ -72,7 +72,7 @@ def __init__(self, numerator=None, denominator=None, print '---> initialize calculation' - if (tof_range is None): + if tof_range is None: self.tof_min = 10000 self.tof_max = 21600 else: @@ -386,7 +386,7 @@ def _calculateFinalAxis(self, Workspace=None, bNumerator=None): index_tof_min = self._getIndex(self.tof_min, x_axis) index_tof_max = self._getIndex(self.tof_max, x_axis) - if (bNumerator is True): + if bNumerator is True: self.y_axis_numerator = counts_vs_tof[index_tof_min:index_tof_max].copy() self.y_axis_error_numerator = counts_vs_tof_error[index_tof_min:index_tof_max].copy() self.x_axis_ratio = self.x_axis[index_tof_min:index_tof_max].copy() @@ -482,14 +482,14 @@ def weighted_mean(self, data, error): #calculate numerator dataNum = 0 for i in range(sz): - if (data[i] != 0): + if data[i] != 0: tmpFactor = float(data[i]) / (error[i]**2) dataNum += tmpFactor #calculate denominator dataDen = 0 for i in range(sz): - if (error[i] != 0): + if error[i] != 0: tmpFactor = float(1) / (error[i]**2) dataDen += tmpFactor @@ -575,7 +575,7 @@ def _removeBackground(self, max_back = 0 max_back_error = 0 - for t in (range(nbr_tof-1)): + for t in range(nbr_tof-1): _y_slice = data[:,t] _y_error_slice = error[:,t] @@ -780,7 +780,7 @@ def plotObject(instance): linestyle='', label='Exp. data') - if (instance.a is not None): + if instance.a is not None: x = linspace(10000, 22000, 100) _label = "%.3f + x*%.2e" % (instance.a, instance.b) plot(x, instance.a + instance.b * x, label=_label) @@ -858,7 +858,7 @@ def outputFittingParameters(a, b, error_a, error_b, #then if it does, parse the file and check if following infos are #already defined: # lambda_requested, S1H, S2H, S1W, S2W - if (bFileExist): + if bFileExist: f = open(output_file_name, 'r') text = f.readlines() # split_lines = text.split('\n') @@ -880,17 +880,17 @@ def outputFittingParameters(a, b, error_a, error_b, _line_split = _line.split(' ') _incident_medium = variable_value_splitter(_line_split[0]) - if (_incident_medium['value'].strip() == incident_medium.strip()): + if _incident_medium['value'].strip() == incident_medium.strip(): _lambdaRequested = variable_value_splitter(_line_split[1]) - if (isWithinRange(_lambdaRequested['value'], lambda_requested)): + if isWithinRange(_lambdaRequested['value'], lambda_requested): _s1h = variable_value_splitter(_line_split[2]) - if (isWithinRange(_s1h['value'], S1H[i])): + if isWithinRange(_s1h['value'], S1H[i]): _s2h = variable_value_splitter(_line_split[3]) - if (isWithinRange(_s2h['value'],S2H[i])): + if isWithinRange(_s2h['value'],S2H[i]): _s1w = variable_value_splitter(_line_split[4]) - if (isWithinRange(_s1w['value'],S1W[i])): + if isWithinRange(_s1w['value'],S1W[i]): _s2w = variable_value_splitter(_line_split[5]) - if (isWithinRange(_s2w['value'],S2W[i])): + if isWithinRange(_s2w['value'],S2W[i]): _match = True break @@ -995,7 +995,7 @@ def createIndividualList(string_list_files): list_files = "1000:0, 1001:1, 1002:1, 1003:2" return {1000:0, 1001:1, 1002:2, 1003:2} """ - if (string_list_files == ''): + if string_list_files == '': return None first_split = string_list_files.split(',') @@ -1168,7 +1168,7 @@ def isRunsSorted(list_runs, S1H, S2H): _left_formated = "%2.1f" % _left _right_formated = "%2.1f" % _right - if (_left_formated != _right_formated): + if _left_formated != _right_formated: return False return True @@ -1199,7 +1199,7 @@ def calculateAndFit(numerator='', cal1.run() print 'Done with cal1.run()' - if (list_objects != [] and list_objects[-1] is not None): + if list_objects != [] and list_objects[-1] is not None: new_cal1 = cal1 * list_objects[-1] new_cal1.fit() return new_cal1 @@ -1251,7 +1251,7 @@ def calculate(string_runs=None,\ list_attenuator = None #use default string files if not provided - if (string_runs is None): + if string_runs is None: #Input from user # list_runs = ['55889', '55890', '55891', '55892', '55893', '55894', # '55895', '55896', '55897', '55898', '55899', '55900', @@ -1280,14 +1280,14 @@ def calculate(string_runs=None,\ list_attenuator = dico['list_attenuator'] - if (incident_medium is None): + if incident_medium is None: incident_medium = "H20" #default value - if (list_attenuator is None): + if list_attenuator is None: # list_attenuator = [0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4] list_attenuator = [0, 1, 1, 1, 1, 1] - if (list_peak_back is None): + if list_peak_back is None: list_peak_back = zeros((len(list_runs), 4)) #[peak_min, peak_max, back_min, back_max] # list_peak_back[9, ] = [128, 136, 120, 145] # list_peak_back[11, ] = [125, 140, 115, 150] @@ -1382,8 +1382,7 @@ def calculate(string_runs=None,\ recordSettings(a, b, error_a, error_b, name, cal) - if (i < (len(list_runs) - 1) and - list_attenuator[i + 1] == (_attenuator+1)): + if i < (len(list_runs) - 1) and list_attenuator[i + 1] == (_attenuator+1): list_objects.append(cal) #record S1H and S2H diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py index b8b8dd5e86af..e4a356e071f2 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py @@ -268,18 +268,18 @@ def improvingCalibrationOfListOfTubes(filename): #CalibInstWS = loadingStep(filename) # it is defined as the mean values around the neighbours - define_peaks = {19:[10, 80.9771, 123.221, 164.993, 245.717], # the first one was bad\ - 37: [6.36, 80.9347, 122.941, 165.104, 248.32], # the first one was bad\ - 71: [8.62752, 85.074, 124.919, 164.116, 246.82 ], # the last one was bad - check if we can inprove\ - 75: [14.4285, 90.087, 128.987, 167.047, 242.62], # the last one was bad - check if we can inprove\ - 181: [11.726, 94.0496, 137.816, 180, 255], # the third peak was lost\ - 186:[11.9382, 71.5203, 107, 147.727, 239.041], #lost the second peak\ - 234: [4.84, 82.7824, 123.125, 163.945, 241.877], # the first one was bad\ - 235: [4.84, 80.0077, 121.002, 161.098, 238.502], # the first one was bad\ - 245: [9.88089, 93.0593, 136.911, 179.5, 255], # the third peak was bad\ - 273: [18.3711, 105.5, 145.5, 181.6, 243.252],# lost first and third peaks\ - 345: [4.6084, 87.0351, 128.125, 169.923, 245.3] # the last one was bad\ - } + define_peaks = {19:[10, 80.9771, 123.221, 164.993, 245.717],\ # the first one was bad + 37: [6.36, 80.9347, 122.941, 165.104, 248.32],\ # the first one was bad + 71: [8.62752, 85.074, 124.919, 164.116, 246.82 ],\ # the last one was bad - check if we can inprove + 75: [14.4285, 90.087, 128.987, 167.047, 242.62],\ # the last one was bad - check if we can inprove + 181: [11.726, 94.0496, 137.816, 180, 255],\ # the third peak was lost + 186:[11.9382, 71.5203, 107, 147.727, 239.041],\ #lost the second peak + 234: [4.84, 82.7824, 123.125, 163.945, 241.877],\ # the first one was bad + 235: [4.84, 80.0077, 121.002, 161.098, 238.502],\ # the first one was bad + 245: [9.88089, 93.0593, 136.911, 179.5, 255],\ # the third peak was bad + 273: [18.3711, 105.5, 145.5, 181.6, 243.252],\ # lost first and third peaks + 345: [4.6084, 87.0351, 128.125, 169.923, 245.3]\ # the last one was bad + } calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor, fitPar=fitPar, outputPeak=True, overridePeaks=define_peaks) @@ -487,12 +487,12 @@ def completeCalibration(filename): # apply the calibration for the b2_window 2 strips values calibrationTable, peak2Table = tube.calibrate(CalibInstWS, CalibratedComponent,\ - knownPos, #these parameters now have only 4 points\ - funcFactor,\ - fitPar=fitPar,\ - outputPeak=True,\ - calibTable = calibrationTable, # it will append to the calibTable\ - rangeList = b2_window) + knownPos,\ #these parameters now have only 4 points + funcFactor,\ + fitPar=fitPar,\ + outputPeak=True,\ + calibTable = calibrationTable,\ # it will append to the calibTable + rangeList = b2_window) ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable) diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py index 5fd30bafafc5..8d73f4a61ef8 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py @@ -16,7 +16,8 @@ # Set initial parameters for peak finding ExpectedHeight = -1000.0 # Expected Height of Gaussian Peaks (initial value of fit parameter) ExpectedWidth = 8.0 # Expected width of Gaussian peaks in pixels (initial value of fit parameter) -ExpectedPositions = [4.0, 85.0, 128.0, 161.0, 252.0] # Expected positions of the edges and Gaussian peaks in pixels (initial values of fit parameters) +ExpectedPositions = [4.0, 85.0, 128.0, 161.0, 252.0] +# Expected positions of the edges and Gaussian peaks in pixels (initial values of fit parameters) # Set what we want to calibrate (e.g whole intrument or one door ) CalibratedComponent = 'B1_window' # Calibrate B1 window diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py index 251a8a4afefe..b597caa3a92e 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py @@ -102,7 +102,7 @@ def calibrateMerlin(filename): calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door9pos, door9func,\ outputPeak=True,\ margin=30,\ - rangeList=range(20) # because 20, 21, 22, 23 are defective detectors\ + rangeList=range(20)\ # because 20, 21, 22, 23 are defective detectors ) print "Got calibration (new positions of detectors) and put slit peaks into file TubeDemoMerlin01.txt" analisePeakTable(peakTable, 'door9_tube1_peaks') @@ -113,7 +113,7 @@ def calibrateMerlin(filename): CalibratedComponent = 'MERLIN/door8' calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door8pos,\ door8func,\ - outputPeak = True, #change to peakTable to append to peakTable\ + outputPeak = True,\ #change to peakTable to append to peakTable calibTable = calibrationTable,\ margin = 30) analisePeakTable(peakTable, 'door8_peaks') diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py index 2b34e99bde9a..549bf85af3d3 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py @@ -8,7 +8,6 @@ import tube from mantid.simpleapi import * -from tube_calib_fit_params import TubeCalibFitParams def CalibrateWish( RunNumber, PanelNumber): ''' @@ -46,8 +45,8 @@ def CalibrateWish( RunNumber, PanelNumber): #calibrate the upper tubes calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, upper_tube, funcForm,\ rangeList = range(76,152),\ - calibTable=calibrationTable, #give the calibration table to append data\ - outputPeak = peakTable #give peak table to append data\ + calibTable=calibrationTable,\ #give the calibration table to append data + outputPeak = peakTable\ #give peak table to append data ) print "Got calibration (new positions of detectors)" diff --git a/Code/Mantid/scripts/Calibration/ideal_tube.py b/Code/Mantid/scripts/Calibration/ideal_tube.py index a77ce0b84e3d..61f61b076efa 100644 --- a/Code/Mantid/scripts/Calibration/ideal_tube.py +++ b/Code/Mantid/scripts/Calibration/ideal_tube.py @@ -5,7 +5,7 @@ # This class is the ideal tube, which specifies where the peaks formed by slits or edges should occur # Author: Karl Palmen ISIS -class IdealTube: +class IdealTube(object): """ The IdealTube specifies where the peaks formed by slits or edges should occur. @@ -73,7 +73,8 @@ def constructTubeFor3PointsMethod( self, idealAP, idealBP, idealCP, activeTubeLe pixelLen = activeTubeLen/1024 # Pixel length # we then convert idealAP, idealCP and idealBP to Y coordinates and put into ideal tube array - self.positions = numpy.array([ idealAP*pixelLen - activeTubeLen/2, idealCP*pixelLen - activeTubeLen/2, idealBP*pixelLen - activeTubeLen/2]) + self.positions = numpy.array([ idealAP*pixelLen - activeTubeLen/2,\ + idealCP*pixelLen - activeTubeLen/2, idealBP*pixelLen - activeTubeLen/2]) self.functionalForms = [ 2, 1, 2 ] diff --git a/Code/Mantid/scripts/Calibration/tube_calib.py b/Code/Mantid/scripts/Calibration/tube_calib.py index a3b46699b35d..8d1d31d46c7c 100644 --- a/Code/Mantid/scripts/Calibration/tube_calib.py +++ b/Code/Mantid/scripts/Calibration/tube_calib.py @@ -37,7 +37,7 @@ def createTubeCalibtationWorkspaceByWorkspaceIndexList ( integratedWorkspace, ou """ nSpectra = len(workspaceIndexList) - if( nSpectra < 1): + if nSpectra < 1: return pixelNumbers = [] integratedPixelCounts = [] @@ -200,7 +200,7 @@ def getPoints ( IntegratedWorkspace, funcForms, fitParams, whichTube, showPlot=F # Create input workspace for fitting ## get all the counts for the integrated workspace inside the tube countsY = numpy.array([IntegratedWorkspace.dataY(i)[0] for i in whichTube]) - if (len(countsY) == 0): + if len(countsY) == 0: return getPointsWs = CreateWorkspace(range(len(countsY)),countsY,OutputWorkspace='TubePlot') calibPointWs = 'CalibPoint' @@ -303,7 +303,7 @@ def correctTubeToIdealTube( tubePoints, idealTubePoints, nDets, TestMode=False, #print "correctTubeToIdealTube" # Check the arguments - if ( len(tubePoints) != len(idealTubePoints) ): + if len(tubePoints) != len(idealTubePoints) : print "Number of points in tube", len(tubePoints),"must equal number of points in ideal tube", len(idealTubePoints) return xResult @@ -312,18 +312,18 @@ def correctTubeToIdealTube( tubePoints, idealTubePoints, nDets, TestMode=False, usedIdealTubePoints = [] missedTubePoints = [] # Used for diagnostic print only for i in range(len(tubePoints)): - if( tubePoints[i] > 0.0 and tubePoints[i] < nDets): + if tubePoints[i] > 0.0 and tubePoints[i] < nDets: usedTubePoints.append( tubePoints[i] ) usedIdealTubePoints.append ( idealTubePoints[i] ) else: missedTubePoints.append(i+1) # State number of rogue slit points, if any - if( len(tubePoints) != len(usedTubePoints)): + if len(tubePoints) != len(usedTubePoints): print "Only",len(usedTubePoints),"out of",len(tubePoints)," slit points used. Missed",missedTubePoints # Check number of usable points - if( len(usedTubePoints) < 3): + if len(usedTubePoints) < 3: print "Too few usable points in tube",len(usedTubePoints) return [] @@ -346,7 +346,7 @@ def correctTubeToIdealTube( tubePoints, idealTubePoints, nDets, TestMode=False, # In test mode, shove the pixels that are closest to the reckoned peaks # to the position of the first detector so that the resulting gaps can be seen. - if( TestMode ): + if TestMode : print "TestMode code" for i in range( len(usedTubePoints) ): #print "used point",i,"shoving pixel",int(usedTubePoints[i]) @@ -377,13 +377,13 @@ def getCalibratedPixelPositions( ws, tubePts, idealTubePts, whichTube, peakTestM detPositions = [] #Get position of first and last pixel of tube nDets = len(whichTube) - if( nDets < 1): + if nDets < 1: return detIDs, detPositions # Correct positions of detectors in tube by quadratic fit pixels = correctTubeToIdealTube ( tubePts, idealTubePts, nDets, TestMode=peakTestMode, polinFit=polinFit ) #print pixels - if( len(pixels) != nDets): + if len(pixels) != nDets: print "Tube correction failed." return detIDs, detPositions baseInstrument = ws.getInstrument().getBaseInstrument() @@ -395,7 +395,7 @@ def getCalibratedPixelPositions( ws, tubePts, idealTubePts, whichTube, peakTestM d0pos,dNpos = det0.getPos(),detN.getPos() ## identical to norm of vector: |dNpos - d0pos| tubeLength = det0.getDistance(detN) - if( tubeLength <= 0.0): + if tubeLength <= 0.0: print "Zero length tube cannot be calibrated, calibration failed." return detIDs, detPositions #unfortunatelly, the operation '/' is not defined in V3D object, so @@ -502,13 +502,13 @@ def getCalibration( ws, tubeSet, calibTable, fitPar, iTube, peaksTable, all_skipped.update(skipped) print "Calibrating tube", i+1,"of",nTubes, tubeSet.getTubeName(i) - if ( len(wht) < 1 ): + if len(wht) < 1 : print "Unable to get any workspace indices (spectra) for this tube. Tube",tubeSet.getTubeName(i),"not calibrated." #skip this tube continue # Calibribate the tube, if possible - if (tubeSet.getTubeLength(i) <= excludeShortTubes): + if tubeSet.getTubeLength(i) <= excludeShortTubes: #skip this tube continue @@ -537,7 +537,7 @@ def getCalibration( ws, tubeSet, calibTable, fitPar, iTube, peaksTable, detIDList, detPosList = getCalibratedPixelPositions( ws, actualTube, iTube.getArray(), wht, peaksTestMode, polinFit) #save the detector positions to calibTable - if( len(detIDList) == len(wht)): # We have corrected positions + if len(detIDList) == len(wht): # We have corrected positions for j in range(len(wht)): nextRow = {'Detector ID': detIDList[j], 'Detector Position': detPosList[j] } calibTable.addRow ( nextRow ) @@ -587,19 +587,19 @@ def getCalibrationFromPeakFile ( ws, calibTable, iTube, PeakFile ): wht, _ = tube.getTube(0) print "Calibrating tube", i+1 ,"of", nTubes, TubeName #, " length", tubeSet.getTubeLength(i) - if ( len(wht) < 1 ): + if len(wht) < 1 : print "Unable to get any workspace indices for this tube. Calibration abandoned." return detIDList, detPosList = getCalibratedPixelPositions( ws, actualTube, idealTube, wht) #print len(wht) - if( len(detIDList) == len(wht)): # We have corrected positions + if len(detIDList) == len(wht): # We have corrected positions for j in range(len(wht)): nextRow = {'Detector ID': detIDList[j], 'Detector Position': detPosList[j] } calibTable.addRow ( nextRow ) - if(nTubes == 0): + if nTubes == 0: return # Delete temporary workspaces for getting new detector positions @@ -626,16 +626,16 @@ def constructIdealTubeFromRealTube( ws, tube, fitPar, funcForm ): idealTube = IdealTube() nTubes = tube.getNumTubes() - if(nTubes < 1): + if nTubes < 1: raise RuntimeError("Invalid tube specification received by constructIdealTubeFromRealTube") - elif(nTubes > 1): + elif nTubes > 1: print "Specification has several tubes. The ideal tube will be based on the first tube",tube.getTubeName(0) wht, _ = tube.getTube(0) # print wht # Check tube - if ( len(wht) < 1 ): + if len(wht) < 1 : raise RuntimeError("Unable to get any workspace indices for this tube. Cannot use as ideal tube.") # Get actual tube on which ideal tube is based diff --git a/Code/Mantid/scripts/Calibration/tube_spec.py b/Code/Mantid/scripts/Calibration/tube_spec.py index c699cc3b1edb..8b71923e42d4 100644 --- a/Code/Mantid/scripts/Calibration/tube_spec.py +++ b/Code/Mantid/scripts/Calibration/tube_spec.py @@ -107,8 +107,8 @@ def isTube(self, comp): :rtype: Value, true if component passes test as being a tube """ # We simply assume it's a tube if it has a large number of children - if( hasattr( comp, "nelements")): - return (comp.nelements() >= self.minNumDetsInTube ) + if hasattr( comp, "nelements"): + return comp.nelements() >= self.minNumDetsInTube else: return False @@ -125,7 +125,7 @@ def searchForTubes(self, comp): #print "Tube found", comp.getName() # If not tube, Search children, if any else: - if( hasattr( comp, "nelements")): + if hasattr( comp, "nelements"): for i in range(comp.nelements()): self.searchForTubes(comp[i]) @@ -136,12 +136,12 @@ def getNumTubes(self): :rtype: Value, number of tubes (-1 for erroneous specification) """ - if(self.numTubes >= 0): + if self.numTubes >= 0: return self.numTubes # We have a negative number set in self.numTubes, so we search for tubes comps = self.getComponents() - if( comps == []): + if comps == []: return self.numTubes for i in range( len(comps)): @@ -157,7 +157,7 @@ def getComponent ( self ): :rtype: instrument component """ - if( self.componentArray != []): + if self.componentArray != []: return self.componentArray[0] # We look for the component @@ -165,7 +165,7 @@ def getComponent ( self ): comp = self.inst.getComponentByName(self.componentNameArray[0]) - if( comp ): + if comp : self.componentArray.append(comp) return self.componentArray[0] @@ -177,7 +177,7 @@ def getComponents ( self ): :rtype: array of instrument components """ - if( self.componentArray != []): + if self.componentArray != []: return self.componentArray # We look for the components @@ -186,7 +186,7 @@ def getComponents ( self ): comp = self.inst.getComponentByName(self.componentNameArray[i]) - if( comp ): + if comp : self.componentArray.append(comp) else: print "Did not find", self.componentNameArray[i] @@ -214,28 +214,28 @@ def getDetectorInfoFromTube( self, tubeIx ): :rtype: ID of first detector, number of detectors and step between detectors +1 or -1 """ nTubes = self.getNumTubes() - if(nTubes < 0): + if nTubes < 0: print "Error in listing tubes" return 0, 0, 1 - if(tubeIx < 0 or tubeIx >= nTubes): + if tubeIx < 0 or tubeIx >= nTubes: print "Tube index",tubeIx,"out of range 0 to",nTubes return 0, 0, 1 comp = self.tubes[tubeIx] - if(comp != 0): + if comp != 0: firstDet = comp[0].getID() numDet = comp.nelements() # Allow for reverse numbering of Detectors lastDet = comp[numDet-1].getID() - if (lastDet < firstDet): + if lastDet < firstDet: step = -1 - if( firstDet - lastDet + 1 != numDet): + if firstDet - lastDet + 1 != numDet: print "Detector number range",firstDet-lastDet+1," not equal to number of detectors",numDet print "Detectors not numbered continuously in this tube. Calibration will fail for this tube." else: step = 1 - if( lastDet - firstDet + 1 != numDet): + if lastDet - firstDet + 1 != numDet: print "Detector number range",lastDet-firstDet+1," not equal to number of detectors",numDet print "Detectors not numbered continuously in this tube. Calibration will fail for this tube." @@ -257,16 +257,16 @@ def getTubeLength( self, tubeIx ): """ nTubes = self.getNumTubes() - if(nTubes < 0): + if nTubes < 0: print "Error in listing tubes" return 0.0 - if(tubeIx < 0 or tubeIx >= nTubes): + if tubeIx < 0 or tubeIx >= nTubes: print "Tube index",tubeIx,"out of range 0 to",nTubes return 0.0 comp = self.tubes[tubeIx] - if(comp != 0): + if comp != 0: firstDet = comp[0].getID() numDet = comp.nelements() return comp[0].getDistance( comp[numDet-1] ) @@ -286,16 +286,16 @@ def getTubeName ( self, tubeIx ): :rtype: Name of tube as in IDF or 'unknown' if not found. """ nTubes = self.getNumTubes() - if(nTubes < 0): + if nTubes < 0: print "Error in listing tubes" return 'Unknown' - if(tubeIx < 0 or tubeIx >= nTubes): + if tubeIx < 0 or tubeIx >= nTubes: print "Tube index",tubeIx,"out of range 0 to",nTubes return 'Unknown' comp = self.tubes[tubeIx] - if(comp != 0): + if comp != 0: return comp.getFullName() else: print self.componentNameArray[0], tubeIx, "not found" @@ -323,17 +323,17 @@ def getTubeByString(self, tubeIx): sp = self.ws.getSpectrum(sampleIndex) detids = sp.getDetectorIDs() numDetsPerWkID = len(detids) - if( numDetsPerWkID != 1): + if numDetsPerWkID != 1: print "We have",numDetsPerWkID,"detectors per workspace index. 1 is required." print "cannot obtain range of workspace indices for this tube in this workspace" return wkIds, skipped # Go and get workspace Indices - if(step == -1): + if step == -1: startDet = firstDet - numDet + 1 else: startDet = firstDet - if( numDet > 0): + if numDet > 0: for i in range (0, self.ws.getNumberHistograms(), numDet): try: deti = self.ws.getDetector(i) @@ -341,13 +341,13 @@ def getTubeByString(self, tubeIx): skipped.append(i) continue detID = deti.getID() - if (detID >= startDet and detID < startDet+numDet): + if detID >= startDet and detID < startDet+numDet: iPixel = detID - firstDet wkIds = range( i - iPixel, i - iPixel + step*numDet, step) # print "Workspace indices",i-iPixel,"to",i-iPixel+numDet-1 #print firstDet, numDet - if (numDet > 0): + if numDet > 0: return wkIds, skipped else: print "specified tube has no detectors." @@ -364,7 +364,7 @@ def getTube(self, tubeIx): :rtype: list of indices """ nTubes = self.getNumTubes() - if( (0 <= tubeIx) & (tubeIx < nTubes) ): + if (0 <= tubeIx) & (tubeIx < nTubes) : return self.getTubeByString(tubeIx) else: print "Tube", tubeIx, "out of range 0 to",self.numTubes,"." diff --git a/Code/Mantid/scripts/Engineering/EnginXUtils.py b/Code/Mantid/scripts/Engineering/EnginXUtils.py index dfcd58de7fc8..6ca38533361e 100644 --- a/Code/Mantid/scripts/Engineering/EnginXUtils.py +++ b/Code/Mantid/scripts/Engineering/EnginXUtils.py @@ -37,7 +37,7 @@ def getWsIndicesForBank(bank, ws): def isIndexInBank(index): try: det = ws.getDetector(index) - return (det.getID() in detIDs) + return det.getID() in detIDs except: return False diff --git a/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py b/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py index 2816abce37c6..a2e86978f080 100644 --- a/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py +++ b/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py @@ -1,5 +1,4 @@ #pylint: disable=invalid-name -import math import numpy from Ui_MainWindow import Ui_MainWindow #import line for the UI python class @@ -7,11 +6,7 @@ from PyQt4.QtCore import * from PyQt4.QtGui import * -import matplotlib -from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas -from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar -from matplotlib.figure import Figure -from matplotlib.pyplot import gcf, setp +from matplotlib.pyplot import setp import mantid import mantid.simpleapi as api @@ -1027,11 +1022,11 @@ def filterByTime(self): print "Input workspace = ", str(self._dataWS) END DB """ - splitws, infows = api.GenerateEventsFilter( - InputWorkspace = self._dataWS, - UnitOfTime = "Seconds", - TitleOfSplitters = title, - OutputWorkspace = splitwsname, + splitws, infows = api.GenerateEventsFilter(\ + InputWorkspace = self._dataWS,\ + UnitOfTime = "Seconds",\ + TitleOfSplitters = title,\ + OutputWorkspace = splitwsname,\ InformationWorkspace = splitinfowsname, **kwargs) self.splitWksp(splitws, infows) @@ -1081,12 +1076,12 @@ def filterByLogValue(self): title = str(self.ui.lineEdit_title.text()) - splitws, infows = api.GenerateEventsFilter( - InputWorkspace = self._dataWS, - UnitOfTime = "Seconds", - TitleOfSplitters = title, - OutputWorkspace = splitwsname, - LogName = samplelog, + splitws, infows = api.GenerateEventsFilter(\ + InputWorkspace = self._dataWS,\ + UnitOfTime = "Seconds",\ + TitleOfSplitters = title,\ + OutputWorkspace = splitwsname,\ + LogName = samplelog,\ InformationWorkspace = splitinfowsname, **kwargs) try: @@ -1121,17 +1116,17 @@ def splitWksp(self, splitws, infows): outbasewsname = "tempsplitted" self.ui.lineEdit_outwsname.setText(outbasewsname) - api.FilterEvents( - InputWorkspace = self._dataWS, - SplitterWorkspace = splitws, - InformationWorkspace = infows, - OutputWorkspaceBaseName = outbasewsname, - GroupWorkspaces = dogroupws, - FilterByPulseTime = filterbypulse, - CorrectionToSample = corr2sample, - SpectrumWithoutDetector = how2skip, - SplitSampleLogs = splitsamplelog, - OutputWorkspaceIndexedFrom1 = startfrom1, + api.FilterEvents(\ + InputWorkspace = self._dataWS,\ + SplitterWorkspace = splitws,\ + InformationWorkspace = infows,\ + OutputWorkspaceBaseName = outbasewsname,\ + GroupWorkspaces = dogroupws,\ + FilterByPulseTime = filterbypulse,\ + CorrectionToSample = corr2sample,\ + SpectrumWithoutDetector = how2skip,\ + SplitSampleLogs = splitsamplelog,\ + OutputWorkspaceIndexedFrom1 = startfrom1,\ OutputTOFCorrectionWorkspace = 'TOFCorrTable', **kwargs) return diff --git a/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py b/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py index dca70d0e2ffc..ea76a73778e2 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py +++ b/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py @@ -488,7 +488,7 @@ def convert_to_energy(self,wb_run=None,sample_run=None,ei_guess=None,rebin=None, results_name = deltaE_ws_sample.name() - if out_ws_name and not(self._multirep_mode): + if out_ws_name and not self._multirep_mode: if results_name != out_ws_name: RenameWorkspace(InputWorkspace=results_name,OutputWorkspace=out_ws_name) result = mtd[out_ws_name] @@ -562,7 +562,7 @@ def calculate_rotation(self,sample_wkspace,motor=None, offset=None): offset = self.prop_man.motor_offset # - if (offset is None): + if offset is None: motor_offset = float('nan') else: motor_offset = float(offset) @@ -1071,7 +1071,7 @@ def get_abs_normalization_factor(self,deltaE_wkspaceName,ei_monovan): err = data_ws.readE(i)[0] if sig != sig: #ignore NaN (hopefully it will mean mask some day) continue - if ((err <= 0) or (sig <= 0)): # count Inf and negative||zero readings. Presence of this indicates that + if (err <= 0) or (sig <= 0): # count Inf and negative||zero readings. Presence of this indicates that # something went wrong izerc+=1 continue @@ -1105,7 +1105,7 @@ def get_abs_normalization_factor(self,deltaE_wkspaceName,ei_monovan): # n_i is the modified signal signal_sum = sum(map(lambda e: e * e,error)) weight_sum = sum(map(lambda s,e: e * e / s,signal,error)) - if(weight_sum == 0.0): + if weight_sum == 0.0: prop_man.log("WB integral has been calculated incorrectly, look at van_int workspace: {0}".format(deltaE_wkspaceName),'error') raise ArithmeticError("Division by 0 weight when calculating WB integrals from workspace {0}".format(deltaE_wkspaceName)) norm_factor['Poisson'] = signal_sum / weight_sum @@ -1114,7 +1114,7 @@ def get_abs_normalization_factor(self,deltaE_wkspaceName,ei_monovan): # TGP suggestion from 12-2012 signal_sum = sum(map(lambda s,e: s * s / (e * e),signal,error)) weight_sum = sum(map(lambda s,e: s / (e * e),signal,error)) - if(weight_sum == 0.0): + if weight_sum == 0.0: prop_man.log("WB integral has been calculated incorrectly, look at van_int workspace: {0}".format(deltaE_wkspaceName),'error') raise ArithmeticError("Division by 0 weight when calculating WB integrals from workspace {0}".format(deltaE_wkspaceName)) norm_factor['TGP'] = signal_sum / weight_sum @@ -1136,7 +1136,7 @@ def get_abs_normalization_factor(self,deltaE_wkspaceName,ei_monovan): # check for NaN if (norm_factor['LibISIS'] != norm_factor['LibISIS']) | (izerc != 0): # It is an error, print diagnostics: - if (norm_factor['LibISIS'] != norm_factor['LibISIS']): + if norm_factor['LibISIS'] != norm_factor['LibISIS']: log_value = '\n--------> Absolute normalization factor is NaN <----------------------------------------------\n' else: log_value = '\n--------> Warning, Monovanadium has zero spectra <--------------------------------------------\n' @@ -1386,7 +1386,7 @@ def _do_mono(self, run, ei_guess, normalization to a white-beam vanadium run. """ - if (self._do_ISIS_reduction): + if self._do_ISIS_reduction: self._do_mono_ISIS(run,ei_guess,\ white_run, map_file, spectra_masks, Tzero) else: diff --git a/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py b/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py index 2e775a0b0f1e..b4c1ed622716 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py +++ b/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py @@ -28,7 +28,7 @@ def __init__(self,Instrument,run_workspace=None): deployed in reduction """ # - if not(run_workspace is None): + if not run_workspace is None: object.__setattr__(self,'sample_run',run_workspace) # Helper properties, defining logging options diff --git a/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py b/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py index 87aadf239b50..b8494f8a5eb5 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py +++ b/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py @@ -393,9 +393,9 @@ def get_abs_range(self,instance=None): def is_range_valid(self): """Method verifies if binning range is consistent with incident energy """ if self._incident_energy.multirep_mode(): - return (self._energy_bins[2] <= self._range) + return self._energy_bins[2] <= self._range else: - return (self._energy_bins[2] <= self._incident_energy.get_current()) + return self._energy_bins[2] <= self._incident_energy.get_current() def _calc_relative_range(self,ei,range_mult=1): """ """ @@ -624,7 +624,7 @@ class MapMaskFile(PropDescriptor): def __init__(self,file_ext,doc_string=None): self._file_name = None self._file_ext = file_ext - if not(doc_string is None): + if not doc_string is None: self.__doc__ = doc_string def __get__(self,instance,type=None): @@ -636,7 +636,7 @@ def __get__(self,instance,type=None): def __set__(self,instance,value): if value != None: fileName, fileExtension = os.path.splitext(value) - if (not fileExtension): + if not fileExtension: value = value + self._file_ext self._file_name = value @@ -655,7 +655,7 @@ def __get__(self,instance,type=None): def __set__(self,instance,value): if value != None: fileName, fileExtension = os.path.splitext(value) - if (not fileExtension): + if not fileExtension: value = value + '.msk' instance.hard_mask_file = value prop_helpers.ComplexProperty.__set__(self,instance.__dict__,[False,True]) @@ -756,7 +756,7 @@ def __set__(self,instance,value): else: tDict = instance.__dict__ if value is None: - if (not self._rel_range): + if not self._rel_range: self._rel_range = True self._other_prop = ['monovan_lo_frac','monovan_hi_frac'] else: @@ -858,7 +858,7 @@ def __set__(self,instance,value): else: value = subformats[0] - if not(value in SaveFormat.save_formats): + if not value in SaveFormat.save_formats: instance.log("Trying to set saving in unknown format: \"" + str(value) + "\" No saving will occur for this format") return else: diff --git a/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py b/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py index dbea0fcda92b..5ab7fe6d8978 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py +++ b/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py @@ -157,7 +157,7 @@ def __setattr__(self,name0,val): # replace common substitutions for string value if type(val) is str : val1 = val.lower() - if (val1 == 'none' or len(val1) == 0): + if val1 == 'none' or len(val1) == 0: val = None if val1 == 'default': val = self.getDefaultParameterValue(name0) @@ -262,16 +262,16 @@ def set_input_parameters_ignore_nan(self,**kwargs): with some parameters missing. """ # if sum is in parameters one needs to set it first - if 'sum_runs' in kwargs and not (kwargs['sum_runs'] is None): + if 'sum_runs' in kwargs and not kwargs['sum_runs'] is None: self.sum_runs = kwargs['sum_runs'] del kwargs['sum_runs'] - if 'sum' in kwargs and not (kwargs['sum'] is None): + if 'sum' in kwargs and not kwargs['sum'] is None: self.sum_runs = kwargs['sum'] del kwargs['sum'] for par_name,value in kwargs.items() : - if not(value is None): + if not value is None: setattr(self,par_name,value) @@ -367,7 +367,7 @@ def update_defaults_from_instrument(self,pInstrument,ignore_changes=False): param_list = prop_helpers.get_default_idf_param_list(pInstrument) # remove old changes which are not related to IDF (not to reapply it again) for prop_name in old_changes: - if not (prop_name in param_list): + if not prop_name in param_list: try: dependencies = getattr(PropertyManager,prop_name).dependencies() except: @@ -392,7 +392,7 @@ def update_defaults_from_instrument(self,pInstrument,ignore_changes=False): # Assignment to descriptors should accept the form, descriptor is written in IDF changed_descriptors = set() for key,val in descr_dict.iteritems(): - if not (key in old_changes_list): + if not key in old_changes_list: try: # this is reliability check, and except ideally should never be hit. May occur if old IDF contains # properties, not present in recent IDF. cur_val = getattr(self,key) @@ -430,7 +430,7 @@ def update_defaults_from_instrument(self,pInstrument,ignore_changes=False): # Walk through the complex properties first and then through simple properties for key,val in sorted_param.iteritems(): - if not(key in old_changes_list): + if not key in old_changes_list: # complex properties change through their dependencies so we are setting them first if isinstance(val,prop_helpers.ComplexProperty): public_name = key[1:] @@ -513,7 +513,7 @@ def check_files_list(files_list): base_file_missing = check_files_list(self.__file_properties) abs_file_missing=False - if not (monovan_run is None): + if not monovan_run is None: abs_file_missing = check_files_list(self.__abs_norm_file_properties) if base_file_missing or abs_file_missing: @@ -581,7 +581,7 @@ def log_changed_values(self,log_level='notice',display_header=True,already_chang save_dir = config.getString('defaultsave.directory') self.log("****************************************************************",log_level) - if self.monovan_run != None and not('van_mass' in changed_Keys): # This output is + if self.monovan_run != None and not 'van_mass' in changed_Keys: # This output is self.log("*** Monochromatic vanadium mass used : {0} ".format(self.van_mass),log_level) # Adroja request from may 2014 # self.log("*** By default results are saved into: {0}".format(save_dir),log_level) diff --git a/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py b/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py index 687a731b6f58..d1943b913b8c 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py +++ b/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py @@ -212,9 +212,9 @@ def gen_getter(keyval_dict,key): gen_getter(keyval_dict,A) == 10; gen_getter(keyval_dict,B) == 20; and gen_getter(keyval_dict,C) == [10,20]; """ - if not(key in keyval_dict): + if not key in keyval_dict: name = '_'+key - if not(name in keyval_dict): + if not name in keyval_dict: raise KeyError('Property with name: {0} is not among the class properties '.format(key)) else: name = key @@ -239,9 +239,9 @@ def gen_setter(keyval_dict,key,val): and gen_getter(keyval_dict,C,[1,2]) causes keyval_dict[A] == 1 and keyval_dict[B] == 2 """ - if not(key in keyval_dict): + if not key in keyval_dict: name = '_'+key - if not(name in keyval_dict): + if not name in keyval_dict: raise KeyError(' Property name: {0} is not defined'.format(key)) else: name = key @@ -263,7 +263,7 @@ def check_instrument_name(old_name,new_name): if new_name is None: - if not(old_name is None): + if not old_name is None: return (None,None,str(config.getFacility())) else: raise KeyError("No instrument name is defined") diff --git a/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py b/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py index a8f3240fb30f..6b61fbc53dbf 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py +++ b/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py @@ -306,7 +306,7 @@ def _set_ws_as_source(self,value): def chop_ws_part(self,origin,tof_range,rebin,chunk_num,n_chunks): """ chop part of the original workspace and sets it up as new original. Return the old one """ - if not(origin): + if not origin: origin = self.get_workspace() origin_name = origin.name() @@ -446,7 +446,7 @@ def find_file(self,inst_name=None,run_num=None,filePath=None,fileExt=None,**kwar except RuntimeError: message = 'Cannot find file matching hint {0} on current search paths ' \ 'for instrument {1}'.format(file_hint,inst_name) - if not ('be_quet' in kwargs): + if not 'be_quet' in kwargs: RunDescriptor._logger(message,'warning') return 'ERROR:find_file: ' + message #-------------------------------------------------------------------------------------------------------------------- @@ -496,7 +496,7 @@ def load_run(self,inst_name, calibration=None, force=False, mon_load_option=Fals self._ws_name = None ws_name = self.get_ws_name() #----------------------------------- - if ws_name in mtd and not(force): + if ws_name in mtd and not force: RunDescriptor._logger("{0} already loaded as workspace.".format(ws_name),'information') else: # If it doesn't exists as a workspace assume we have to try and diff --git a/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py b/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py index ac74d3baf48c..2c9d4ca926b0 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py +++ b/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py @@ -1,10 +1,7 @@ #pylint: disable=invalid-name """ Empty class temporary left for compatibility with previous interfaces """ import DirectEnergyConversion as DRC -import CommonFunctions as common -import time as time from mantid.simpleapi import * -from mantid import api from mantid.kernel import funcreturns @@ -33,7 +30,7 @@ def setup(instname=None,reload=False): instname = config['default.instrument'] - if not (Reducer is None) : + if not Reducer is None : old_name=Reducer.prop_man.instr_name if old_name.upper()[0:3] == instname.upper()[0:3] : if not reload : diff --git a/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py b/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py index 11a587e4f47e..e443f21074f9 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py +++ b/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py @@ -356,7 +356,7 @@ def FlatAbs(ncan, thick, density, sigs, siga, angles, waves): acc = np.ones(nlam) # case where tsec is close to 90 degrees. CALCULATION IS UNRELIABLE - if (abs(abs(tsec)-90.0) < 1.0): + if abs(abs(tsec)-90.0) < 1.0: #default to 1 for everything return ass, assc, acsc, acc else: @@ -386,7 +386,7 @@ def FlatAbs(ncan, thick, density, sigs, siga, angles, waves): sampleSec1, sampleSec2 = calcThicknessAtSec(sampleXSection, samThickness, [sec1, sec2]) - if (sec2 < 0.): + if sec2 < 0.: ass = fs / samThickness else: ass= np.exp(-sampleSec2) * fs / samThickness @@ -432,7 +432,7 @@ def calcFlatAbsCan(ass, canXSection, canThickness1, canThickness2, sampleSec1, s canThick1Sec1, canThick1Sec2 = calcThicknessAtSec(canXSection, canThickness1, sec) canThick2Sec1, canThick2Sec2 = calcThicknessAtSec(canXSection, canThickness2, sec) - if (sec2 < 0.): + if sec2 < 0.: val = np.exp(-(canThick1Sec1-canThick1Sec2)) assc = ass * val @@ -453,7 +453,7 @@ def calcFlatAbsCan(ass, canXSection, canThickness1, canThickness2, sampleSec1, s canThickness = canThickness1 + canThickness2 - if(canThickness > 0.): + if canThickness > 0.: acc = (acc1 + acc2) / canThickness acsc = (acsc1 + acsc2) / canThickness diff --git a/Code/Mantid/scripts/Inelastic/IndirectBayes.py b/Code/Mantid/scripts/Inelastic/IndirectBayes.py index 034439f50f60..6c329884cc18 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectBayes.py +++ b/Code/Mantid/scripts/Inelastic/IndirectBayes.py @@ -338,11 +338,11 @@ def QLRun(program,samWS,resWS,resnormWS,erange,nbins,Fit,wfile,Loop,Plot,Save): CreateWorkspace(OutputWorkspace=probWS, DataX=xProb, DataY=yProb, DataE=eProb,\ Nspec=3, UnitX='MomentumTransfer') outWS = C2Fw(samWS[:-4],fname) - if (Plot != 'None'): + if Plot != 'None': QuasiPlot(fname,Plot,res_plot,Loop) if program == 'QSe': outWS = C2Se(fname) - if (Plot != 'None'): + if Plot != 'None': QuasiPlot(fname,Plot,res_plot,Loop) #Add some sample logs to the output workspaces @@ -624,14 +624,14 @@ def QuasiPlot(ws_stem,plot_type,res_plot,sequential): ws_name = ws_stem + '_Result' num_spectra = mtd[ws_name].getNumberHistograms() - if (plot_type == 'Prob' or plot_type == 'All'): + if plot_type == 'Prob' or plot_type == 'All': prob_ws = ws_stem+'_Prob' if prob_ws in mtd.getObjectNames(): mp.plotSpectrum(prob_ws,[1,2],False) QuasiPlotParameters(ws_name, plot_type) - if (plot_type == 'Fit' or plot_type == 'All'): + if plot_type == 'Fit' or plot_type == 'All': fWS = ws_stem+'_Workspace_0' f_plot=mp.plotSpectrum(fWS,res_plot,False) @@ -648,10 +648,10 @@ def QuasiPlotParameters(ws_name, plot_type): param_names = ['Amplitude', 'FWHM', 'Beta'] for param_name in param_names: - if (plot_type == param_name or plot_type == 'All'): + if plot_type == param_name or plot_type == 'All': spectra_indicies = [i for i in range(num_spectra) if param_name in mtd[ws_name].getAxis(1).label(i)] - if(len(spectra_indicies) > 0): + if len(spectra_indicies) > 0: plotSpectra(ws_name, param_name, indicies=spectra_indicies[:3]) # Quest programs @@ -743,7 +743,7 @@ def QuestRun(samWS,resWS,nbs,erange,nbins,Fit,Loop,Plot,Save): dataXb = xbout[:Nbet] dataYb = ybout[:Nbet] zpWS = fname + '_Zp' +str(m) - if (m > 0): + if m > 0: Qaxis += ',' Qaxis += str(Q[m]) @@ -818,7 +818,7 @@ def QuestRun(samWS,resWS,nbs,erange,nbins,Fit,Loop,Plot,Save): logger.information('Output file for Fit : ' + fpath) logger.information('Output file for Contours : ' + cpath) - if (Plot != 'None' and Loop == True): + if Plot != 'None' and Loop == True: QuestPlot(fname,Plot) EndTime('Quest') @@ -836,9 +836,9 @@ def QuestAddSampleLogs(workspace, res_workspace, background, elastic_peak, e_ran def QuestPlot(inputWS,Plot): - if (Plot == 'Sigma' or Plot == 'All'): + if Plot == 'Sigma' or Plot == 'All': sig_plot=mp.importMatrixWorkspace(inputWS+'_Sigma').plotGraph2D() - if (Plot == 'Beta' or Plot == 'All'): + if Plot == 'Beta' or Plot == 'All': beta_plot=mp.importMatrixWorkspace(inputWS+'_Beta').plotGraph2D() # ResNorm programs @@ -935,7 +935,7 @@ def ResNormRun(vname,rname,erange,nbin,Plot='None',Save=False): logger.information('Parameter file created : ' + par_path) logger.information('Fit file created : ' + fit_path) - if (Plot != 'None'): + if Plot != 'None': ResNormPlot(fname,Plot) EndTime('ResNorm') @@ -947,12 +947,12 @@ def ResNormAddSampleLogs(workspace, e_range, v_binning): AddSampleLog(Workspace=workspace, LogName="van_binning", LogType="Number", LogText=str(v_binning)) def ResNormPlot(inputWS,Plot): - if (Plot == 'Intensity' or Plot == 'All'): + if Plot == 'Intensity' or Plot == 'All': iWS = inputWS + '_ResNorm_Intensity' i_plot=mp.plotSpectrum(iWS,0,False) - if (Plot == 'Stretch' or Plot == 'All'): + if Plot == 'Stretch' or Plot == 'All': sWS = inputWS + '_ResNorm_Stretch' s_plot=mp.plotSpectrum(sWS,0,False) - if (Plot == 'Fit' or Plot == 'All'): + if Plot == 'Fit' or Plot == 'All': fWS = inputWS + '_ResNorm_Fit' f_plot=mp.plotSpectrum(fWS,0,False) diff --git a/Code/Mantid/scripts/Inelastic/IndirectCommon.py b/Code/Mantid/scripts/Inelastic/IndirectCommon.py index 4388c5992cc3..32d4b57ab60f 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectCommon.py +++ b/Code/Mantid/scripts/Inelastic/IndirectCommon.py @@ -106,7 +106,7 @@ def checkUnitIs(ws, unit_id, axis_index=0): """ axis = mtd[ws].getAxis(axis_index) unit = axis.getUnit() - return (unit.unitID() == unit_id) + return unit.unitID() == unit_id # Get the default save directory and check it's valid def getDefaultWorkingDirectory(): @@ -138,7 +138,7 @@ def createQaxis(inputWS): if not axis.isNumeric(): msg += 'Input workspace must have either spectra or numeric axis.' raise ValueError(msg) - if ( axis.getUnit().unitID() != 'MomentumTransfer' ): + if axis.getUnit().unitID() != 'MomentumTransfer' : msg += 'Input must have axis values of Q' raise ValueError(msg) for i in range(0, nHist): diff --git a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py index 48b5271f2fea..7a536ba87deb 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py +++ b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py @@ -527,7 +527,7 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): # Check that number of histograms in each corrections workspace matches # that of the input (sample) workspace for ws in corrections: - if ( mtd[ws].getNumberHistograms() != nHist ): + if mtd[ws].getNumberHistograms() != nHist : raise ValueError('Mismatch: num of spectra in '+ws+' and inputWS') # Workspaces that hold intermediate results CorrectedSampleWS = '__csam' diff --git a/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py b/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py index 0bef58b4a212..477210de2277 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py +++ b/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py @@ -34,8 +34,8 @@ def loadData(rawfiles, outWS='RawFile', Sum=False, SpecMin=-1, SpecMax=-1,\ return workspaces def createMappingFile(groupFile, ngroup, nspec, first): - if ( ngroup == 1 ): return 'All' - if ( nspec == 1 ): return 'Individual' + if ngroup == 1 : return 'All' + if nspec == 1 : return 'Individual' filename = config['defaultsave.directory'] filename = os.path.join(filename, groupFile) handle = open(filename, 'w') @@ -86,7 +86,7 @@ def getInstrumentDetails(instrument): if j < ( len(reflections[i][1]) -1 ): message += ',' result += message - if ( i < ( len(reflections) - 1) ): + if i < ( len(reflections) - 1) : result += '\n' return result diff --git a/Code/Mantid/scripts/Inelastic/IndirectMuscat.py b/Code/Mantid/scripts/Inelastic/IndirectMuscat.py index 8dfbabd426c1..99cd2f969532 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectMuscat.py +++ b/Code/Mantid/scripts/Inelastic/IndirectMuscat.py @@ -23,12 +23,12 @@ def CalcW0(nq,dq,disp,coeff): Q.append(q0) q02 = q0*q0 Q2.append(q02) - if (disp == 'Poly'): + if disp == 'Poly': w = coeff[0]+coeff[1]*q0+coeff[2]*q02+coeff[3]*q0*q02+coeff[4]*q02*q02 - if (disp == 'CE'): + if disp == 'CE': qk = coeff[1]*q0 w = coeff[0]*(1.0-math.sin(qk)/qk) - if (disp == 'SS'): + if disp == 'SS': w0 = coeff[0]*(1.0-math.exp(coeff[1]*q02)) w0.append(w*0.001) #convert from mmeV to meV e0.append(0.0) @@ -67,7 +67,7 @@ def CheckCoeff(disp,coeff): error = disp + ' coeff 2 is zero' logger.notice('ERROR *** '+error) sys.exit(error) - if (disp == 'Poly'): + if disp == 'Poly': cc = coeff[0]+coeff[1]+coeff[2]+coeff[3]+coeff[4] if cc < 1e-8: error = 'Poly coeffs all zero' @@ -131,7 +131,7 @@ def ReadSqw(sqw,Verbose): sys.exit(error) nel= nw+1 for n in range(0,nw): - if (Xw[n] < dw): + if Xw[n] < dw: nel = n dq = Q[1]-Q[0] if dq < 1e-5: @@ -244,7 +244,7 @@ def MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): idet = m+1 kill,totals,iw,energy,scat1,scatm,RR,Sqw=muscat.muscat_data(idet,lpt,llpt,sqw,lsqw,rinstr,nran,\ ijeom,rgeom,sam,ims,dqw,Q_in,Sqw_in) - if (kill != 0): + if kill != 0: error = 'Muscat error code : '+str(kill) logger.notice(error) sys.exit(error) @@ -366,7 +366,7 @@ def MuscatDataStart(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): EndTime('Muscat Data') def plotMuscat(inWS,spec_list,Plot): - if (Plot == 'Totals' or Plot == 'All'): + if Plot == 'Totals' or Plot == 'All': tot_plot=mp.plotSpectrum(inWS+'_Totals',spec_list) - if (Plot == 'Scat1' or Plot == 'All'): + if Plot == 'Scat1' or Plot == 'All': mp.importMatrixWorkspace(inWS+'_1').plotGraph2D() diff --git a/Code/Mantid/scripts/Inelastic/IndirectNeutron.py b/Code/Mantid/scripts/Inelastic/IndirectNeutron.py index a217d099b527..e2adb61045ca 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectNeutron.py +++ b/Code/Mantid/scripts/Inelastic/IndirectNeutron.py @@ -95,7 +95,7 @@ def ReadIbackGroup(a,first): #read Ascii block of spec def getFilePath(run,ext,instr): path = None fname = None - if(os.path.isfile(run)): + if os.path.isfile(run): #using full file path path = run #base name less extension @@ -256,7 +256,7 @@ def IbackStart(instr,run,ana,refl,rejectZ,useM,mapPath,Plot,Save): #Ascii s opath = os.path.join(workdir,outWS+'.nxs') SaveNexusProcessed(InputWorkspace=outWS, Filename=opath) logger.information('Output file : ' + opath) - if (Plot): + if Plot: plotForce(outWS,Plot) EndTime('Iback') @@ -348,7 +348,7 @@ def InxStart(instr,run,ana,refl,rejectZ,useM,mapPath,Plot,Save): opath = os.path.join(workdir,outWS+'.nxs') SaveNexusProcessed(InputWorkspace=outWS, Filename=opath) logger.information('Output file : ' + opath) - if (Plot): + if Plot: plotForce(outWS,Plot) EndTime('Inx') @@ -379,7 +379,7 @@ def ReadMap(path): logger.information('Map file : ' + path +' ; spectra = ' +str(lasc-1)) val = ExtractInt(asc[0]) numb = val[0] - if (numb != (lasc-1)): + if numb != (lasc-1): error = 'Number of lines not equal to number of spectra' logger.error(error) sys.exit(error) @@ -407,7 +407,7 @@ def UseMap(inWS,map): logger.information('** spectrum '+str(n+1)+' skipped') def plotForce(inWS,Plot): - if (Plot == 'Spectrum' or Plot == 'Both'): + if Plot == 'Spectrum' or Plot == 'Both': nHist = mtd[inWS].getNumberHistograms() if nHist > 10 : nHist = 10 @@ -415,7 +415,7 @@ def plotForce(inWS,Plot): for i in range(0, nHist): plot_list.append(i) res_plot=mp.plotSpectrum(inWS,plot_list) - if (Plot == 'Contour' or Plot == 'Both'): + if Plot == 'Contour' or Plot == 'Both': cont_plot=mp.importMatrixWorkspace(inWS).plotGraph2D() def ChangeAngles(inWS,instr,theta): @@ -595,7 +595,7 @@ def IN13Read(instr,run,ana,refl,Plot,Save): #Ascii start routine opath = os.path.join(workdir,outWS+'.nxs') SaveNexusProcessed(InputWorkspace=outWS, Filename=opath) logger.information('Output file : ' + opath) - if (Plot != 'None'): + if Plot != 'None': plotForce(outWS,Plot) return outWS diff --git a/Code/Mantid/scripts/Inelastic/inelastic_indirect_reducer.py b/Code/Mantid/scripts/Inelastic/inelastic_indirect_reducer.py index 09561f344fc5..26702c6cd4bf 100644 --- a/Code/Mantid/scripts/Inelastic/inelastic_indirect_reducer.py +++ b/Code/Mantid/scripts/Inelastic/inelastic_indirect_reducer.py @@ -109,7 +109,7 @@ def _setup_steps(self): self.append_step(step) # The "SaveItem" step saves the files in the requested formats. - if (len(self._save_formats) > 0): + if len(self._save_formats) > 0: step = steps.SaveItem() step.set_formats(self._save_formats) step.set_save_to_cm_1(self._save_to_cm_1) diff --git a/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py b/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py index 9ab1b09ee8d6..d0248d8f88e9 100644 --- a/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py +++ b/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py @@ -68,7 +68,7 @@ def execute(self, reducer, file_ws): if ( self._sum ) and ( len(self._data_files) > 1 ): ## Sum files merges = [] - if ( self._multiple_frames ): + if self._multiple_frames : self._sum_chopped(wsname) else: self._sum_regular(wsname) @@ -139,7 +139,7 @@ def _load_single_file(self, filename, output_ws): else: self._multiple_frames = False - if ( self._multiple_frames ): + if self._multiple_frames : workspaces = mtd[output_ws].getNames() else: workspaces = [output_ws] @@ -226,7 +226,7 @@ def _require_chop_data(self, ws): 'Workflow.ChopDataIfGreaterThan')[0] except IndexError: return False - if ( mtd[ws].readX(0)[mtd[ws].blocksize()] > cdigt ): + if mtd[ws].readX(0)[mtd[ws].blocksize()] > cdigt : return True else: return False @@ -257,7 +257,7 @@ def __init__(self, MultipleFrames=False): def execute(self, reducer, file_ws): - if (self._multiple_frames): + if self._multiple_frames: try: workspaces = mtd[file_ws].getNames() except AttributeError: @@ -270,7 +270,7 @@ def execute(self, reducer, file_ws): except IndexError: msk = 'None' - if (msk != 'IdentifyNoisyDetectors'): + if msk != 'IdentifyNoisyDetectors': return temp_ws_mask = '__temp_ws_mask' @@ -279,7 +279,7 @@ def execute(self, reducer, file_ws): nhist = ws.getNumberHistograms() for i in range(0, nhist): - if (ws.readY(i)[0] == 0.0): + if ws.readY(i)[0] == 0.0: self._masking_detectors.append(i) DeleteWorkspace(Workspace=temp_ws_mask) @@ -307,7 +307,7 @@ def __init__(self, MultipleFrames=False): self._background_end = None def execute(self, reducer, file_ws): - if ( self._multiple_frames ): + if self._multiple_frames : try: workspaces = mtd[file_ws].getNames() except AttributeError: @@ -340,7 +340,7 @@ def __init__(self): def execute(self, reducer, file_ws): if self._calib_workspace is None: # No calibration workspace set return - if ( self._multiple_frames ): + if self._multiple_frames : try: workspaces = mtd[file_ws].getNames() except AttributeError: @@ -377,7 +377,7 @@ def __init__(self, MultipleFrames=False): def execute(self, reducer, file_ws): """Does everything we want to with the Monitor. """ - if ( self._multiple_frames ): + if self._multiple_frames : try: workspaces = mtd[file_ws].getNames() except AttributeError: @@ -414,14 +414,14 @@ def _need_to_unwrap(self, ws): 'Workflow.UnwrapMonitor')[0] except IndexError: return False # Default it to not unwrap - if ( unwrap == 'Never' ): + if unwrap == 'Never' : return False - elif ( unwrap == 'Always' ): + elif unwrap == 'Always' : return True - elif ( unwrap == 'BaseOnTimeRegime' ): + elif unwrap == 'BaseOnTimeRegime' : SpecMon = mtd[ws+'_mon'].readX(0)[0] SpecDet = mtd[ws].readX(0)[0] - if ( SpecMon == SpecDet ): + if SpecMon == SpecDet : return True else: return False @@ -462,7 +462,7 @@ def _monitor_efficiency(self, monitor): raise ValueError('Unable to retrieve monitor thickness, area and '\ 'attenuation from Instrument Parameter file.') else: - if ( area == -1 or thickness == -1 or attenuation == -1): + if area == -1 or thickness == -1 or attenuation == -1: return OneMinusExponentialCor(InputWorkspace=monitor,OutputWorkspace= monitor,C= (attenuation * thickness),C1= area) @@ -494,7 +494,7 @@ def __init__(self, MultipleFrames=False, EMode="Indirect"): self._emode = EMode def execute(self, reducer, file_ws): - if ( self._multiple_frames ): + if self._multiple_frames : try: workspaces = mtd[file_ws].getNames() except AttributeError: @@ -545,7 +545,7 @@ def _create_scaling_workspace(self, wsgroup, merged): lowest = 0 highest = 0 for ws in wsgroup: - if ( unit == '' ): + if unit == '' : unit = mtd[ws].getAxis(0).getUnit().unitID() low = mtd[ws].dataX(0)[0] high = mtd[ws].dataX(0)[mtd[ws].blocksize()-1] @@ -564,7 +564,7 @@ def _create_scaling_workspace(self, wsgroup, merged): def _ws_in_range(self, ranges, xval): result = 0 for range in ranges: - if ( xval >= range[0] and xval <= range[1] ): result += 1 + if xval >= range[0] and xval <= range[1] : result += 1 return result class ConvertToCm1(ReductionStep): @@ -584,7 +584,7 @@ def execute(self, reducer, file_ws): if self._save_to_cm_1 == False: return - if ( self._multiple_frames ): + if self._multiple_frames : try: workspaceNames = mtd[file_ws].getNames() except AttributeError: @@ -614,7 +614,7 @@ def __init__(self, MultipleFrames=False): self._multiple_frames = MultipleFrames def execute(self, reducer, file_ws): - if ( self._multiple_frames ): + if self._multiple_frames : try: workspaces = mtd[file_ws].getNames() except AttributeError: @@ -654,7 +654,7 @@ def _rebin_mf(self, workspaces): nbins = mtd[ws].blocksize() if nbins > nbin: nbin = nbins for ws in workspaces: - if (mtd[ws].blocksize() == nbin): + if mtd[ws].blocksize() == nbin: Rebin(InputWorkspace=ws,OutputWorkspace= ws,Params= self._rebin_string) else: Rebin(InputWorkspace=ws,OutputWorkspace= ws,Params= rstwo) @@ -716,7 +716,7 @@ def execute(self, reducer, file_ws): correction = 11.606 / ( 2 * self._temp ) - if ( self._multiple_frames ): + if self._multiple_frames : workspaces = mtd[file_ws].getNames() else: workspaces = [file_ws] @@ -742,7 +742,7 @@ def execute(self, reducer, file_ws): if self._scale_factor is None: # Scale factor is the default value, 1.0 return - if ( self._multiple_frames ): + if self._multiple_frames : workspaces = mtd[file_ws].getNames() else: workspaces = [file_ws] diff --git a/Code/Mantid/scripts/Inelastic/msg_reducer.py b/Code/Mantid/scripts/Inelastic/msg_reducer.py index 235d88a596a2..df597f58c3dd 100644 --- a/Code/Mantid/scripts/Inelastic/msg_reducer.py +++ b/Code/Mantid/scripts/Inelastic/msg_reducer.py @@ -48,7 +48,7 @@ def pre_process(self): self._multiple_frames = loadData.is_multiple_frames() - if( self._info_table_props is not None ): + if self._info_table_props is not None : wsNames = loadData.get_ws_list().keys() wsNameList = ", ".join(wsNames) propsList = ", ".join(self._info_table_props) @@ -58,7 +58,7 @@ def pre_process(self): LogPropertyNames=propsList, GroupPolicy="First") - if ( self._sum ): + if self._sum : self._data_files = loadData.get_ws_list() self._setup_steps() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_data_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_data_script.py index 357266aa9e57..5a8fefbf9452 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_data_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_data_script.py @@ -112,7 +112,7 @@ def to_script(self, for_automated_reduction=False): # sf configuration file # if self.scaling_factor_file != '': - if (self.scaling_factor_file_flag): + if self.scaling_factor_file_flag: script += "ScalingFactorFile='%s',\n" % str(self.scaling_factor_file) else: script += "ScalingFactorFile='',\n" @@ -227,12 +227,12 @@ def from_xml_element(self, instrument_dom): #data metadata _tthd_value = BaseScriptElement.getStringElement(instrument_dom, "tthd_value") - if (_tthd_value == ''): + if _tthd_value == '': _tthd_value = 'N/A' self.tthd_value = _tthd_value _ths_value = BaseScriptElement.getStringElement(instrument_dom, "ths_value") - if (_ths_value == ''): + if _ths_value == '': _ths_value = 'N/A' self.ths_value = _ths_value diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py index e747eaa22002..40663e98f6bc 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py @@ -141,7 +141,7 @@ def to_script(self): if self.masked_side is not None: script += "MaskDetectorSide('%s')\n" % str(self.masked_side) # Edges - if (self.top != 0 or self.bottom != 0 or self.left != 0 or self.right != 0): + if self.top != 0 or self.bottom != 0 or self.left != 0 or self.right != 0: script += "Mask(nx_low=%d, nx_high=%d, ny_low=%d, ny_high=%d)\n" % (self.left, self.right, self.bottom, self.top) # Rectangles for item in self.shapes: diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py index 8099643ef3e7..6d4731dea439 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py @@ -278,7 +278,7 @@ def _run_number_changed(self): # 3. Update the log name combo box if metaws is None: - self._content.info_text_browser.setText( + self._content.info_text_browser.setText(\ str("Error! Failed to load data file %s. Current working directory is %s. " % (eventnxsname, os.getcwd()))) else: self._metaws = metaws diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_absolute_units.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_absolute_units.py index a1bd1a8913dd..6a87cf213116 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_absolute_units.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_absolute_units.py @@ -1,6 +1,5 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore -from functools import partial +from PyQt4 import QtGui, QtCore from reduction_gui.widgets.base_widget import BaseWidget from reduction_gui.reduction.inelastic.dgs_absolute_units_script import AbsoluteUnitsScript import reduction_gui.widgets.util as util @@ -33,16 +32,16 @@ def __init__(self, parent=None): def initialize_content(self): # Constraints - for widget in [ - self._content.ei_edit, - self._content.van_mass_edit, - self._content.sample_mass_edit, - self._content.sample_rmm_edit, - self._content.median_test_high_edit, - self._content.median_test_low_edit, - self._content.median_test_out_high_edit, - self._content.median_test_out_low_edit, - self._content.errorbar_crit_edit, + for widget in [\ + self._content.ei_edit,\ + self._content.van_mass_edit,\ + self._content.sample_mass_edit,\ + self._content.sample_rmm_edit,\ + self._content.median_test_high_edit,\ + self._content.median_test_low_edit,\ + self._content.median_test_out_high_edit,\ + self._content.median_test_out_low_edit,\ + self._content.errorbar_crit_edit,\ ]: dvp = QtGui.QDoubleValidator(widget) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_diagnose_detectors.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_diagnose_detectors.py index cf561e29be5e..a8ed11691da5 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_diagnose_detectors.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_diagnose_detectors.py @@ -1,6 +1,5 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore -from functools import partial +from PyQt4 import QtGui, QtCore from reduction_gui.widgets.base_widget import BaseWidget from reduction_gui.reduction.inelastic.dgs_diagnose_detectors_script import DiagnoseDetectorsScript import reduction_gui.widgets.util as util @@ -33,16 +32,16 @@ def __init__(self, parent=None): def initialize_content(self): # Constraints - for widget in [ - self._content.median_test_high_edit, - self._content.median_test_low_edit, - self._content.median_test_out_high_edit, - self._content.median_test_out_low_edit, - self._content.errorbar_crit_edit, - self._content.ratio_var_crit_edit, - self._content.sambkg_median_test_high_edit, - self._content.sambkg_median_test_low_edit, - self._content.sambkg_errorbar_crit_edit + for widget in [\ + self._content.median_test_high_edit,\ + self._content.median_test_low_edit,\ + self._content.median_test_out_high_edit,\ + self._content.median_test_out_low_edit,\ + self._content.errorbar_crit_edit,\ + self._content.ratio_var_crit_edit,\ + self._content.sambkg_median_test_high_edit,\ + self._content.sambkg_median_test_low_edit,\ + self._content.sambkg_errorbar_crit_edit\ ]: dvp = QtGui.QDoubleValidator(widget) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py index a2666009a994..cf30672d6521 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py @@ -64,7 +64,7 @@ def getPixelRange(self): def calculatePixelRange(self): nbr_x = len(self.x_list) - if ((nbr_x % 304) == 0): + if (nbr_x % 304) == 0: _list = self.y_list #REF_L else: _list = self.x_list #REF_M diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py index 9303985ec0d0..d1a8c68ff43d 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py @@ -1,5 +1,5 @@ -#pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore +#pylint: disable=invalid-name,unused-import +from PyQt4 import QtGui, QtCore import reduction_gui.widgets.util as util import math import os @@ -212,9 +212,7 @@ def getMetadata(self,file): This retrieve the metadata from the data event NeXus file """ _full_file_name = file - tmpWks = LoadEventNexus(Filename=_full_file_name,\ -# OutputWorkspace='tmpWks',\ - MetaDataOnly='1') + tmpWks = LoadEventNexus(Filename=_full_file_name,MetaDataOnly='1') #mt1 = mtd['tmpWks'] #mt_run = mt1.getRun() @@ -320,19 +318,19 @@ def _smooth_x_axis(self, x_axis, y_axis, e_axis): sz = len(x_axis) i=0 - while (i < sz-1): + while i < sz-1: _left_x = x_axis[i] _right_x = x_axis[i+1] bCalAverage = False - if (_left_x == _right_x): + if _left_x == _right_x: bCalAverage = True else: _left_x = math.fabs(_left_x) _right_x = math.fabs(_right_x) _relative_diff = (_left_x - _right_x) / (_left_x + _right_x) - if (math.fabs(_relative_diff <= _precision)): + if math.fabs(_relative_diff <= _precision): bCalAverage = True _left_e = e_axis[i] @@ -346,7 +344,7 @@ def _smooth_x_axis(self, x_axis, y_axis, e_axis): _right_e2 = _right_e * _right_e _right_y = y_axis[i+1] - if (_left_e2 == 0. or _right_e2 == 0.): + if _left_e2 == 0. or _right_e2 == 0.: _y = 0. _e = 0. else: @@ -386,14 +384,14 @@ def weightedMean(self, data_array, error_array): # calculate the numerator of mean dataNum = 0 for i in range(sz): - if not (data_array[i] == 0): + if not data_array[i] == 0: tmpFactor = float(data_array[i]) / float((pow(error_array[i],2))) dataNum += tmpFactor # calculate denominator dataDen = 0 for i in range(sz): - if not (error_array[i] == 0): + if not error_array[i] == 0: tmpFactor = 1./float((pow(error_array[i],2))) dataDen += tmpFactor @@ -542,7 +540,7 @@ def _produce_y_of_same_x_(self, isUsingLessErrorValue): if data_y[j]>0 and data_y_i[j]>0: if isUsingLessErrorValue: - if (data_e[j] > data_e_i[j]): + if data_e[j] > data_e_i[j]: data_y[j] = data_y_i[j] data_e[j] = data_e_i[j] else: @@ -571,7 +569,7 @@ def _create_ascii_clicked(self): #retrieve name of the output file file_name = QtGui.QFileDialog.getSaveFileName(self, "Select or define a ASCII file name", default_file_name, "(*.txt)") - if (str(file_name).strip() == ''): + if str(file_name).strip() == '': return #check the status of the 4th column switch @@ -619,7 +617,7 @@ def _create_ascii_clicked(self): sz = len(x_axis)-1 for i in range(sz): # do not display data where R=0 - if (y_axis[i] > 1e-15): + if y_axis[i] > 1e-15: _line = str(x_axis[i]) _line += ' ' + str(y_axis[i]) _line += ' ' + str(e_axis[i]) @@ -639,7 +637,7 @@ def browse_config_file_name(self): ''' try: file_name = QtGui.QFileDialog.getOpenFileName(self, "Select a SF configuration file", "", "(*.cfg)") - if (str(file_name).strip() != ''): + if str(file_name).strip() != '': if os.path.isfile(file_name): self._summary.cfg_scaling_factor_file_name.setText(file_name) self.retrieve_list_of_incident_medium(file_name) @@ -919,14 +917,14 @@ def _norm_clicked(self, is_checked): self._summary.norm_peak_to_pixel.setEnabled(is_checked) self._summary.norm_background_switch.setEnabled(is_checked) - if (not(is_checked)): + if not is_checked: self._norm_background_clicked(False) else: NormBackFlag = self._summary.norm_background_switch.isChecked() self._norm_background_clicked(NormBackFlag) self._summary.norm_low_res_range_switch.setEnabled(is_checked) - if (not(is_checked)): + if not is_checked: self._norm_low_res_clicked(False) else: LowResFlag = self._summary.norm_low_res_range_switch.isChecked() @@ -1061,7 +1059,7 @@ def _plot_data_count_vs_tof_2d(self): basename = os.path.basename(file_path) ws_base = "__%s" % basename - if (self.instrument_name == 'REF_L'): + if self.instrument_name == 'REF_L': ws_output_base = "Pixel Y vs TOF" + " - " + basename else: ws_output_base = "Pixel X vs TOF" + " - " + basename @@ -1311,7 +1309,7 @@ def _add_data(self): state.q_step = float(_q_step) state.scaling_factor_file = self._summary.cfg_scaling_factor_file_name.text() - if (self._summary.use_sf_config_switch.isChecked()): + if self._summary.use_sf_config_switch.isChecked(): state.scaling_factor_file_flag = True else: state.scaling_factor_file_flag = False @@ -1345,7 +1343,7 @@ def _add_data(self): item_widget = QtGui.QListWidgetItem(run_numbers, self._summary.angle_list) state.scaling_factor_file = self._summary.cfg_scaling_factor_file_name.text() - if (self._summary.use_sf_config_switch.isChecked()): + if self._summary.use_sf_config_switch.isChecked(): state.scaling_factor_file_flag = True else: state.scaling_factor_file_flag = False diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py index 7e781fee6ab0..db89665db9b7 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py @@ -61,7 +61,7 @@ def __init__(self, wk1=None, wk2=None, parent=None, type='data'): self.y2 = mt2.readY(0)[:] self.dataType = type - if (type == 'data'): + if type == 'data': self._peakFromValue=float(parent._summary.data_peak_from_pixel.text()) self._peakToValue=float(parent._summary.data_peak_to_pixel.text()) self._backFromValue=float(parent._summary.data_background_from_pixel1.text()) @@ -253,7 +253,7 @@ def peak_input_changed(self): def update_peak_back_selection_mode(self, bPeak): """Make sure that only 1 peak/back selection is activated at the same time""" self.peakSwitch.setChecked(bPeak) - self.backSwitch.setChecked(not(bPeak)) + self.backSwitch.setChecked(not bPeak) if bPeak: # class_name = self.from_peak_input.__class__.__name__ @@ -276,7 +276,7 @@ def update_back_selection_mode(self): def update_linear_log_selection_mode(self, bLinear): """Make sure that only linear or log are selected at the same time""" self.linear.setChecked(bLinear) - self.log.setChecked(not(bLinear)) + self.log.setChecked(not bLinear) def update_linear_selection_mode(self): self.update_linear_log_selection_mode(True) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py index 6871f9d0befa..b20f3a35624f 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py @@ -596,14 +596,14 @@ def _norm_clicked(self, is_checked): self._summary.norm_peak_to_pixel.setEnabled(is_checked) self._summary.norm_background_switch.setEnabled(is_checked) - if (not(is_checked)): + if not is_checked: self._norm_background_clicked(False) else: NormBackFlag = self._summary.norm_background_switch.isChecked() self._norm_background_clicked(NormBackFlag) self._summary.norm_low_res_range_switch.setEnabled(is_checked) - if (not(is_checked)): + if not is_checked: self._norm_low_res_clicked(False) else: LowResFlag = self._summary.norm_low_res_range_switch.isChecked() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py index 494bdae69bb5..7d7fa32c1abc 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py @@ -135,7 +135,7 @@ def browse_config_file_name(self): Define configuration file name ''' file_name = QtGui.QFileDialog.getOpenFileName(self, "Select config file name", "", "(*.cfg)") - if (str(file_name).strip() != ''): + if str(file_name).strip() != '': self._summary.cfg_scaling_factor_file_name.setText(file_name) self.display_preview_config_file() @@ -289,7 +289,7 @@ def _add_data(self): in_list = False # Check whether it's already in the list run_numbers = self._summary.data_run_number_edit.text() - if (run_numbers == ''): + if run_numbers == '': return list_items = self._summary.angle_list.findItems(run_numbers, QtCore.Qt.MatchFixedString) @@ -404,7 +404,7 @@ def set_editing_state(self, state): self._summary.tof_max.setText(str(state.tof_max)) self._summary.cfg_scaling_factor_file_name.setText(str(state.scaling_factor_file)) - if (state.scaling_factor_file != ''): + if state.scaling_factor_file != '': self.display_preview_config_file() self._summary.data_run_number_edit.setText(str(state.data_file)) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py index 065345064a76..a6b69395b762 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py @@ -462,14 +462,14 @@ def _norm_clicked(self, is_checked): self._summary.norm_peak_to_pixel.setEnabled(is_checked) self._summary.norm_background_switch.setEnabled(is_checked) - if (not(is_checked)): + if not is_checked: self._norm_background_clicked(False) else: NormBackFlag = self._summary.norm_background_switch.isChecked() self._norm_background_clicked(NormBackFlag) self._summary.norm_low_res_range_switch.setEnabled(is_checked) - if (not(is_checked)): + if not is_checked: self._norm_low_res_clicked(False) else: LowResFlag = self._summary.norm_low_res_range_switch.isChecked() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/util.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/util.py index 862e7528df74..0ec9cb1e3cd8 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/util.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/util.py @@ -38,7 +38,7 @@ def _check_and_get_float_line_edit(line_edit, min=None): value = 0.0 try: value = float(line_edit.text()) - if (min is None or value>min): + if min is None or value>min: line_edit.setStyleSheet(CSS_DEFAULT) else: line_edit.setStyleSheet(CSS_INVALID) diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py index 128e085c06d4..0789e8d3c743 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py @@ -83,11 +83,11 @@ def __init__(self): self.live_method = settings.value(self.__live_data_method_key, "", type=str) self.live_freq = settings.value(self.__live_data_frequency_key, 0, type=float) - if not (self.live_freq): + if not self.live_freq: logger.information("No settings were found for Update frequency of loading live data, Loading default of 60 seconds") self.live_freq = float(60) settings.setValue(self.__live_data_frequency_key, self.live_freq) - if not (self.live_method): + if not self.live_method: logger.information("No settings were found for Accumulation Method of loading live data, Loading default of \"Add\"") self.live_method = "Add" settings.setValue(self.__live_data_method_key, self.live_method) @@ -280,12 +280,12 @@ def _initialise_table(self): for column in range(self.tableMain.columnCount()): for row in range(self.tableMain.rowCount()): - if (column in self.run_cols): + if column in self.run_cols: item = QtGui.QTableWidgetItem() item.setText('') item.setToolTip('Runs can be colon delimited to coadd them') self.tableMain.setItem(row, column, item) - elif (column in self.angle_cols): + elif column in self.angle_cols: item = QtGui.QTableWidgetItem() item.setText('') item.setToolTip('Angles are in degrees') @@ -439,15 +439,15 @@ def _autofill(self): howMany = len(self.tableMain.selectedItems()) for cell in self.tableMain.selectedItems(): sum = sum + self.tableMain.row(cell) - if (howMany): + if howMany: selectedrow = self.tableMain.row(self.tableMain.selectedItems()[0]) - if (sum / howMany == selectedrow): + if sum / howMany == selectedrow: startrow = selectedrow + 1 filled = 0 for cell in self.tableMain.selectedItems(): row = startrow txt = cell.text() - while (self.tableMain.item(row, 0).text() != ''): + while self.tableMain.item(row, 0).text() != '': item = QtGui.QTableWidgetItem() item.setText(txt) self.tableMain.setItem(row, self.tableMain.column(cell), item) @@ -686,22 +686,22 @@ def _process(self): overlapLow = [] overlapHigh = [] theta = [0, 0, 0] - if (self.tableMain.item(row, 0).text() != ''): + if self.tableMain.item(row, 0).text() != '': self.statusMain.showMessage("Processing row: " + str(row + 1)) logger.debug("Processing row: " + str(row + 1)) for i in range(3): run_entry = str(self.tableMain.item(row, i * 5).text()) - if (run_entry != ''): + if run_entry != '': runno.append(run_entry) ovLow = str(self.tableMain.item(row, (i * 5) + 3).text()) - if (ovLow != ''): + if ovLow != '': overlapLow.append(float(ovLow)) ovHigh = str(self.tableMain.item(row, (i * 5) + 4).text()) - if (ovHigh != ''): + if ovHigh != '': overlapHigh.append(float(ovHigh)) # Determine resolution - if (self.tableMain.item(row, 15).text() == ''): + if self.tableMain.item(row, 15).text() == '': loadedRun = None if load_live_runs.is_live_run(runno[0]): loadedRun = load_live_runs.get_live_data(config['default.instrument'], frequency = self.live_freq, accumulation = self.live_method) @@ -761,16 +761,16 @@ def _process(self): qmin = round(qmin, 3) qmax = round(qmax, 3) wksp.append(wq.name()) - if (self.tableMain.item(row, i * 5 + 1).text() == ''): + if self.tableMain.item(row, i * 5 + 1).text() == '': item = QtGui.QTableWidgetItem() item.setText(str(theta)) self.tableMain.setItem(row, i * 5 + 1, item) - if (self.tableMain.item(row, i * 5 + 3).text() == ''): + if self.tableMain.item(row, i * 5 + 3).text() == '': item = QtGui.QTableWidgetItem() item.setText(str(qmin)) self.tableMain.setItem(row, i * 5 + 3, item) overlapLow.append(qmin) - if (self.tableMain.item(row, i * 5 + 4).text() == ''): + if self.tableMain.item(row, i * 5 + 4).text() == '': item = QtGui.QTableWidgetItem() if i == len(runno) - 1: # allow full high q-range for last angle @@ -786,18 +786,18 @@ def _process(self): Scale(InputWorkspace=wksp[i], OutputWorkspace=wksp[i], Factor=1 / float(self.tableMain.item(row, self.scale_col).text())) if self.__checked_row_stiched(row): - if (len(runno) == 1): + if len(runno) == 1: logger.notice("Nothing to combine for processing row : " + str(row)) else: w1 = getWorkspace(wksp[0]) w2 = getWorkspace(wksp[-1]) - if (len(runno) == 2): + if len(runno) == 2: outputwksp = runno[0] + '_' + runno[1][3:5] else: outputwksp = runno[0] + '_' + runno[-1][3:5] begoverlap = w2.readX(0)[0] # get Qmax - if (self.tableMain.item(row, i * 5 + 4).text() == ''): + if self.tableMain.item(row, i * 5 + 4).text() == '': overlapHigh = 0.3 * max(w1.readX(0)) Qmin = min(w1.readX(0)) @@ -881,7 +881,7 @@ def _plot(self, plotbutton): self.__graphs[wksp[i]] = base_graph titl = groupGet(ws_name_binned, 'samp', 'run_title') - if (type(titl) == str): + if type(titl) == str: base_graph.activeLayer().setTitle(titl) base_graph.activeLayer().setAxisScale(Layer.Left, Imin * 0.1, Imax * 10, Layer.Log10) base_graph.activeLayer().setAxisScale(Layer.Bottom, Qmin * 0.9, Qmax * 1.1, Layer.Log10) @@ -890,7 +890,7 @@ def _plot(self, plotbutton): # Create and plot stitched outputs if self.__checked_row_stiched(row): - if (len(runno) == 2): + if len(runno) == 2: outputwksp = runno[0] + '_' + runno[1][3:5] else: outputwksp = runno[0] + '_' + runno[2][3:5] @@ -1044,7 +1044,7 @@ def _save_table_contents(self, filename): rowtext = [] for column in range(self.tableMain.columnCount() - 2): rowtext.append(self.tableMain.item(row, column).text()) - if (len(rowtext) > 0): + if len(rowtext) > 0: writer.writerow(rowtext) self.current_table = filename logger.notice("Saved file to " + filename) @@ -1133,7 +1133,7 @@ def _load_table(self): reader = csv.reader(open(filename, "rb")) row = 0 for line in reader: - if (row < 100): + if row < 100: for column in range(self.tableMain.columnCount() - 2): item = QtGui.QTableWidgetItem() item.setText(line[column]) @@ -1168,7 +1168,7 @@ def _reload_table(self): reader = csv.reader(open(filename, "rb")) row = 0 for line in reader: - if (row < 100): + if row < 100: for column in range(self.tableMain.columnCount() - 2): item = QtGui.QTableWidgetItem() item.setText(line[column]) diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py index 051187316c18..536297b780ae 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py @@ -70,7 +70,7 @@ def __update_groupTOF_method(self, checked): self.__group_tof_workspaces = checked def icatDownload(self): - return (self.__icat_download) + return self.__icat_download def groupTOFWorkspaces(self): return self.__group_tof_workspaces diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py index ad186ca6bfdc..6dabce7fe2a5 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py @@ -277,7 +277,7 @@ def populateList(self): self.listWidget.setCurrentItem(self.listWidget.item(0)) # try to get correct user directory currentInstrument=config['default.instrument'] - if (self.SavePath!=''): + if self.SavePath!='': self.lineEdit.setText(self.SavePath) else: if self.__has_mount_point: @@ -318,23 +318,23 @@ def buttonClickHandler1(self): for idx in self.listWidget.selectedItems(): runlist=parseRunList(str(self.spectraEdit.text())) fname=os.path.join(self.lineEdit.text(),prefix + idx.text()) - if (self.comboBox.currentIndex() == 0): + if self.comboBox.currentIndex() == 0: print "Custom Ascii format" - if (self.radio1.isChecked()): + if self.radio1.isChecked(): sep=',' - elif (self.radio2.isChecked()): + elif self.radio2.isChecked(): sep=' ' - elif (self.radio3.isChecked()): + elif self.radio3.isChecked(): sep='\t' else: sep=' ' saveCustom(idx,fname,sep,self.listWidget2.selectedItems(),self.titleCheckBox.isChecked(),self.xErrorCheckBox.isChecked()) - elif (self.comboBox.currentIndex() == 1): + elif self.comboBox.currentIndex() == 1: print "Not yet implemented!" - elif (self.comboBox.currentIndex() == 2): + elif self.comboBox.currentIndex() == 2: print "ANSTO format" saveANSTO(idx,fname) - elif (self.comboBox.currentIndex() == 3): + elif self.comboBox.currentIndex() == 3: print "ILL MFT format" saveMFT(idx,fname,self.listWidget2.selectedItems()) # for idx in self.listWidget.selectedItems(): @@ -378,16 +378,16 @@ def groupGet(wksp, whattoget, field=''): returns information about instrument or sample details for a given workspace wksp, also if the workspace is a group (info from first group element) ''' - if (whattoget == 'inst'): + if whattoget == 'inst': if isinstance(mtd[wksp], WorkspaceGroup): return mtd[wksp + '_1'].getInstrument() else: return mtd[wksp].getInstrument() - elif (whattoget == 'samp' and field != ''): + elif whattoget == 'samp' and field != '': if isinstance(mtd[wksp], WorkspaceGroup): try: log = mtd[wksp + '_1'].getRun().getLogData(field).value - if (type(log) is int or type(log) is str): + if type(log) is int or type(log) is str: res = log else: res = log[len(log) - 1] @@ -397,7 +397,7 @@ def groupGet(wksp, whattoget, field=''): else: try: log = mtd[wksp].getRun().getLogData(field).value - if (type(log) is int or type(log) is str): + if type(log) is int or type(log) is str: res = log else: res = log[len(log) - 1] @@ -405,7 +405,7 @@ def groupGet(wksp, whattoget, field=''): res = 0 print "Block " + field + " not found." return res - elif (whattoget == 'wksp'): + elif whattoget == 'wksp': if isinstance(mtd[wksp], WorkspaceGroup): return mtd[wksp + '_1'].getNumberHistograms() else: diff --git a/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py b/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py index b4e5b77b847f..97556c8b8122 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py +++ b/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py @@ -115,7 +115,7 @@ def addDetectorPixels(self, name, r=[], theta=[], phi=[], names=[], energy=[]): for i in range(len(r)): for j in range(len(r[i])): - if (str(r[i][j]) != "nan"): + if str(r[i][j]) != "nan": basecomponent = self._append_child("component", type_element, type="pixel") location_element = self._append_child("location", basecomponent,r=str(r[i][j]),\ t=str(theta[i][j]), p=str(phi[i][j]), name=str(names[i][j])) @@ -128,7 +128,7 @@ def addDetectorPixelsIdList(self, name, r=[], names=[]): component = self._append_child("idlist", self._root, idname=name) for i in range(len(r)): for j in range(len(r[i])): - if (str(r[i][j]) != "nan"): + if str(r[i][j]) != "nan": self._append_child("id", component, val=str(names[i][j])) def addMonitors(self, distance=[], names=[]): diff --git a/Code/Mantid/scripts/PyChop/PyChop.py b/Code/Mantid/scripts/PyChop/PyChop.py index 9498d3a32069..a869bbdaefb0 100644 --- a/Code/Mantid/scripts/PyChop/PyChop.py +++ b/Code/Mantid/scripts/PyChop/PyChop.py @@ -433,7 +433,7 @@ def van_var(*args): #! chopper: tsqchp,ifail=tchop(omega, ei) ifail - if (ifail <> 0): + if ifail <> 0: tsqchp = 0.0 @@ -468,7 +468,7 @@ def tikeda(S1,S2,B1,B2,EMOD,ei): SIG=math.sqrt( (S1*S1) + ((S2*S2*81.8048)/ei) ) A = 4.37392e-4 * SIG * math.sqrt(ei) for j in range(len(ei)): - if (ei[j] > 130.0): + if ei[j] > 130.0: B[j]=B2 else: B[j]=B1 @@ -509,7 +509,7 @@ def tchop(omega,ei): w=omega ei=ei - if (p == 0.00 and R == 0.00 and rho == 0.00): + if p == 0.00 and R == 0.00 and rho == 0.00: ierr=1 tausqr = 0.00 @@ -523,12 +523,12 @@ def tchop(omega,ei): #! ------------------------------------- #for j in range(len(ei)): groot=0 - if (gammm >= 4.00): + if gammm >= 4.00: ierr=1 tausqr=0.00 else: ierr=0 - if (gammm <= 1.00): + if gammm <= 1.00: gsqr=(1.00-(gammm**2)**2 /10.00) / (1.00-(gammm**2)/6.00) else: groot=math.sqrt(gammm) @@ -772,7 +772,7 @@ def achop(ei,omega): #for j in range(numpy.size(ei)): groot=0 - if (gamm >= 4.00): + if gamm >= 4.00: f1=0 print 'no transmission at ', ei, 'meV at ',omega/(2*math.pi), 'Hz' else: diff --git a/Code/Mantid/scripts/PyChop/fluxGUI.py b/Code/Mantid/scripts/PyChop/fluxGUI.py index df654459f675..99fc48fc9e30 100644 --- a/Code/Mantid/scripts/PyChop/fluxGUI.py +++ b/Code/Mantid/scripts/PyChop/fluxGUI.py @@ -1,8 +1,6 @@ #pylint: disable=invalid-name -import sys from PyChop_LET_UI import Ui_MainWindow #import line for the UI python class from PyQt4 import QtCore, QtGui #import others if needed -import math from mantidplot import * from mantid import * diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py index 5b8bf98c7498..f92a97e05040 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py @@ -137,7 +137,7 @@ def convert(self, wavelength_min, wavelength_max, detector_workspace_indexes, mo _monitor_ws: A workspace of monitors """ # Sanity check inputs. - if(wavelength_min >= wavelength_max): + if wavelength_min >= wavelength_max: raise ValueError("Wavelength_min must be < wavelength_max min: %s, max: %s" % (wavelength_min, wavelength_max)) if correct_monitor and not all((bg_min, bg_max)): diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/load_live_runs.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/load_live_runs.py index 4af7dc825f57..2be3a6c4cb1b 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/load_live_runs.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/load_live_runs.py @@ -6,6 +6,6 @@ def get_live_data(instrument_name, frequency = 60, accumulation = "Add", output_ return ws def is_live_run(run): try: - return (int(run) is 0) + return int(run) is 0 except: return False diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py index 1e2a4500e629..999dd0a65df4 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py @@ -30,7 +30,7 @@ def addRuns(runlist,wname): #dae="ndx"+mtd.settings['default.instrument'].lower() dae="ndxoffspec" LoadDAE(DAEname=dae,OutputWorkspace=output,SpectrumMin="1") - if(mtd[output].isGroup()): + if mtd[output].isGroup(): for k in mtd[output].getNames(): mtd[k].setYUnit('Counts') else: @@ -57,7 +57,7 @@ def addRuns(runlist,wname): #dae="ndx"+mtd.settings['default.instrument'].lower() dae="ndxoffspec" LoadDAE(DAEname=dae,OutputWorkspace="wtemp",SpectrumMin="1") - if(mtd['wtemp'].isGroup()): + if mtd['wtemp'].isGroup(): for k in mtd['wtemp'].getNames(): mtd[k].setYUnit('Counts') else: @@ -264,7 +264,7 @@ def removeoutlayer(wksp): for i in range(nspec): for j in range(len(x)-1): y=a1.readY(i)[j] - if (y<2): + if y<2: a1.dataY(i)[j]=0.0 a1.dataE(i)[j]=0.0 @@ -298,13 +298,13 @@ def nrSESANSFn(runList,nameList,P0runList,P0nameList,minSpec,maxSpec,upPeriod,do GroupDetectors(InputWorkspace=i,OutputWorkspace=i,MapFile=mapfile) ConvertUnits(i,i,"Wavelength",AlignBins=1) Rebin(i,i,reb) - if (removeoutlayer != "0"): + if removeoutlayer != "0": removeoutlayer(i+"_1") removeoutlayer(i+"_2") CropWorkspace(i,i+"mon",StartWorkspaceIndex=mon_spec,EndWorkspaceIndex=mon_spec) if nspec == 245: CropWorkspace(i,i+"2ddet",StartWorkspaceIndex=4,EndWorkspaceIndex=243) - if (floodfile != "none"): + if floodfile != "none": floodnorm(i+"2ddet",floodfile) if nspec == 1030: CropWorkspace(i,i+"2ddet",StartWorkspaceIndex=3,EndWorkspaceIndex=124) @@ -317,7 +317,7 @@ def nrSESANSFn(runList,nameList,P0runList,P0nameList,minSpec,maxSpec,upPeriod,do if nspec > 4 and minSp != 3: Divide(i+"2ddet",i+"mon",i+"2dnorm") DeleteWorkspace(i+"mon") - if (diagnostics == "0"): + if diagnostics == "0": DeleteWorkspace(i+"det") DeleteWorkspace(i) Minus(i+"norm_"+upPeriod,i+"norm_"+downPeriod,"num") @@ -425,9 +425,9 @@ def nrSESANSFn(runList,nameList,P0runList,P0nameList,minSpec,maxSpec,upPeriod,do k=k+1 def nrCalcSEConst(RFFrequency,poleShoeAngle): - if (RFFrequency=="0.5"): + if RFFrequency=="0.5": B=0.53*34.288 - elif (RFFrequency=="1.0"): + elif RFFrequency=="1.0": B=34.288 else: B=2.0*34.288 @@ -475,7 +475,7 @@ def nrSESANSP0Fn(P0runList,P0nameList,minSpec,maxSpec,upPeriod,downPeriod,gparam else: CropWorkspace(i,i+"det",StartWorkspaceIndex=minSp,EndWorkspaceIndex=maxSp) Divide(i+"det",i+"mon",i+"norm") - if (diagnostics=="0"): + if diagnostics=="0": DeleteWorkspace(i+"mon") DeleteWorkspace(i+"det") DeleteWorkspace(i) @@ -483,7 +483,7 @@ def nrSESANSP0Fn(P0runList,P0nameList,minSpec,maxSpec,upPeriod,downPeriod,gparam Plus(i+"norm_2",i+"norm_1","den") Divide("num","den",i+"pol") ReplaceSpecialValues(i+"pol",i+"pol",0.0,0.0,0.0,0.0) - if (diagnostics=="0"): + if diagnostics=="0": DeleteWorkspace(i+"norm_2") DeleteWorkspace(i+"norm_1") DeleteWorkspace("num") @@ -625,7 +625,7 @@ def nrNRFn(runList,nameList,incidentAngles,DBList,specChan,minSpec,maxSpec,gpara k=0 for i in nlist: - if(mtd[i].isGroup()): + if mtd[i].isGroup(): #RenameWorkspace(i+"_1",i) snames=mtd[i].getNames() Plus(i+"_1",i+"_2","wtemp") @@ -701,7 +701,7 @@ def nrNRFn(runList,nameList,incidentAngles,DBList,specChan,minSpec,maxSpec,gpara k=k+1 DeleteWorkspace(i) - if(diagnostics==0): + if diagnostics==0: DeleteWorkspace(i+"mon") DeleteWorkspace(i+"det") @@ -735,7 +735,7 @@ def nrDBFn(runListShort,nameListShort,runListLong,nameListLong,nameListComb,minS ConvertUnits(InputWorkspace=i,OutputWorkspace=i,Target="Wavelength",AlignBins="1") Rebin(InputWorkspace=i,OutputWorkspace=i,Params=reb) CropWorkspace(InputWorkspace=i,OutputWorkspace=i+"mon",StartWorkspaceIndex=mon_spec,EndWorkspaceIndex=mon_spec) - if(mtd[i].isGroup()): + if mtd[i].isGroup(): snames=mtd[i].getNames() a1=mtd[snames[0]] else: @@ -758,7 +758,7 @@ def nrDBFn(runListShort,nameListShort,runListLong,nameListLong,nameListComb,minS ConvertUnits(InputWorkspace=i,OutputWorkspace=i,Target="Wavelength",AlignBins="1") Rebin(InputWorkspace=i,OutputWorkspace=i,Params=reb) CropWorkspace(InputWorkspace=i,OutputWorkspace=i+"mon",StartWorkspaceIndex=mon_spec,EndWorkspaceIndex=mon_spec) - if(mtd[i].isGroup()): + if mtd[i].isGroup(): lnames=mtd[i].getNames() a1=mtd[lnames[0]] else: @@ -778,7 +778,7 @@ def nrDBFn(runListShort,nameListShort,runListLong,nameListLong,nameListComb,minS ReplaceSpecialValues(i+"norm",i+"norm","0.0","0.0","0.0","0.0") for i in range(len(nlistS)): - if(mtd[nlistS[i]+"norm"].isGroup()): + if mtd[nlistS[i]+"norm"].isGroup(): snames=mtd[nlistS[i]+"norm"].getNames() lnames=mtd[nlistL[i]+"norm"].getNames() for k in range(len(snames)): @@ -789,7 +789,7 @@ def nrDBFn(runListShort,nameListShort,runListLong,nameListLong,nameListComb,minS a1=findbin(lnames[k],float(minWavelength)) MultiplyRange(lnames[k],lnames[k],"0",str(a1),"0.0") WeightedMean(snames[k],lnames[k],nlistComb[i]+"_"+str(k+1)) - if (diagnostics=="0"): + if diagnostics=="0": DeleteWorkspace(snames[k]+"int") DeleteWorkspace(lnames[k]+"int") else: @@ -800,11 +800,11 @@ def nrDBFn(runListShort,nameListShort,runListLong,nameListLong,nameListComb,minS a1=findbin(nlistL[i]+"norm",float(minWavelength)) MultiplyRange(nlistL[i]+"norm",nlistL[i]+"norm","0",str(a1),"0.0") WeightedMean(nlistS[i]+"norm",nlistL[i]+"norm",nlistComb[i]) - if (diagnostics=="0"): + if diagnostics=="0": DeleteWorkspace(nlistS[i]+"int") DeleteWorkspace(nlistL[i]+"int") - if (diagnostics=="0"): + if diagnostics=="0": DeleteWorkspace(nlistS[i]+"mon") DeleteWorkspace(nlistS[i]+"det") if nspec != 4: @@ -916,7 +916,7 @@ def NRCombineDatafn(RunsNameList,CombNameList,applySFs,SFList,SFError,scaleOptio RenameWorkspace('currentSum',CombNameList) for i in range(len(rlist)-1): mtd.deleteWorkspace("sf"+str(i)) - if (diagnostics==0): + if diagnostics==0: for i in range(len(rlist)): mtd.deleteWorkspace(rlist[i]+"reb") return [arr2list(sfs),arr2list(sferrs)] @@ -1109,7 +1109,7 @@ def nrPNRFn(runList,nameList,incidentAngles,DBList,specChan,minSpec,maxSpec,gpar for i in nlist: a1=mtd[i+"_1"] nspec=a1.getNumberHistograms() - if (subbgd==1 and nspec!=4): + if subbgd==1 and nspec!=4: # If a background subtraction is required sum the bgd outside the # area of the detector that is visible through the analyser over all periods and average CloneWorkspace(i,"bgdtemp") @@ -1117,7 +1117,7 @@ def nrPNRFn(runList,nameList,incidentAngles,DBList,specChan,minSpec,maxSpec,gpar Rebin(InputWorkspace="bgdtemp",OutputWorkspace="bgdtemp",Params=reb) CropWorkspace(InputWorkspace="bgdtemp",OutputWorkspace="bgdtemp",StartWorkspaceIndex=4,EndWorkspaceIndex=243) Plus("bgdtemp"+"_"+pnums[0],"bgdtemp"+"_"+pnums[1],OutputWorkspace="wbgdsum") - if (nper>2): + if nper>2: for j in range(2,nper): Plus("wbgdsum","bgdtemp"+"_"+pnums[j],OutputWorkspace="wbgdsum") GroupDetectors("wbgdsum","bgd2",WorkspaceIndexList=range(0,50),KeepUngroupedSpectra="0") @@ -1151,7 +1151,7 @@ def nrPNRFn(runList,nameList,incidentAngles,DBList,specChan,minSpec,maxSpec,gpar #print str(2.0*float(incAngles[k]))+" "+str(atan((float(minSpec)-float(specChan))*1.2e-3/3.63)*180.0/pi)+" "+str(a1) RotateInstrumentComponent(wksp+"det","DetectorBench",X="-1.0",Angle=str(a1)) floodnorm(wksp+"det",floodfile) - if (subbgd==1): + if subbgd==1: # Subract a per spectrum background Minus(wksp+"det",wbgdtemp,OutputWorkspace=wksp+"det") ResetNegatives(InputWorkspace=wksp+"det",OutputWorkspace=wksp+"det",AddMinimum='0',ResetValue="0.0") @@ -1179,7 +1179,7 @@ def nrPNRFn(runList,nameList,incidentAngles,DBList,specChan,minSpec,maxSpec,gpar RenameWorkspace(InputWorkspace=i+"norm"+"_"+pnums[j]+"corr",OutputWorkspace=i+"normcorr"+"_"+pnums[j]) GroupWorkspaces(InputWorkspaces=i+"normcorr_"+pnums[0]+","+i+"normcorr_"+pnums[1],OutputWorkspace=i+"normcorr") ConvertUnits(InputWorkspace=i+"normcorr",OutputWorkspace=i+"normcorrRvQ",Target="MomentumTransfer") - if (nspec > 4 and doLDCorrs != "0"): + if nspec > 4 and doLDCorrs != "0": nrPNRCorrection(i+"detnorm_"+pnums[0],i+"detnorm_"+pnums[1]) for j in range(4): RenameWorkspace(InputWorkspace=i+"detnorm"+"_"+pnums[j]+"corr",OutputWorkspace=i+"detnormcorr"+"_"+pnums[j]) @@ -1190,19 +1190,19 @@ def nrPNRFn(runList,nameList,incidentAngles,DBList,specChan,minSpec,maxSpec,gpar RenameWorkspace(InputWorkspace=i+"norm"+"_"+pnums[j]+"corr",OutputWorkspace=i+"normcorr"+"_"+pnums[j]) GroupWorkspaces(InputWorkspaces=i+"normcorr_"+pnums[0]+","+i+"normcorr_"+pnums[1]+","+i+"normcorr_"+pnums[2]+","+i+"normcorr_"+pnums[3]+"",OutputWorkspace=i+"normcorr") ConvertUnits(InputWorkspace=i+"normcorr",OutputWorkspace=i+"normcorrRvQ",Target="MomentumTransfer") - if (nspec > 4 and doLDCorrs != "0"): + if nspec > 4 and doLDCorrs != "0": nrPACorrection(i+"detnorm_"+pnums[0],i+"detnorm_"+pnums[1],i+"detnorm_"+pnums[2],i+"detnorm_"+pnums[3]) for j in range(4): RenameWorkspace(InputWorkspace=i+"detnorm"+"_"+pnums[j]+"corr",OutputWorkspace=i+"detnormcorr"+"_"+pnums[j]) GroupWorkspaces(InputWorkspaces=i+"detnormcorr_"+pnums[0]+","+i+"detnormcorr_"+pnums[1]+","+i+"detnormcorr_"+pnums[2]+","+i+"detnormcorr_"+pnums[3]+"",OutputWorkspace=i+"detnormcorr") - if (diagnostics == 0 and doCorrs != "0"): + if diagnostics == 0 and doCorrs != "0": DeleteWorkspace(i+"norm") DeleteWorkspace(i+"RvQ") - if (diagnostics == 0 and doLDCorrs != "0"): + if diagnostics == 0 and doLDCorrs != "0": DeleteWorkspace(i+"detnorm") k=k+1 DeleteWorkspace(i) - if (subbgd==1): + if subbgd==1: DeleteWorkspace("wbgdtemp") def tl(wksp,th0,schan): diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py index 742d1b04520c..fa0c74c731df 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py @@ -130,7 +130,7 @@ def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max, background_mi print i0_monitor_index print nHist - if (run=='0'): + if run=='0': RunNumber = '0' else: RunNumber = groupGet(_sample_ws.getName(),'samp','run_number') @@ -148,7 +148,7 @@ def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max, background_mi DirectBeam = SumSpectra(InputWorkspace=_detector_ws, StartWorkspaceIndex=db[0], EndWorkspaceIndex=db[1]) ReflectedBeam = ReflectedBeam / DirectBeam polCorr(polcorr, IvsLam, crho, calpha, cAp, cPp) - if (theta and correct_positions): + if theta and correct_positions: IvsQ = l2q(ReflectedBeam, detector_component_name, theta, sample_component_name) else: IvsQ = ConvertUnits(InputWorkspace=ReflectedBeam, Target="MomentumTransfer") @@ -182,7 +182,7 @@ def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max, background_mi # Convert to I vs Q # check if detector in direct beam - if (theta == None or theta == 0 or theta == ''): + if theta == None or theta == 0 or theta == '': inst = groupGet('IvsLam','inst') detLocation=inst.getComponentByName(detector_component_name).getPos() sampleLocation=inst.getComponentByName(sample_component_name).getPos() @@ -411,7 +411,7 @@ def nrPNRCorrection(Wksp,crho,calpha,cAp,cPp): logger.notice(message) print message CloneWorkspace(Wksp,OutputWorkspace='_'+Wksp+'_uncorrected') - if ( (not isinstance(mtd[Wksp], WorkspaceGroup)) or (not mtd[Wksp].size()==2) ): + if (not isinstance(mtd[Wksp], WorkspaceGroup)) or (not mtd[Wksp].size()==2) : print "PNR correction works only with exactly 2 periods!" return mtd[Wksp] else: @@ -560,17 +560,17 @@ def groupGet(wksp,whattoget,field=''): returns information about instrument or sample details for a given workspace wksp, also if the workspace is a group (info from first group element) ''' - if (whattoget == 'inst'): + if whattoget == 'inst': if isinstance(mtd[wksp], WorkspaceGroup): return mtd[wksp+'_1'].getInstrument() else: return mtd[wksp].getInstrument() - elif (whattoget == 'samp' and field != ''): + elif whattoget == 'samp' and field != '': if isinstance(mtd[wksp], WorkspaceGroup): try: log = mtd[wksp + '_1'].getRun().getLogData(field).value - if (type(log) is int or type(log) is str): + if type(log) is int or type(log) is str: res=log else: res = log[len(log)-1] @@ -580,7 +580,7 @@ def groupGet(wksp,whattoget,field=''): else: try: log = mtd[wksp].getRun().getLogData(field).value - if (type(log) is int or type(log) is str): + if type(log) is int or type(log) is str: res=log else: res = log[len(log)-1] @@ -588,7 +588,7 @@ def groupGet(wksp,whattoget,field=''): res = 0 print "Block "+field+" not found." return res - elif (whattoget == 'wksp'): + elif whattoget == 'wksp': if isinstance(mtd[wksp], WorkspaceGroup): return mtd[wksp+'_1'].getNumberHistograms() else: diff --git a/Code/Mantid/scripts/SANS/ISISCommandInterface.py b/Code/Mantid/scripts/SANS/ISISCommandInterface.py index 7c181d5918a6..b453bb6065b2 100644 --- a/Code/Mantid/scripts/SANS/ISISCommandInterface.py +++ b/Code/Mantid/scripts/SANS/ISISCommandInterface.py @@ -266,7 +266,7 @@ def TransmissionSample(sample, direct, reload = True, period_t = -1, period_d = """ _printMessage('TransmissionSample("' + str(sample) + '","' + str(direct) + '")') ReductionSingleton().set_trans_sample(sample, direct, reload, period_t, period_d) - return ReductionSingleton().samp_trans_load.execute( + return ReductionSingleton().samp_trans_load.execute(\ ReductionSingleton(), None) def TransmissionCan(can, direct, reload = True, period_t = -1, period_d = -1): @@ -280,7 +280,7 @@ def TransmissionCan(can, direct, reload = True, period_t = -1, period_d = -1): """ _printMessage('TransmissionCan("' + str(can) + '","' + str(direct) + '")') ReductionSingleton().set_trans_can(can, direct, reload, period_t, period_d) - return ReductionSingleton().can_trans_load.execute( + return ReductionSingleton().can_trans_load.execute(\ ReductionSingleton(), None) def AssignSample(sample_run, reload = True, period = isis_reduction_steps.LoadRun.UNSET_PERIOD): @@ -317,7 +317,7 @@ def SetCentre(xcoord, ycoord, bank = 'rear'): """ _printMessage('SetCentre(' + str(xcoord) + ', ' + str(ycoord) + ')') - ReductionSingleton().set_beam_finder(isis_reduction_steps.BaseBeamFinder( + ReductionSingleton().set_beam_finder(isis_reduction_steps.BaseBeamFinder(\ float(xcoord)/1000.0, float(ycoord)/1000.0), bank) def GetMismatchedDetList(): @@ -380,9 +380,9 @@ def WavRangeReduction(wav_start=None, wav_end=None, full_trans_wav=None, name_su # if the user chose to reduce front and does not require fit if not (com_det_option == 'front' and not fitRequired): reduce_rear_flag = True - if (com_det_option != 'rear'): + if com_det_option != 'rear': reduce_front_flag = True - if (com_det_option == 'merged'): + if com_det_option == 'merged': merge_flag = True #The shift and scale is always on the front detector. @@ -408,7 +408,7 @@ def WavRangeReduction(wav_start=None, wav_end=None, full_trans_wav=None, name_su # do reduce front bank if reduce_front_flag: # it is necessary to replace the Singleton if a reduction was done before - if (reduce_rear_flag): + if reduce_rear_flag: # In this case, it is necessary to reload the files, in order to move the components to the # correct position defined by its get_beam_center. (ticket #5942) @@ -416,8 +416,8 @@ def WavRangeReduction(wav_start=None, wav_end=None, full_trans_wav=None, name_su ReductionSingleton.replace(ReductionSingleton().cur_settings()) # for the LOQ instrument, if the beam centers are different, we have to reload the data. - if (ReductionSingleton().instrument._NAME == 'LOQ' and - (ReductionSingleton().get_beam_center('rear') != ReductionSingleton().get_beam_center('front'))): + if ReductionSingleton().instrument._NAME == 'LOQ' and\ + ReductionSingleton().get_beam_center('rear') != ReductionSingleton().get_beam_center('front'): # It is necessary to reload sample, transmission and can files. #reload sample @@ -636,7 +636,7 @@ def _WavRangeReduction(name_suffix=None): Run a reduction that has been set up, from loading the raw data to calculating Q """ def _setUpPeriod(period): - assert(ReductionSingleton().get_sample().loader.move2ws(period)) + assert ReductionSingleton().get_sample().loader.move2ws(period) can = ReductionSingleton().get_can() if can and can.loader.periods_in_file > 1: can.loader.move2ws(period) @@ -868,8 +868,8 @@ def LimitsR(rmin, rmax, quiet=False, reducer=None): def LimitsWav(lmin, lmax, step, bin_type): _printMessage('LimitsWav(' + str(lmin) + ', ' + str(lmax) + ', ' + str(step) + ', ' + bin_type + ')') - if ( bin_type.upper().strip() == 'LINEAR'): bin_type = 'LIN' - if ( bin_type.upper().strip() == 'LOGARITHMIC'): bin_type = 'LOG' + if bin_type.upper().strip() == 'LINEAR': bin_type = 'LIN' + if bin_type.upper().strip() == 'LOGARITHMIC': bin_type = 'LOG' if bin_type == 'LOG': bin_sym = '-' else: @@ -1049,7 +1049,7 @@ def FindBeamCentre(rlow, rupp, MaxIter = 10, xstart = None, ystart = None, toler if xstart or ystart: ReductionSingleton().set_beam_finder( - isis_reduction_steps.BaseBeamFinder( + isis_reduction_steps.BaseBeamFinder(\ float(xstart), float(ystart)),det_bank) beamcoords = ReductionSingleton().get_beam_center() @@ -1094,7 +1094,7 @@ def FindBeamCentre(rlow, rupp, MaxIter = 10, xstart = None, ystart = None, toler if not graph_handle: #once we have a plot it will be updated automatically when the workspaces are updated graph_handle = mantidplot.plotSpectrum(centre.QUADS, 0) - graph_handle.activeLayer().setTitle( + graph_handle.activeLayer().setTitle(\ centre.status_str(it, resX, resY)) except : #if plotting is not available it probably means we are running outside a GUI, in which case do everything but don't plot diff --git a/Code/Mantid/scripts/SANS/SANSUtility.py b/Code/Mantid/scripts/SANS/SANSUtility.py index f0d604f2ff49..59904b160692 100644 --- a/Code/Mantid/scripts/SANS/SANSUtility.py +++ b/Code/Mantid/scripts/SANS/SANSUtility.py @@ -625,14 +625,14 @@ def StripEndZeroes(workspace, flag_value = 0.0): # Find the first non-zero value start = 0 for i in range(0, length): - if ( y_vals[i] != flag_value ): + if y_vals[i] != flag_value : start = i break # Now find the last non-zero value stop = 0 length -= 1 for j in range(length, 0,-1): - if ( y_vals[j] != flag_value ): + if y_vals[j] != flag_value : stop = j break # Find the appropriate X values and call CropWorkspace diff --git a/Code/Mantid/scripts/SANS/SANSadd2.py b/Code/Mantid/scripts/SANS/SANSadd2.py index 8a878d45dad2..a8a6436f50ad 100644 --- a/Code/Mantid/scripts/SANS/SANSadd2.py +++ b/Code/Mantid/scripts/SANS/SANSadd2.py @@ -28,12 +28,12 @@ def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add' userEntry = runs[0] - while(True): + while True: isFirstDataSetEvent = False #we need to catch all exceptions to ensure that a dialog box is raised with the error try : - lastPath, lastFile, logFile, num_periods, isFirstDataSetEvent = _loadWS( + lastPath, lastFile, logFile, num_periods, isFirstDataSetEvent = _loadWS(\ userEntry, defType, inst, 'AddFilesSumTempory', rawTypes, period) # if event data prevent loop over periods makes no sense @@ -51,7 +51,7 @@ def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add' for i in range(len(runs)-1): userEntry = runs[i+1] - lastPath, lastFile, logFile, dummy, isDataSetEvent = _loadWS( + lastPath, lastFile, logFile, dummy, isDataSetEvent = _loadWS(\ userEntry, defType, inst,'AddFilesNewTempory', rawTypes, period) if isDataSetEvent != isFirstDataSetEvent: @@ -154,7 +154,7 @@ def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add' path,base = os.path.split(outFile) if path == '' or base not in os.listdir(path): path = config['defaultsave.directory'] + path - assert(base in os.listdir(path)) + assert base in os.listdir(path) pathout = path if logFile: _copyLog(lastPath, logFile, pathout) diff --git a/Code/Mantid/scripts/SANS/isis_instrument.py b/Code/Mantid/scripts/SANS/isis_instrument.py index 8fdd32688fb0..3f1c3e6a23b7 100644 --- a/Code/Mantid/scripts/SANS/isis_instrument.py +++ b/Code/Mantid/scripts/SANS/isis_instrument.py @@ -163,9 +163,9 @@ def __init__(self, scale=1.0, shift=0.0, fitScale=False, fitShift=False, qMin=No def __init__(self, instr, det_type): #detectors are known by many names, the 'uni' name is an instrument independent alias the 'long' name is the instrument view name and 'short' name often used for convenience - self._names = { - 'uni' : det_type, - 'long': instr.getStringParameter(det_type+'-detector-name')[0], + self._names = {\ + 'uni' : det_type,\ + 'long': instr.getStringParameter(det_type+'-detector-name')[0],\ 'short': instr.getStringParameter(det_type+'-detector-short-name')[0]} #the bank is often also referred to by its location, as seen by the sample if det_type.startswith('low'): @@ -399,7 +399,7 @@ def crop_to_detector(self, input_name, output_name=None): try: wki = mtd[input_name] #Is it really necessary to crop? - if (wki.getNumberHistograms() != self.last_spec_num - self.get_first_spec_num() + 1): + if wki.getNumberHistograms() != self.last_spec_num - self.get_first_spec_num() + 1: CropWorkspace(InputWorkspace=input_name,OutputWorkspace= output_name, StartWorkspaceIndex = self.get_first_spec_num() - 1, EndWorkspaceIndex = self.last_spec_num - 1) @@ -699,7 +699,7 @@ def changeCalibration(self, ws_name): CopyInstrumentParameters(calib, ws_name) def setCalibrationWorkspace(self, ws_reference): - assert(isinstance(ws_reference, Workspace)) + assert isinstance(ws_reference, Workspace) # we do deep copy of singleton - to be removed in 8470 # this forces us to have 'copyable' objects. self._newCalibrationWS = str(ws_reference) @@ -823,7 +823,7 @@ def set_up_for_run(self, base_runno): first.set_first_spec_num(1) first.set_orien('Vertical') second.set_orien('Vertical') - elif (base_runno >= 568 and base_runno < 684): + elif base_runno >= 568 and base_runno < 684: first.set_first_spec_num(9) first.set_orien('Rotated') second.set_orien('Rotated') diff --git a/Code/Mantid/scripts/SANS/isis_reducer.py b/Code/Mantid/scripts/SANS/isis_reducer.py index 30e9ab5afdda..f6bdb9599e9b 100644 --- a/Code/Mantid/scripts/SANS/isis_reducer.py +++ b/Code/Mantid/scripts/SANS/isis_reducer.py @@ -183,10 +183,10 @@ def _init_steps(self): # so currently do not understand why it is in isis_reduction_steps # Also the main purpose of this class is to use it as an input argument # to ConvertToQ below - self.prep_normalize = isis_reduction_steps.CalculateNormISIS( + self.prep_normalize = isis_reduction_steps.CalculateNormISIS(\ [self.norm_mon, self.transmission_calculator]) - self.to_Q = isis_reduction_steps.ConvertToQISIS( + self.to_Q = isis_reduction_steps.ConvertToQISIS(\ self.prep_normalize) self._background_subtracter = isis_reduction_steps.CanSubtraction() self.geometry_correcter = isis_reduction_steps.SampleGeomCor() @@ -600,7 +600,7 @@ def get_beam_center(self, bank = None): def getCurrSliceLimit(self): if not self._slices_def: self._slices_def = su.sliceParser("") - assert(self._slice_index == 0) + assert self._slice_index == 0 return self._slices_def[self._slice_index] def getNumSlices(self): diff --git a/Code/Mantid/scripts/SANS/isis_reduction_steps.py b/Code/Mantid/scripts/SANS/isis_reduction_steps.py index 6d09cf983533..9dd1305c0e4f 100644 --- a/Code/Mantid/scripts/SANS/isis_reduction_steps.py +++ b/Code/Mantid/scripts/SANS/isis_reduction_steps.py @@ -205,7 +205,7 @@ def _loadFromWorkspace(self, reducer): If reload is True, it will try to get all the information necessary to reload this workspace from the data file. """ - assert(isinstance(self._data_file, Workspace)) + assert isinstance(self._data_file, Workspace) ws_pointer = self._data_file try: @@ -704,7 +704,7 @@ def parse_instruction(self, instName, details): self.time_mask = '' self.time_mask_r = '' self.time_mask_f = '' - elif (type == 'TIME' or type == 'T'): + elif type == 'TIME' or type == 'T': parts = parts[2].split() if len(parts) == 3: detname = parts[0].rstrip() @@ -1027,7 +1027,7 @@ def display(self, wksp, reducer, counts=None): Ys.append(flags.readY(i)[0]) Es.append(0) - if (vals.readY(i)[0] > maxval): + if vals.readY(i)[0] > maxval: #don't include masked or monitors if (flags.readY(i)[0] == 0) and (vals.readY(i)[0] < 5000): maxval = vals.readY(i)[0] @@ -1405,7 +1405,7 @@ def calculate(self, reducer): direct_tmp_out = self.setup_wksp(direct_raw, reducer.instrument,\ wavbin, pre_sample, post_sample) - fittedtransws, unfittedtransws = self.get_wksp_names( + fittedtransws, unfittedtransws = self.get_wksp_names(\ trans_raw, translambda_min, translambda_max, reducer) # If no fitting is required just use linear and get unfitted data from CalculateTransmission algorithm @@ -1611,7 +1611,7 @@ def calculate(self, reducer, wave_wks=[]): ConvertToHistogram(InputWorkspace=self.TMP_ISIS_NAME,OutputWorkspace= self.TMP_ISIS_NAME) ## try to redefine self._pixel_file to pass to CalculateNORM method calculate. detect_pixel_file = self.getPixelCorrFile(reducer.instrument.cur_detector().name()) - if (detect_pixel_file != ""): + if detect_pixel_file != "": self._pixel_file = detect_pixel_file for step in self._wave_steps: @@ -1707,7 +1707,7 @@ def execute(self, reducer, workspace): Calculate the normalization workspaces and then call the chosen Q conversion algorithm. """ wavepixeladj = "" - if (reducer.wide_angle_correction and reducer.transmission_calculator.output_wksp): + if reducer.wide_angle_correction and reducer.transmission_calculator.output_wksp: #calculate the transmission wide angle correction _issueWarning("sans solid angle correction execution") SANSWideAngleCorrection(SampleData=workspace,\ @@ -1995,11 +1995,11 @@ def read_line(self, line, reducer): hab_str_pos = upper_line.find('HAB') x_pos = 0.0 y_pos = 0.0 - if (main_str_pos > 0): + if main_str_pos > 0: values = upper_line[main_str_pos+5:].split() #remov the SET CENTRE/MAIN x_pos = float(values[0])/1000.0 y_pos = float(values[1])/1000.0 - elif (hab_str_pos > 0): + elif hab_str_pos > 0: values = upper_line[hab_str_pos+4:].split() # remove the SET CENTRE/HAB print ' convert values ',values x_pos = float(values[0])/1000.0 @@ -2008,7 +2008,7 @@ def read_line(self, line, reducer): values = upper_line.split() x_pos = float(values[2])/1000.0 y_pos = float(values[3])/1000.0 - if (hab_str_pos > 0): + if hab_str_pos > 0: print 'Front values = ',x_pos,y_pos reducer.set_beam_finder(BaseBeamFinder(x_pos, y_pos),'front') else: @@ -2184,7 +2184,7 @@ def readLimitValues(self, limit_line, reducer): _issueWarning("General wave re-bin lines are not implemented, line ignored \"" + limit_line + "\"") return else: - reducer.to_wavelen.set_rebin( + reducer.to_wavelen.set_rebin(\ minval, step_type + step_size, maxval, override=False) elif limit_type.upper() == 'Q': if rebin_str: @@ -2806,7 +2806,7 @@ def __init__(self): def calculate_volume(self, reducer): geo = reducer.get_sample().geometry - assert( issubclass(geo.__class__, GetSampleGeom)) + assert issubclass(geo.__class__, GetSampleGeom) try: if geo.shape == 'cylinder-axis-up': diff --git a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py index 3be9f366704a..da992481ba3a 100644 --- a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py +++ b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py @@ -54,7 +54,7 @@ # # Get the config file name and the run number to process from the command line # -if (len(sys.argv) < 3): +if len(sys.argv) < 3: print "You MUST give the config file name(s) and run number on the command line" exit(0) @@ -158,9 +158,9 @@ # can not be None. TOPAZ has one calibration file, but SNAP may have two. # if (calibration_file_1 is not None ) or (calibration_file_2 is not None): - if (calibration_file_1 is None ): + if calibration_file_1 is None : calibration_file_1 = "" - if (calibration_file_2 is None ): + if calibration_file_2 is None : calibration_file_2 = "" LoadIsawDetCal( event_ws,\ Filename=calibration_file_1, Filename2=calibration_file_2 ) diff --git a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py index 296beb0688c7..16a978089c34 100644 --- a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py +++ b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py @@ -69,7 +69,7 @@ def run ( self ): # # Get the config file name from the command line # -if (len(sys.argv) < 2): +if len(sys.argv) < 2: print "You MUST give the config file name on the command line" exit(0) @@ -132,7 +132,7 @@ def run ( self ): all_done = False active_list=[] while not all_done: - if ( len(list) > 0 and len(active_list) < max_processes ): + if len(list) > 0 and len(active_list) < max_processes : thread = list[0] list.remove(thread) active_list.append( thread ) diff --git a/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py b/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py index 8f8345eae747..37c0a52e4346 100644 --- a/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py +++ b/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py @@ -54,7 +54,7 @@ def counts_vs_pixel_distribution(file_path, is_pixel_y=True, callback=None, ws_base = "__%s" % basename ws_output_base = '' - if (instrument == 'REFL'): + if instrument == 'REFL': if isPeak: type = 'Peak' else: diff --git a/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py b/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py index 0f7fcb029383..71d76110b52d 100644 --- a/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py +++ b/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py @@ -218,9 +218,9 @@ def findQaxisMinMax(q_axis): for i in arange(nbr_row - 1) + 1: _q_min = q_axis[i][-1] _q_max = q_axis[i][0] - if (_q_min > q_min): + if _q_min > q_min: q_min = _q_min - if (_q_max < q_max): + if _q_max < q_max: q_max = _q_max #find now the index of those min and max in each row @@ -386,13 +386,13 @@ def convertWorkspaceToQ(ws_data, #keep only the overlap region of Qs _q_min = _q_axis_min_max_index[_q_index, 0] - if (_q_min != 0): + if _q_min != 0: _y_axis_tmp[0:_q_min] = 0 _y_error_axis_tmp[0:_q_min] = 0 _q_max = int(_q_axis_min_max_index[_q_index, 1]) sz = shape(_y_axis_tmp)[0] - if (_q_max != sz): + if _q_max != sz: _index_q_max_range = arange(sz - _q_max) + _q_max for i in _index_q_max_range: _y_axis_tmp[i] = 0 @@ -502,16 +502,16 @@ def angleUnitConversion(value, from_units='degree', to_units='rad'): """ - if (from_units == to_units): + if from_units == to_units: return value from_factor = 1 #convert everything into rad - if (from_units == 'degree'): + if from_units == 'degree': from_factor = 1.745329252e-2 value_rad = from_factor * value - if (to_units == 'rad'): + if to_units == 'rad': return value_rad else: to_factor = 57.2957795 @@ -723,7 +723,7 @@ def ref_beamdiv_correct(cpix, det_secondary, xI = xF yI = yF - if (len(int_poly_x) > 2): + if len(int_poly_x) > 2: int_poly_x.append(int_poly_x[0]) int_poly_y.append(int_poly_y[0]) int_poly_x.append(int_poly_x[1]) @@ -800,13 +800,13 @@ def applySF(InputWorkspace, """ #check if config file is there - if (os.path.isfile(sfFile)): + if os.path.isfile(sfFile): #parse file and put info into array f = open(sfFile, 'r') sfFactorTable = [] for line in f.read().split('\n'): - if (len(line) > 0 and line[0] != '#'): + if len(line) > 0 and line[0] != '#': sfFactorTable.append(line.split(' ')) f.close() @@ -845,7 +845,7 @@ def applySF(InputWorkspace, for i in range(nbr_row): _file_incidentMedium = getFieldValue(sfFactorTable,i,0) - if (_file_incidentMedium.strip() == _incidentMedium.strip()): + if _file_incidentMedium.strip() == _incidentMedium.strip(): print '--- incident medium match ---' _file_lambdaRequested = getFieldValue(sfFactorTable,i,1) if (isWithinPrecisionRange(_file_lambdaRequested, @@ -862,7 +862,7 @@ def applySF(InputWorkspace, s2h_value, valuePrecision)): print '--- S2H match ---' - if (slitsWidthFlag): + if slitsWidthFlag: print '--- (with Width flag) ----' _file_s1w = getFieldValue(sfFactorTable,i,4) if(isWithinPrecisionRange(_file_s1w, @@ -946,7 +946,7 @@ def loadNeXus(runNumbers, type): """ wks_name = '' - if (type == 'data'): + if type == 'data': wks_name = 'ws_event_data' else: wks_name = 'ws_event_norm' @@ -1172,7 +1172,7 @@ def weightedMean(data_array, error_array, error_0): # calculate the numerator of mean dataNum = 0 for i in range(sz): - if (error_array[i] == 0): + if error_array[i] == 0: error_array[i] = error_0 tmpFactor = float(data_array[i]) / float((pow(error_array[i],2))) @@ -1181,7 +1181,7 @@ def weightedMean(data_array, error_array, error_0): # calculate denominator dataDen = 0 for i in range(sz): - if (error_array[i] == 0): + if error_array[i] == 0: error_array[i] = error_0 tmpFactor = 1./float((pow(error_array[i],2))) dataDen += tmpFactor @@ -1419,7 +1419,7 @@ def applyScalingFactor(tof_axis, file created by the sfCalculator procedure """ #sf_file = 'NaN' - if (os.path.isfile(sf_file)): + if os.path.isfile(sf_file): print '-> scaling factor file FOUND! (', sf_file, ')' @@ -1427,7 +1427,7 @@ def applyScalingFactor(tof_axis, f = open(sf_file, 'r') sfFactorTable = [] for line in f.read().split('\n'): - if (len(line) > 0 and line[0] != '#'): + if len(line) > 0 and line[0] != '#': sfFactorTable.append(line.split(' ')) f.close() @@ -1463,7 +1463,7 @@ def applyScalingFactor(tof_axis, for i in range(nbr_row): _file_incidentMedium = getFieldValue(sfFactorTable,i,0) - if (_file_incidentMedium.strip() == _incidentMedium.strip()): + if _file_incidentMedium.strip() == _incidentMedium.strip(): print '*** incident medium match ***' _file_lambdaRequested = getFieldValue(sfFactorTable,i,1) if (isWithinPrecisionRange(_file_lambdaRequested, @@ -1480,7 +1480,7 @@ def applyScalingFactor(tof_axis, s2h_value, valuePrecision)): print '*** s2h match ***' - if (slitsWidthFlag): + if slitsWidthFlag: print '*** (with slits width flag) ***' _file_s1w = getFieldValue(sfFactorTable,i,4) if(isWithinPrecisionRange(_file_s1w, @@ -1709,7 +1709,7 @@ def getQrange(ws_histo_data, theta, dMD, q_min, q_step): _Q = _const * math.sin(theta) / (tofm*1e-6) _q_axis[t] = _Q*1e-10 q_max = max(_q_axis) - if (q_min >= q_max): + if q_min >= q_max: q_min = min(_q_axis) print '----> q_min: ', q_min print '----> q_step: ', q_step @@ -1767,13 +1767,13 @@ def convertToQ(tof_axis, # keep only the overlap region of Qs _q_min = _q_axis_min_max_index[_y_index, 0] - if (_q_min != 0): + if _q_min != 0: _y_axis_tmp[0:_q_min] = 0 _y_error_axis_tmp[0:_q_min] = 0 _q_max = int(_q_axis_min_max_index[_y_index, 1]) sz = shape(_y_axis_tmp)[0] - if (_q_max != sz): + if _q_max != sz: _index_q_max_range = arange(sz - _q_max) + _q_max for i in _index_q_max_range: _y_axis_tmp[i] = 0 @@ -2060,7 +2060,7 @@ def cleanupData1D(final_data_y_axis, final_data_y_error_axis): if abs(_error) >= abs(_data): _data_tmp = 0 _error_tmp = 1 - elif (_data< 1e-12): + elif _data< 1e-12: # if value is below 10^-12 _data_tmp = 0 _error_tmp = 1 diff --git a/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py b/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py index 8a767a6cae39..274030ee979f 100644 --- a/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py +++ b/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py @@ -752,7 +752,7 @@ def __init__(self): def calculate_volume(self, reducer): geo = reducer.get_sample().geometry - assert( issubclass(geo.__class__, GetSampleGeom)) + assert issubclass(geo.__class__, GetSampleGeom) try: if geo.shape == 'cylinder-axis-up': @@ -804,14 +804,14 @@ def execute(self, reducer, workspace): # Find the first non-zero value start = 0 for i in range(0, length): - if ( y_vals[i] != self._flag_value ): + if y_vals[i] != self._flag_value : start = i break # Now find the last non-zero value stop = 0 length -= 1 for j in range(length, 0,-1): - if ( y_vals[j] != self._flag_value ): + if y_vals[j] != self._flag_value : stop = j break # Find the appropriate X values and call CropWorkspace From 55bd0bd2575b93bf71242fbd42f5f5bbf0e1a9c4 Mon Sep 17 00:00:00 2001 From: Andrei Savici Date: Thu, 19 Feb 2015 21:28:14 -0500 Subject: [PATCH 320/414] removing unused imports from algorithms and functions. Refs #11134 --- .../plugins/algorithms/CalibrateRectangularDetectors.py | 3 +-- .../PythonInterface/plugins/algorithms/ConjoinSpectra.py | 1 - .../Framework/PythonInterface/plugins/algorithms/DSFinterp.py | 2 +- .../PythonInterface/plugins/algorithms/RefLReduction.py | 2 -- .../Framework/PythonInterface/plugins/algorithms/SortXAxis.py | 1 - .../PythonInterface/plugins/algorithms/SuggestTibCNCS.py | 2 +- .../Framework/PythonInterface/plugins/algorithms/Symmetrise.py | 3 ++- .../plugins/algorithms/WorkflowAlgorithms/CutMD.py | 2 -- .../plugins/algorithms/WorkflowAlgorithms/Fury.py | 2 +- .../algorithms/WorkflowAlgorithms/ReactorSANSResolution.py | 1 - .../PythonInterface/plugins/functions/ChudleyElliot.py | 1 - .../plugins/functions/Examples/Example1DFunction.py | 3 --- .../PythonInterface/plugins/functions/FickDiffusion.py | 3 --- .../Framework/PythonInterface/plugins/functions/HallRoss.py | 1 - .../PythonInterface/plugins/functions/StretchedExpFT.py | 1 - .../PythonInterface/plugins/functions/TeixeiraWater.py | 3 +-- 16 files changed, 7 insertions(+), 24 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py index d641f58596fb..e6afd8c5d44f 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py @@ -3,8 +3,7 @@ from mantid.kernel import * from mantid.simpleapi import * import os -import datetime -from time import localtime, strftime +from time import strftime from mantid import config from mantid.kernel import Direction diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py index 1980cb4f440d..04155b4acb48 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py @@ -2,7 +2,6 @@ from mantid.api import * from mantid.kernel import * from mantid.simpleapi import * -import os class ConjoinSpectra(PythonAlgorithm): """ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py index bd71c1c6e5ac..83f1b9624edb 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py @@ -110,7 +110,7 @@ def PyExec(self): dsf.Save(outws) # overwrite dataY and dataE ############################################################################################# - +#pylint: disable=unused-import try: import dsfinterp AlgorithmFactory.subscribe(DSFinterp) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py index c20e85d085bd..d30cc3990182 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py @@ -1,8 +1,6 @@ #pylint: disable=no-init,invalid-name from mantid.api import * from mantid.simpleapi import * -from numpy import zeros, shape, arange -import math # import sfCalculator import sys diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py index 06cb23819356..57cf1afa921c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py @@ -4,7 +4,6 @@ from mantid.api import * from mantid.kernel import * import numpy as np -import operator class SortXAxis(PythonAlgorithm): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py index b7e025ec22cb..504a2502ca88 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py @@ -40,7 +40,7 @@ def summary(self): def PyInit(self): """ Declare properties """ - val=mantid.kernel.FloatBoundedValidator() + val=FloatBoundedValidator() val.setBounds(0.5,50) #reasonable incident nergy range for CNCS self.declareProperty("IncidentEnergy",0.,val,"Incident energy (0.5 to 50 meV)") self.declareProperty("TibMin",0.,Direction.Output) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py index 41e7ef7be15f..9ce3813e07c7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py @@ -2,7 +2,8 @@ from mantid import logger, mtd 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 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py index da015d751386..429609ee17cc 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py @@ -3,8 +3,6 @@ from mantid.api import * from mantid.simpleapi import * import numpy as np -import os.path -import re import __builtin__ class Projection(object): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py index 28aad4ce7454..2bdfaf105585 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py @@ -1,7 +1,7 @@ #pylint: disable=no-init 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 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py index b505c147b431..2ba70394d509 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py @@ -1,5 +1,4 @@ #pylint: disable=no-init -import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * import math diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py index af5d9d6d5576..90eb73a4f8eb 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py @@ -25,7 +25,6 @@ ''' from mantid.api import IFunction1D, FunctionFactory -from mantid import logger import math, numpy as np class ChudleyElliot(IFunction1D): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py index f7d2d7ec287a..e0d7949985e1 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py @@ -10,9 +10,6 @@ derivative """ from mantid.api import IFunction1D, FunctionFactory -from mantid import logger -import math -import numpy as np class Example1DFunction(IFunction1D): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py index a73359b318ea..56dc7df6c1e9 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py @@ -25,9 +25,6 @@ ''' from mantid.api import IFunction1D, FunctionFactory -from mantid import logger -import math -import numpy as np class FickDiffusion(IFunction1D): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py index 6d90f26f967a..d11191838628 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py @@ -25,7 +25,6 @@ ''' from mantid.api import IFunction1D, FunctionFactory -from mantid import logger import math, numpy as np class HallRoss(IFunction1D): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py index 8414056e5218..9f5a53f04ac6 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py @@ -29,7 +29,6 @@ import numpy as np import copy -from pdb import set_trace as tr class StretchedExpFT(IFunction1D): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py index 588c534985ca..b49549b786eb 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py @@ -25,8 +25,7 @@ ''' from mantid.api import IFunction1D, FunctionFactory -from mantid import logger -import math, numpy as np +import numpy as np class TeixeiraWater(IFunction1D): From c32b1ef4a4d3cddebc9261d8edb3b1b892ba38a3 Mon Sep 17 00:00:00 2001 From: Andrei Savici Date: Thu, 19 Feb 2015 21:32:10 -0500 Subject: [PATCH 321/414] Few more. refs #11134 --- .../PythonInterface/plugins/algorithms/SuggestTibCNCS.py | 1 - .../PythonInterface/plugins/functions/DSFinterp1DFit.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py index 504a2502ca88..9de958469e28 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py @@ -1,6 +1,5 @@ #pylint: disable=no-init,invalid-name from mantid.api import PythonAlgorithm, AlgorithmFactory -import mantid.simpleapi from mantid.kernel import FloatBoundedValidator,Direction from numpy import sqrt,floor diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py index 26f9af3ac401..e3e18c0edb39 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py @@ -162,7 +162,7 @@ def function1D(self, xvals): return intensities_interpolator(xvals) # can we pass by reference? # Required to have Mantid recognize the new function -#pylint: unused-import +#pylint: disable=unused-import try: import dsfinterp FunctionFactory.subscribe(DSFinterp1DFit) From d89b87a30ec105bbb9ca67a8fcea3009a7cfb30b Mon Sep 17 00:00:00 2001 From: Andrei Savici Date: Thu, 19 Feb 2015 22:47:14 -0500 Subject: [PATCH 322/414] Update TubeCalibDemoMaps_All.py undo some line continuations. Refs #11134 --- .../Examples/TubeCalibDemoMaps_All.py | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py index e4a356e071f2..3938be682040 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py @@ -268,17 +268,17 @@ def improvingCalibrationOfListOfTubes(filename): #CalibInstWS = loadingStep(filename) # it is defined as the mean values around the neighbours - define_peaks = {19:[10, 80.9771, 123.221, 164.993, 245.717],\ # the first one was bad - 37: [6.36, 80.9347, 122.941, 165.104, 248.32],\ # the first one was bad - 71: [8.62752, 85.074, 124.919, 164.116, 246.82 ],\ # the last one was bad - check if we can inprove - 75: [14.4285, 90.087, 128.987, 167.047, 242.62],\ # the last one was bad - check if we can inprove - 181: [11.726, 94.0496, 137.816, 180, 255],\ # the third peak was lost - 186:[11.9382, 71.5203, 107, 147.727, 239.041],\ #lost the second peak - 234: [4.84, 82.7824, 123.125, 163.945, 241.877],\ # the first one was bad - 235: [4.84, 80.0077, 121.002, 161.098, 238.502],\ # the first one was bad - 245: [9.88089, 93.0593, 136.911, 179.5, 255],\ # the third peak was bad - 273: [18.3711, 105.5, 145.5, 181.6, 243.252],\ # lost first and third peaks - 345: [4.6084, 87.0351, 128.125, 169.923, 245.3]\ # the last one was bad + define_peaks = {19:[10, 80.9771, 123.221, 164.993, 245.717], # the first one was bad + 37: [6.36, 80.9347, 122.941, 165.104, 248.32], # the first one was bad + 71: [8.62752, 85.074, 124.919, 164.116, 246.82 ], # the last one was bad - check if we can inprove + 75: [14.4285, 90.087, 128.987, 167.047, 242.62], # the last one was bad - check if we can inprove + 181: [11.726, 94.0496, 137.816, 180, 255], # the third peak was lost + 186:[11.9382, 71.5203, 107, 147.727, 239.041], #lost the second peak + 234: [4.84, 82.7824, 123.125, 163.945, 241.877], # the first one was bad + 235: [4.84, 80.0077, 121.002, 161.098, 238.502], # the first one was bad + 245: [9.88089, 93.0593, 136.911, 179.5, 255], # the third peak was bad + 273: [18.3711, 105.5, 145.5, 181.6, 243.252], # lost first and third peaks + 345: [4.6084, 87.0351, 128.125, 169.923, 245.3] # the last one was bad } calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor, fitPar=fitPar, outputPeak=True, overridePeaks=define_peaks) @@ -486,12 +486,12 @@ def completeCalibration(filename): fitPar.setAutomatic(True) # apply the calibration for the b2_window 2 strips values - calibrationTable, peak2Table = tube.calibrate(CalibInstWS, CalibratedComponent,\ - knownPos,\ #these parameters now have only 4 points - funcFactor,\ - fitPar=fitPar,\ - outputPeak=True,\ - calibTable = calibrationTable,\ # it will append to the calibTable + calibrationTable, peak2Table = tube.calibrate(CalibInstWS, CalibratedComponent, + knownPos, #these parameters now have only 4 points + funcFactor, + fitPar=fitPar, + outputPeak=True, + calibTable = calibrationTable, # it will append to the calibTable rangeList = b2_window) ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable) From eeee5797b277bdeb8e09484c9232b5c3795d0089 Mon Sep 17 00:00:00 2001 From: Andrei Savici Date: Thu, 19 Feb 2015 22:50:41 -0500 Subject: [PATCH 323/414] Update TubeCalibDemoMerlin.py Refs #11134. Undo some line continuations --- .../Examples/TubeCalibDemoMerlin.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py index b597caa3a92e..4fb14c18ea79 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py @@ -99,11 +99,11 @@ def calibrateMerlin(filename): CalibratedComponent = 'MERLIN/door9' # door9 # == Get the calibration and put results into calibration table == # also put peaks into PeakFile - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door9pos, door9func,\ - outputPeak=True,\ - margin=30,\ - rangeList=range(20)\ # because 20, 21, 22, 23 are defective detectors - ) + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door9pos, door9func, + outputPeak=True, + margin=30, + rangeList=range(20) # because 20, 21, 22, 23 are defective detectors + ) print "Got calibration (new positions of detectors) and put slit peaks into file TubeDemoMerlin01.txt" analisePeakTable(peakTable, 'door9_tube1_peaks') @@ -111,10 +111,10 @@ def calibrateMerlin(filename): door8pos = points7 door8func = points7func CalibratedComponent = 'MERLIN/door8' - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door8pos,\ - door8func,\ - outputPeak = True,\ #change to peakTable to append to peakTable - calibTable = calibrationTable,\ + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door8pos, + door8func, + outputPeak = True, #change to peakTable to append to peakTable + calibTable = calibrationTable, margin = 30) analisePeakTable(peakTable, 'door8_peaks') From 4cb27c84bba6c63e13f69ec3fa1a5012efaac074 Mon Sep 17 00:00:00 2001 From: Andrei Savici Date: Thu, 19 Feb 2015 22:52:54 -0500 Subject: [PATCH 324/414] Update TubeCalibDemoWish_Simple.py Undo some continuations. Refs #11134 --- .../Calibration/Examples/TubeCalibDemoWish_Simple.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py index 549bf85af3d3..66d4f301bf89 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py @@ -43,10 +43,10 @@ def CalibrateWish( RunNumber, PanelNumber): rangeList = range(0,76), outputPeak=True) #calibrate the upper tubes - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, upper_tube, funcForm,\ - rangeList = range(76,152),\ - calibTable=calibrationTable,\ #give the calibration table to append data - outputPeak = peakTable\ #give peak table to append data + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, upper_tube, funcForm, + rangeList = range(76,152), + calibTable=calibrationTable,#give the calibration table to append data + outputPeak = peakTable#give peak table to append data ) print "Got calibration (new positions of detectors)" From 43fe498aaa7714879d1c1d7d83871ba848363f04 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Fri, 20 Feb 2015 09:43:52 +0000 Subject: [PATCH 325/414] Refs #11010 Warn if creating outline of insufficient elements --- .../Geometry/src/Instrument/ObjCompAssembly.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Code/Mantid/Framework/Geometry/src/Instrument/ObjCompAssembly.cpp b/Code/Mantid/Framework/Geometry/src/Instrument/ObjCompAssembly.cpp index a83138ee4639..02c439231f9d 100644 --- a/Code/Mantid/Framework/Geometry/src/Instrument/ObjCompAssembly.cpp +++ b/Code/Mantid/Framework/Geometry/src/Instrument/ObjCompAssembly.cpp @@ -4,11 +4,16 @@ #include "MantidGeometry/Objects/ShapeFactory.h" #include "MantidGeometry/Objects/Object.h" #include "MantidKernel/Exception.h" +#include "MantidKernel/Logger.h" #include #include #include #include +namespace { + Mantid::Kernel::Logger g_log("ObjCompAssembly"); +} + namespace Mantid { namespace Geometry { using Kernel::V3D; @@ -352,6 +357,10 @@ boost::shared_ptr ObjCompAssembly::createOutline() { throw Kernel::Exception::InstrumentDefinitionError("Empty ObjCompAssembly"); } + if (nelements() < 2) { + g_log.warning("Creating outline with fewer than 2 elements. The outline displayed may be inaccurate."); + } + // Get information about the shape and size of a detector std::string type; int otype; From ac0cfd7aa97c4cb0a92121692c1c582eb275eca5 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Fri, 20 Feb 2015 10:49:44 +0000 Subject: [PATCH 326/414] Better handle the failure when num groups > num spectra in component Refs #11140 --- .../src/CreateGroupingWorkspace.cpp | 10 ++++++++-- .../test/CreateGroupingWorkspaceTest.h | 20 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/src/CreateGroupingWorkspace.cpp b/Code/Mantid/Framework/Algorithms/src/CreateGroupingWorkspace.cpp index afa69cc2d060..31c53bf188ff 100644 --- a/Code/Mantid/Framework/Algorithms/src/CreateGroupingWorkspace.cpp +++ b/Code/Mantid/Framework/Algorithms/src/CreateGroupingWorkspace.cpp @@ -169,12 +169,18 @@ void makeGroupingByNumGroups(const std::string compName, int numGroups, // Get detectors for given instument component std::vector detectors; inst->getDetectorsInBank(detectors, compName); + size_t numDetectors = detectors.size(); + + // Sanity check for following calculation + if(numGroups > static_cast(numDetectors)) + throw std::runtime_error("Number of groups must be less than or " + "equal to number of detectors"); // Calculate number of detectors per group - int detectorsPerGroup = static_cast(detectors.size()) / numGroups; + int detectorsPerGroup = static_cast(numDetectors) / numGroups; // Map detectors to group - for (unsigned int detIndex = 0; detIndex < detectors.size(); detIndex++) { + for (unsigned int detIndex = 0; detIndex < numDetectors; detIndex++) { int detectorID = detectors[detIndex]->getID(); int groupNum = (detIndex / detectorsPerGroup) + 1; diff --git a/Code/Mantid/Framework/Algorithms/test/CreateGroupingWorkspaceTest.h b/Code/Mantid/Framework/Algorithms/test/CreateGroupingWorkspaceTest.h index 1c6da9d70818..b1269a78fcf5 100644 --- a/Code/Mantid/Framework/Algorithms/test/CreateGroupingWorkspaceTest.h +++ b/Code/Mantid/Framework/Algorithms/test/CreateGroupingWorkspaceTest.h @@ -174,6 +174,26 @@ class CreateGroupingWorkspaceTest : public CxxTest::TestSuite AnalysisDataService::Instance().remove(outWSName); } + void test_exec_WithFixedGroups_FailOnGroupsGreaterThanDet() + { + // Name of the output workspace. + std::string outWSName("CreateGroupingWorkspaceTest_OutputWS_fail"); + + CreateGroupingWorkspace alg; + TS_ASSERT_THROWS_NOTHING( alg.initialize() ) + TS_ASSERT( alg.isInitialized() ) + TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("InstrumentName", "IRIS") ); + TS_ASSERT_THROWS_NOTHING( alg.setProperty("FixedGroupCount", 52) ); + TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("ComponentName", "graphite") ); + TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("OutputWorkspace", outWSName) ); + TS_ASSERT_THROWS_NOTHING( alg.execute() ); + + // Should fail as IRIS graphite component has only 51 spectra + TS_ASSERT( !alg.isExecuted() ); + + AnalysisDataService::Instance().remove(outWSName); + } + }; From efc0e9f540786a07087d7173d7e22b5623710631 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Fri, 20 Feb 2015 12:16:25 +0000 Subject: [PATCH 327/414] Refs #11142 Fix unstable RemoveExpDecay test --- .../Algorithms/test/RemoveExpDecayTest.h | 107 +++++------------- 1 file changed, 28 insertions(+), 79 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h b/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h index 078029a8e1f2..ce8960f20688 100644 --- a/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h +++ b/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h @@ -4,15 +4,9 @@ #include #include "MantidAPI/AnalysisDataService.h" -#include "MantidAPI/Workspace.h" #include "MantidAlgorithms/RemoveExpDecay.h" -#include "MantidDataHandling/LoadInstrument.h" -#include "MantidDataHandling/LoadMuonNexus2.h" -#include "MantidDataObjects/Workspace2D.h" #include "MantidTestHelpers/WorkspaceCreationHelper.h" -#include - using namespace Mantid::Algorithms; using namespace Mantid::API; @@ -20,107 +14,62 @@ class RemoveExpDecayTest : public CxxTest::TestSuite { public: - void testName() - { - TS_ASSERT_EQUALS( alg.name(), "RemoveExpDecay" ) - } - - void testCategory() - { - TS_ASSERT_EQUALS( alg.category(), "Muon" ) - } + const std::string outputName = "MuonRemoveExpDecay_Output"; void testInit() { + MuonRemoveExpDecay alg; alg.initialize(); - TS_ASSERT( alg.isInitialized() ) + TS_ASSERT(alg.isInitialized()) } - void testLoadNexusAndSetProperties() + void testExecute() { - //This test does not run on Windows64 as is does not support HDF4 files - - loader.initialize(); - loader.setPropertyValue("Filename", "emu00006473.nxs"); - loader.setPropertyValue("OutputWorkspace", "EMU6473"); - TS_ASSERT_THROWS_NOTHING( loader.execute() ); - TS_ASSERT_EQUALS(loader.isExecuted(),true); + auto ws = WorkspaceCreationHelper::Create2DWorkspace(1,1); - alg.setPropertyValue("InputWorkspace", "EMU6473"); - alg.setPropertyValue("OutputWorkspace", "Result"); + MuonRemoveExpDecay alg; + TS_ASSERT_THROWS_NOTHING(alg.initialize()); + TS_ASSERT(alg.isInitialized()) + alg.setProperty("InputWorkspace", ws); + alg.setPropertyValue("OutputWorkspace", outputName); alg.setPropertyValue("Spectra", "0"); - } + TS_ASSERT_THROWS_NOTHING(alg.execute()); + TS_ASSERT(alg.isExecuted()) - void testProperties() - { - //This test does not run on Windows64 as is does not support HDF4 files - TS_ASSERT_EQUALS( alg.getPropertyValue("Spectra"), "0"); + AnalysisDataService::Instance().remove(outputName); } - void testExecute() + void testExecuteWhereSepctraNotSet() { - //This test does not run on Windows64 as is does not support HDF4 files - try - { - TS_ASSERT_EQUALS(alg.execute(),true); - } - catch(std::runtime_error & e) - { - TS_FAIL(e.what()); - } - - Workspace_const_sptr outputWS = AnalysisDataService::Instance().retrieve("Result"); - } + auto ws = WorkspaceCreationHelper::Create2DWorkspace(1,1); - void testWhereOptional3rdArgNotSet() - { - //This test does not run on Windows64 as is does not support HDF4 files - - MuonRemoveExpDecay alg2; - alg2.initialize(); - - alg2.setPropertyValue("InputWorkspace", "EMU6473"); - alg2.setPropertyValue("OutputWorkspace", "MuonRemoveExpDecayResult"); - - try - { - TS_ASSERT_EQUALS(alg2.execute(),true); - } - catch(std::runtime_error & e) - { - TS_FAIL(e.what()); - } + MuonRemoveExpDecay alg; + TS_ASSERT_THROWS_NOTHING(alg.initialize()); + TS_ASSERT(alg.isInitialized()) + alg.setProperty("InputWorkspace", ws); + alg.setPropertyValue("OutputWorkspace", outputName); + TS_ASSERT_THROWS_NOTHING(alg.execute()); + TS_ASSERT(alg.isExecuted()) + + AnalysisDataService::Instance().remove(outputName); } void test_yUnitLabel() { - const std::string outputWSName = "RemoveExpDecayTest_yUnitLabel_OutputWS"; - auto ws = WorkspaceCreationHelper::Create2DWorkspace(1,1); MuonRemoveExpDecay alg; alg.initialize(); alg.setProperty("InputWorkspace", ws); - alg.setProperty("OutputWorkspace", outputWSName); + alg.setProperty("OutputWorkspace", outputName); alg.execute(); - auto result = AnalysisDataService::Instance().retrieveWS(outputWSName); - + auto result = AnalysisDataService::Instance().retrieveWS(outputName); TS_ASSERT(result); + TS_ASSERT_EQUALS(result->YUnitLabel(), "Asymmetry"); - if( result ) - { - TS_ASSERT_EQUALS( result->YUnitLabel(), "Asymmetry" ); - } - - AnalysisDataService::Instance().remove(outputWSName); + AnalysisDataService::Instance().remove(outputName); } - - -private: - MuonRemoveExpDecay alg; - Mantid::DataHandling::LoadMuonNexus2 loader; - }; #endif /*MUONREMOVEEXPDECAYTEST_H_*/ From 2178ddfce445989313f536f84911327b61baa0f6 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Fri, 20 Feb 2015 12:28:39 +0000 Subject: [PATCH 328/414] Ignore non workspace output properties in ScriptBuilder Refs #11128 --- .../Framework/API/src/ScriptBuilder.cpp | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/API/src/ScriptBuilder.cpp b/Code/Mantid/Framework/API/src/ScriptBuilder.cpp index 259d2848ea8a..ec68c8f342db 100644 --- a/Code/Mantid/Framework/API/src/ScriptBuilder.cpp +++ b/Code/Mantid/Framework/API/src/ScriptBuilder.cpp @@ -4,6 +4,8 @@ #include "MantidAPI/AlgorithmFactory.h" #include "MantidAPI/HistoryItem.h" #include "MantidAPI/ScriptBuilder.h" +#include "MantidKernel/Property.h" +#include "MantidKernel/Logger.h" #include @@ -13,6 +15,11 @@ namespace API { using Mantid::Kernel::PropertyHistory_sptr; using Mantid::Kernel::PropertyHistory_const_sptr; +namespace +{ + Mantid::Kernel::Logger g_log("ScriptBuilder"); +} + ScriptBuilder::ScriptBuilder(boost::shared_ptr view, std::string versionSpecificity) : m_historyItems(view->getAlgorithmsList()), m_output(), @@ -156,13 +163,30 @@ ScriptBuilder::buildAlgorithmString(AlgorithmHistory_const_sptr algHistory) { */ const std::string ScriptBuilder::buildPropertyString(PropertyHistory_const_sptr propHistory) { + using Mantid::Kernel::Direction; + + // Create a vector of all non workspace property type names + std::vector nonWorkspaceTypes; + nonWorkspaceTypes.push_back("number"); + nonWorkspaceTypes.push_back("boolean"); + nonWorkspaceTypes.push_back("string"); + std::string prop = ""; + // No need to specify value for default properties if (!propHistory->isDefault()) { - if (propHistory->type() == "number") { + // Do not give values to output properties other than workspace properties + if (find(nonWorkspaceTypes.begin(), nonWorkspaceTypes.end(), propHistory->type()) != nonWorkspaceTypes.end() + && propHistory->direction() == Direction::Output) { + g_log.debug() << "Ignoring property " << propHistory->name() + << " of type " << propHistory->type() << std::endl; + // Handle numerical properties + } else if (propHistory->type() == "number") { prop = propHistory->name() + "=" + propHistory->value(); + // Handle boolean properties } else if (propHistory->type() == "boolean") { std::string value = (propHistory->value() == "1" ? "True" : "False"); prop = propHistory->name() + "=" + value; + // Handle all other property types } else { std::string opener = "='"; if (propHistory->value().find('\\') != std::string::npos) { From 6d45da40a624c2e9d644bc7c492cf2e32907782b Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Fri, 20 Feb 2015 13:02:11 +0000 Subject: [PATCH 329/414] Refs #11142 Remove dependency on ADS --- .../Algorithms/test/RemoveExpDecayTest.h | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h b/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h index ce8960f20688..5232ad9c519f 100644 --- a/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h +++ b/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h @@ -3,7 +3,6 @@ #include -#include "MantidAPI/AnalysisDataService.h" #include "MantidAlgorithms/RemoveExpDecay.h" #include "MantidTestHelpers/WorkspaceCreationHelper.h" @@ -29,14 +28,13 @@ class RemoveExpDecayTest : public CxxTest::TestSuite MuonRemoveExpDecay alg; TS_ASSERT_THROWS_NOTHING(alg.initialize()); - TS_ASSERT(alg.isInitialized()) + TS_ASSERT(alg.isInitialized()); + alg.setChild(true); alg.setProperty("InputWorkspace", ws); alg.setPropertyValue("OutputWorkspace", outputName); alg.setPropertyValue("Spectra", "0"); TS_ASSERT_THROWS_NOTHING(alg.execute()); TS_ASSERT(alg.isExecuted()) - - AnalysisDataService::Instance().remove(outputName); } void testExecuteWhereSepctraNotSet() @@ -45,13 +43,12 @@ class RemoveExpDecayTest : public CxxTest::TestSuite MuonRemoveExpDecay alg; TS_ASSERT_THROWS_NOTHING(alg.initialize()); - TS_ASSERT(alg.isInitialized()) + TS_ASSERT(alg.isInitialized()); + alg.setChild(true); alg.setProperty("InputWorkspace", ws); alg.setPropertyValue("OutputWorkspace", outputName); TS_ASSERT_THROWS_NOTHING(alg.execute()); TS_ASSERT(alg.isExecuted()) - - AnalysisDataService::Instance().remove(outputName); } void test_yUnitLabel() @@ -60,15 +57,14 @@ class RemoveExpDecayTest : public CxxTest::TestSuite MuonRemoveExpDecay alg; alg.initialize(); + alg.setChild(true); alg.setProperty("InputWorkspace", ws); alg.setProperty("OutputWorkspace", outputName); alg.execute(); - auto result = AnalysisDataService::Instance().retrieveWS(outputName); + MatrixWorkspace_sptr result = alg.getProperty("OutputWorkspace"); TS_ASSERT(result); TS_ASSERT_EQUALS(result->YUnitLabel(), "Asymmetry"); - - AnalysisDataService::Instance().remove(outputName); } }; From 77a79f6fec5155161cc85e6f3c957c821208867e Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Fri, 20 Feb 2015 13:38:44 +0000 Subject: [PATCH 330/414] Extend unit test to test the original failure case Adds an output parameter set by the algorithm which would have previously been added to the script output. Refs #11128 --- .../Framework/API/test/ScriptBuilderTest.h | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/Code/Mantid/Framework/API/test/ScriptBuilderTest.h b/Code/Mantid/Framework/API/test/ScriptBuilderTest.h index 8bd1da860939..f413726083e7 100644 --- a/Code/Mantid/Framework/API/test/ScriptBuilderTest.h +++ b/Code/Mantid/Framework/API/test/ScriptBuilderTest.h @@ -27,7 +27,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite const std::string workspaceMethodName() const { return "methodname"; } const std::string workspaceMethodOnTypes() const { return "MatrixWorkspace;ITableWorkspace"; } const std::string workspaceMethodInputProperty() const { return "InputWorkspace"; } - + void init() { declareProperty("PropertyA", "Hello"); @@ -52,11 +52,12 @@ class ScriptBuilderTest : public CxxTest::TestSuite const std::string workspaceMethodName() const { return "methodname"; } const std::string workspaceMethodOnTypes() const { return "MatrixWorkspace;ITableWorkspace"; } const std::string workspaceMethodInputProperty() const { return "InputWorkspace"; } - + void init() { declareProperty("PropertyA", "Hello"); declareProperty("PropertyB", "World"); + declareProperty("PropertyC", "", Direction::Output); } void exec() { @@ -65,6 +66,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite alg->initialize(); alg->setProperty("PropertyA", "I Don't exist!"); alg->execute(); + setProperty("PropertyC", "I have been set!"); } }; @@ -81,7 +83,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite const std::string workspaceMethodName() const { return "methodname"; } const std::string workspaceMethodOnTypes() const { return "MatrixWorkspace;ITableWorkspace"; } const std::string workspaceMethodInputProperty() const { return "InputWorkspace"; } - + void init() { declareProperty("PropertyA", 13); @@ -115,7 +117,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite const std::string workspaceMethodName() const { return "methodname"; } const std::string workspaceMethodOnTypes() const { return "Workspace;MatrixWorkspace;ITableWorkspace"; } const std::string workspaceMethodInputProperty() const { return "InputWorkspace"; } - + void init() { declareProperty(new WorkspaceProperty("InputWorkspace", "", Direction::Input)); @@ -137,7 +139,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite }; private: - + public: void setUp() @@ -155,7 +157,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite Mantid::API::AlgorithmFactory::Instance().unsubscribe("BasicAlgorithm",1); Mantid::API::AlgorithmFactory::Instance().unsubscribe("SubAlgorithm",1); } - + void test_Build_Simple() { std::string result[] = { @@ -220,7 +222,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite alg->setRethrows(true); alg->setProperty("InputWorkspace", input); alg->setPropertyValue("OutputWorkspace", "test_output_workspace"); - alg->execute(); + alg->execute(); auto ws = AnalysisDataService::Instance().retrieveWS("test_output_workspace"); auto wsHist = ws->getHistory(); @@ -280,7 +282,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite alg->setProperty("InputWorkspace", "test_output_workspace"); alg->setPropertyValue("OutputWorkspace", "test_output_workspace"); alg->execute(); - + auto ws = AnalysisDataService::Instance().retrieveWS("test_output_workspace"); auto wsHist = ws->getHistory(); auto view = wsHist.createView(); @@ -305,7 +307,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite AnalysisDataService::Instance().remove("test_input_workspace"); } - + void test_Build_Simple_with_backslash() { //checks that property values with \ get prefixed with r, eg. filename=r'c:\test\data.txt' From 0f3c593260db8d9f768757d268f0196fcbcea07f Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Fri, 20 Feb 2015 14:21:10 +0000 Subject: [PATCH 331/414] Ran clang format on modified files Refs #11128 --- Code/Mantid/Framework/API/src/ScriptBuilder.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Code/Mantid/Framework/API/src/ScriptBuilder.cpp b/Code/Mantid/Framework/API/src/ScriptBuilder.cpp index ec68c8f342db..2171a29f2486 100644 --- a/Code/Mantid/Framework/API/src/ScriptBuilder.cpp +++ b/Code/Mantid/Framework/API/src/ScriptBuilder.cpp @@ -15,9 +15,8 @@ namespace API { using Mantid::Kernel::PropertyHistory_sptr; using Mantid::Kernel::PropertyHistory_const_sptr; -namespace -{ - Mantid::Kernel::Logger g_log("ScriptBuilder"); +namespace { +Mantid::Kernel::Logger g_log("ScriptBuilder"); } ScriptBuilder::ScriptBuilder(boost::shared_ptr view, @@ -175,18 +174,19 @@ ScriptBuilder::buildPropertyString(PropertyHistory_const_sptr propHistory) { // No need to specify value for default properties if (!propHistory->isDefault()) { // Do not give values to output properties other than workspace properties - if (find(nonWorkspaceTypes.begin(), nonWorkspaceTypes.end(), propHistory->type()) != nonWorkspaceTypes.end() - && propHistory->direction() == Direction::Output) { + if (find(nonWorkspaceTypes.begin(), nonWorkspaceTypes.end(), + propHistory->type()) != nonWorkspaceTypes.end() && + propHistory->direction() == Direction::Output) { g_log.debug() << "Ignoring property " << propHistory->name() << " of type " << propHistory->type() << std::endl; - // Handle numerical properties + // Handle numerical properties } else if (propHistory->type() == "number") { prop = propHistory->name() + "=" + propHistory->value(); - // Handle boolean properties + // Handle boolean properties } else if (propHistory->type() == "boolean") { std::string value = (propHistory->value() == "1" ? "True" : "False"); prop = propHistory->name() + "=" + value; - // Handle all other property types + // Handle all other property types } else { std::string opener = "='"; if (propHistory->value().find('\\') != std::string::npos) { From f24639d32ec59f217a70e419b4ef7a5c887543ab Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Fri, 20 Feb 2015 14:51:50 +0000 Subject: [PATCH 332/414] Add bounded validator to keep group count property positive Refs #11140 --- .../Framework/Algorithms/src/CreateGroupingWorkspace.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/src/CreateGroupingWorkspace.cpp b/Code/Mantid/Framework/Algorithms/src/CreateGroupingWorkspace.cpp index 31c53bf188ff..5b50cd0fd5ce 100644 --- a/Code/Mantid/Framework/Algorithms/src/CreateGroupingWorkspace.cpp +++ b/Code/Mantid/Framework/Algorithms/src/CreateGroupingWorkspace.cpp @@ -9,6 +9,7 @@ #include #include #include "MantidAPI/FileProperty.h" +#include "MantidKernel/BoundedValidator.h" #include "MantidKernel/ListValidator.h" namespace { @@ -92,9 +93,10 @@ void CreateGroupingWorkspace::init() { declareProperty("MaxRecursionDepth", 5, "Number of levels to search into the instrument (default=5)"); - declareProperty("FixedGroupCount", 0, "Used to distribute the detectors of a " - "given component into a fixed number " - "of groups"); + declareProperty("FixedGroupCount", 0, + boost::make_shared >(0, INT_MAX), + "Used to distribute the detectors of a given component into " + "a fixed number of groups"); declareProperty("ComponentName", "", "Specify the instrument component to " "group into a fixed number of groups"); From 103ac646e7fd98d33adddd70ce184a3a1c6a50c4 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Fri, 20 Feb 2015 15:05:44 +0000 Subject: [PATCH 333/414] Refs #11142 Fix compilation error --- Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h b/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h index 5232ad9c519f..c8a27eb888e3 100644 --- a/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h +++ b/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h @@ -9,12 +9,12 @@ using namespace Mantid::Algorithms; using namespace Mantid::API; +const std::string outputName = "MuonRemoveExpDecay_Output"; + class RemoveExpDecayTest : public CxxTest::TestSuite { public: - const std::string outputName = "MuonRemoveExpDecay_Output"; - void testInit() { MuonRemoveExpDecay alg; From 1d316767582cf2b7942e297afcffd9d4bea01c7a Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Fri, 20 Feb 2015 15:17:47 +0000 Subject: [PATCH 334/414] Addess undeclared members in functions Refs #11147 --- .../plugins/functions/DSFinterp1DFit.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py index 5f5028b06537..a5848154113a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py @@ -31,6 +31,20 @@ class DSFinterp1DFit(IFunction1D): + _RegressionTypes = None + _minWindow = None + _InputWorkspaces = None + _LoadErrors = None + _WorkspaceIndex = None + _ParameterValues = None + _fmin = None + _fmax = None + _LocalRegression = None + _RegressionType = None + _RegressionWindow = None + _xvalues = None + _channelgroup = None + def category(self): return 'QuasiElastic' From 9eb6943c9b39ee203a915d14ce9c703af2929f8d Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Fri, 20 Feb 2015 15:41:20 +0000 Subject: [PATCH 335/414] Started clearing warnings in workflow algorithms Refs #11146 --- .../CreateCalibrationWorkspace.py | 8 +++++++ .../WorkflowAlgorithms/DensityOfStates.py | 18 ++++++++++++++++ .../ElasticWindowMultiple.py | 12 +++++++++++ .../algorithms/WorkflowAlgorithms/Fury.py | 11 ++++++++++ .../IndirectILLReduction.py | 14 +++++++++++++ .../WorkflowAlgorithms/IndirectResolution.py | 12 +++++++++++ .../IndirectTransmissionMonitor.py | 6 ++++++ .../InelasticIndirectReduction.py | 21 +++++++++++++++++++ .../algorithms/WorkflowAlgorithms/JumpFit.py | 8 +++++++ 9 files changed, 110 insertions(+) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateCalibrationWorkspace.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateCalibrationWorkspace.py index e8aa6020978f..4f137fc55c0b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateCalibrationWorkspace.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateCalibrationWorkspace.py @@ -7,6 +7,14 @@ class CreateCalibrationWorkspace(DataProcessorAlgorithm): + _input_files = None + _out_ws = None + _peak_range = None + _back_range = None + _spec_range = None + _intensity_scale = None + _plot = None + def category(self): return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic' diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py index 291d9fd08749..97c33281bda8 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py @@ -9,6 +9,24 @@ class DensityOfStates(PythonAlgorithm): + _float_regex = None + _temperature = None + _bin_width = None + _spec_type = None + _peak_func = None + _ws_name = None + _peak_width = None + _scale = None + _zero_threshold = None + _ions = None + _sum_contributions = None + _scale_by_cross_section = None + _calc_partial = None + _ion_dict = None + _partial_ion_numbers = None + _num_ions = None + _num_branches = None + def summary(self): return "Calculates phonon densities of states, Raman and IR spectrum." diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py index ae1dbd3b9bd7..e02891c53bbf 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py @@ -22,6 +22,18 @@ def _normalize_to_lowest_temp(elt_ws_name): class ElasticWindowMultiple(DataProcessorAlgorithm): + _plot = None + _sample_log_name = None + _input_workspaces = None + _q_workspace = None + _q2_workspace = None + _elf_workspace = None + _elt_workspace = None + _range_1_start = None + _range_1_end = None + _range_2_start = None + _range_2_end = None + def category(self): return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic' diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py index 70e6e93fd478..6f2eb7f49bdf 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py @@ -8,6 +8,17 @@ class Fury(PythonAlgorithm): + _sample = None + _resolution = None + _e_min = None + _e_max = None + _number_points_per_bin = None + _parameter_table = None + _output_workspace = None + _plot = None + _save = None + _dry_run = None + def category(self): return "Workflow\\MIDAS;PythonAlgorithms" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py index 08e6684d5409..d49c6b00b9be 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py @@ -10,6 +10,20 @@ class IndirectILLReduction(DataProcessorAlgorithm): + _raw_workspace = None + _red_workspace = None + _red_left_workspace = None + _red_right_workspace = None + _map_file = None + _use_mirror_mode = None + _save = None + _plot = None + _instrument_name = None + _run_number = None + _analyser = None + _reflection = None + _run_name = None + def category(self): return "Workflow\\MIDAS;Inelastic;PythonAlgorithms" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py index 2d6ef948abd6..fcf2480d0bd2 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py @@ -6,6 +6,18 @@ class IndirectResolution(DataProcessorAlgorithm): + _input_files = None + _out_ws = None + _instrument = None + _analyser = None + _reflection = None + _detector_range = None + _background = None + _rebin_string = None + _scale_factor = None + _plot = None + _save = None + def category(self): return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic' diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmissionMonitor.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmissionMonitor.py index 87f1d83cd956..c6363f4b56d1 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmissionMonitor.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmissionMonitor.py @@ -9,6 +9,12 @@ class IndirectTransmissionMonitor(PythonAlgorithm): + _sample_ws_in = None + _can_ws_in = None + _out_ws = None + _plot = None + _save = None + def category(self): return "Workflow\\Inelastic;PythonAlgorithms;Inelastic" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py index ccb95aedc155..abf9e5a6aa04 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py @@ -5,6 +5,27 @@ class InelasticIndirectReduction(DataProcessorAlgorithm): + _out_ws_group = None + _data_files = None + _instrument = None + _analyser = None + _reflection = None + _param_file = None + _detector_range = None + _background_range = None + _calib_ws_name = None + _detailed_balance = None + _rebin_string = None + _scale_factor = None + _sum_files = None + _map_file = None + _save_formats = None + _plot_type = None + _use_calib_ws = None + _use_detailed_balance = None + _use_scale_factor = None + _plot_ws = None + def category(self): return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic' diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py index 4b1ccd2e651a..07f8ec2f2af8 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py @@ -5,6 +5,14 @@ class JumpFit(PythonAlgorithm): + _in_ws = None + _out_name = None + _jump_function = None + _width = None + _q_min = None + _q_max = None + _plot = None + _save = None def category(self): return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic' From 6f41707c537222cdc12e4f5d8341bf342b749fb0 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Fri, 20 Feb 2015 16:07:04 +0000 Subject: [PATCH 336/414] Fix remaining issues in WorkflowAlgorithms Refs #11146 --- .../plugins/algorithms/WorkflowAlgorithms/MolDyn.py | 9 +++++++++ .../WorkflowAlgorithms/OSIRISDiffractionReduction.py | 8 ++++++++ .../algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py | 2 ++ .../plugins/algorithms/WorkflowAlgorithms/TimeSlice.py | 10 ++++++++++ .../algorithms/WorkflowAlgorithms/USANSReduction.py | 7 +++++++ 5 files changed, 36 insertions(+) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MolDyn.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MolDyn.py index 5e0b12ef31cc..22940d8b51e4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MolDyn.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MolDyn.py @@ -61,6 +61,15 @@ def _make_list(a, l1, l2): class MolDyn(PythonAlgorithm): + _plot = None + _save = None + _sam_path = None + _symmetrise = None + _functions = None + _emax = None + _res_ws = None + _out_ws = None + def category(self): return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic' diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py index 9ce72199366f..1e0539dbcb42 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py @@ -145,6 +145,14 @@ def isInRanges(rangeList, n): class OSIRISDiffractionReduction(PythonAlgorithm): """ Handles the reduction of OSIRIS Diffraction Data. """ + + _cal = None + _outputWsName = None + _sams = None + _vans = None + _samMap = None + _vanMap = None + def category(self): return 'Diffraction;PythonAlgorithms' diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py index 6736b723ce04..b3974e7f1516 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py @@ -10,6 +10,8 @@ class SANSAbsoluteScale(PythonAlgorithm): Normalise detector counts by the sample thickness """ + instrument = None + def category(self): return "Workflow\\SANS\\UsesPropertyManager" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TimeSlice.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TimeSlice.py index 45895d7ad55d..079f9d934305 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TimeSlice.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TimeSlice.py @@ -47,6 +47,16 @@ def _count_monitors(raw_file): class TimeSlice(PythonAlgorithm): + _raw_files = None + _spectra_range = None + _peak_range = None + _output_ws_name_suffix = None + _background_range = None + _calib_ws = None + _out_ws_group = None + _plot = None + _save = None + def category(self): return 'PythonAlgorithms;Inelastic' diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py index 5bbf242df339..eb9bf6ba06b6 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py @@ -9,6 +9,13 @@ class USANSReduction(PythonAlgorithm): + wl_list = None + data_files = None + total_points = None + q_output = None + iq_output = None + iq_err_output = None + def category(self): return "SANS" From fb4f6977103ef4427db199a93759809dd4f5331f Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Fri, 20 Feb 2015 16:55:57 +0000 Subject: [PATCH 337/414] Re #7083 Add widget to select function of logvalue --- .../src/PlotAsymmetryByLogValue.cpp | 10 + .../PlotAsymmetryByLogValueDialog.ui | 678 +++++++++--------- .../src/PlotAsymmetryByLogValueDialog.cpp | 2 + 3 files changed, 362 insertions(+), 328 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp index bc9cb6bda5c6..c40e52dffe40 100644 --- a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp +++ b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp @@ -94,6 +94,16 @@ void PlotAsymmetryByLogValue::init() { boost::make_shared(options), "The calculation type: 'Integral' or 'Differential'."); + std::vector optionsLog; + optionsLog.push_back("Mean"); + optionsLog.push_back("Min"); + optionsLog.push_back("Max"); + optionsLog.push_back("First"); + optionsLog.push_back("Last"); + declareProperty("Function", "Last", + boost::make_shared(optionsLog), + "The calculation type: 'Integral' or 'Differential'."); + declareProperty( "TimeMin", EMPTY_DBL(), "The beginning of the time interval used in the calculations."); diff --git a/Code/Mantid/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PlotAsymmetryByLogValueDialog.ui b/Code/Mantid/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PlotAsymmetryByLogValueDialog.ui index 5d891ba75661..57ba9eee696c 100644 --- a/Code/Mantid/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PlotAsymmetryByLogValueDialog.ui +++ b/Code/Mantid/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PlotAsymmetryByLogValueDialog.ui @@ -1,351 +1,373 @@ - PlotAsymmetryByLogValueDialog - - - - 0 - 0 - 479 - 544 - - - - PlotAsymmetryByLogValue - - - - - - - - + PlotAsymmetryByLogValueDialog + + + + 0 + 0 + 479 + 544 + + + + PlotAsymmetryByLogValue + + - - - - - First run + + + - - - - - - - - - Browse - - - - + + + + + + + First run + + + + + + + + + + Browse + + + + + + + + + + + Last run + + + + + + + + + + Browse + + + + + + + + + + + Log value + + + + + + + + 0 + 0 + + + + true + + + + + + + + + + Function + + + + + + + + 0 + 0 + + + + + + + + + + + + + + Output workspace + + + + + + + + + + + + Type + + + + + + + + 0 + 0 + + + + + + + + + + - - - - - Last run - - - - - - - - - - Browse + + + Periods - - - + + + + + + + Red + + + + + + + + + + Green + + + + + + + + + + - - - - - Log value - - - - - - - - 0 - 0 - - - - true + + + Grouping - - - + + + + + + + Forward spectra + + + + + + + false + + + + + + + Backward spectra + + + + + + + + + + - - - - - Output workspace + + + Time - - - - - - - - - - - Type - - - - - - - - 0 - 0 - - - - - - - + + + + + + + Min + + + + + + + + + + Max + + + + + + + + + + - - - - - - - Periods - - - - - - - Red + + + Dead Time Correction - - - - - - - - - Green - - - - - - - + + + + + QLayout::SetDefaultConstraint + + + + + Type + + + + + + + + 0 + 0 + + + + + + + + + + + 0 + + + + + File + + + + + + + + + + Browse + + + + + + + + - - - - - - - Grouping - - - - - - - Forward spectra - - - - - - - false - - - - - - - Backward spectra - - - - - - - - - - - - - - - Time - - - - - - - - Min - - - - - - - - - - Max + + + 6 - - - - - - - - - - - - - - Dead Time Correction - - - - - - QLayout::SetDefaultConstraint - - - - - Type - - - - - - - - 0 - 0 - - - - - - - - - - - 0 - - - - - File - - - - - - - - - - Browse - - - + + + + + 31 + 26 + + + + ? + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + OK + + + + + + + Cancel + + + - - - - - - - - 6 - - - - - - 31 - 26 - - - - ? - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - OK - - - - - - - Cancel - - - - - - - - firstRunBox - browseFirstButton - lastRunBox - browseLastButton - logBox - outWSBox - redBox - forwardBox - timeMinBox - - - + + + firstRunBox + browseFirstButton + lastRunBox + browseLastButton + logBox + outWSBox + redBox + forwardBox + timeMinBox + + + diff --git a/Code/Mantid/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp b/Code/Mantid/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp index 3d6fe444ee56..9d9acccbb437 100644 --- a/Code/Mantid/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp +++ b/Code/Mantid/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp @@ -66,6 +66,7 @@ void PlotAsymmetryByLogValueDialog::initLayout() tie(m_uiForm.firstRunBox, "FirstRun", m_uiForm.FirstRunLayout); tie(m_uiForm.lastRunBox, "LastRun", m_uiForm.LastRunLayout); tie(m_uiForm.logBox, "LogValue"); + tie(m_uiForm.typeBoxLog, "Function"); tie(m_uiForm.outWSBox, "OutputWorkspace", m_uiForm.OutputWSLayout); tie(m_uiForm.typeBox, "Type"); tie(m_uiForm.redBox, "Red"); @@ -96,6 +97,7 @@ void PlotAsymmetryByLogValueDialog::initLayout() // Fill ComboBoxes with allowed values fillAndSetComboBox("Type", m_uiForm.typeBox); + fillAndSetComboBox("Function", m_uiForm.typeBoxLog); fillAndSetComboBox("DeadTimeCorrType", m_uiForm.dtcType); // Fill log values from the file From 09b9aa4320ccba7944e3d918de95aedfa97ad412 Mon Sep 17 00:00:00 2001 From: Anders Markvardsen Date: Fri, 20 Feb 2015 16:58:02 +0000 Subject: [PATCH 338/414] updates to confidence() method. Re #11141 --- .../Framework/DataHandling/src/LoadMcStas.cpp | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/Code/Mantid/Framework/DataHandling/src/LoadMcStas.cpp b/Code/Mantid/Framework/DataHandling/src/LoadMcStas.cpp index 2e80fb9e8c3c..027c60f08be6 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadMcStas.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadMcStas.cpp @@ -543,24 +543,24 @@ void LoadMcStas::readHistogramData( */ int LoadMcStas::confidence(Kernel::NexusDescriptor &descriptor) const { using namespace ::NeXus; - // We will look at the first entry and check for a - // simulation class that contains a name attribute with the value=mcstas + // look at to see if entry1/simulation/name exist first and then + // if its value = mccode int confidence(0); - try { - ::NeXus::File file = ::NeXus::File(descriptor.filename()); - auto entries = file.getEntries(); - if (!entries.empty()) { - auto firstIt = entries.begin(); - file.openGroup(firstIt->first, firstIt->second); - file.openGroup("simulation", "NXnote"); - std::string nameAttrValue; - file.readData("name", nameAttrValue); - if (boost::iequals(nameAttrValue, "mccode")) - confidence = 98; - file.closeGroup(); - file.closeGroup(); + if(descriptor.pathExists("/entry1/simulation/name")) { + try { + // need to look inside file to check value of entry1/simulation/name + ::NeXus::File file = ::NeXus::File(descriptor.filename()); + file.openGroup( descriptor.firstEntryNameType().first, descriptor.firstEntryNameType().second); + file.openGroup("simulation", "NXnote"); + std::string value; + // check if entry1/simulation/name equals mccode + file.readData("name", value); + if (boost::iequals(value, "mccode")) + confidence = 98; + file.closeGroup(); + file.closeGroup(); + } catch (::NeXus::Exception &) { } - } catch (::NeXus::Exception &) { } return confidence; } From b9dd256f56af48af4ce140cb35abbf5c9ca12930 Mon Sep 17 00:00:00 2001 From: Anders Markvardsen Date: Fri, 20 Feb 2015 17:06:43 +0000 Subject: [PATCH 339/414] AutoTestData now External Data. re #11141 --- .../UsageData/INES_Definition.vtp | 22 ------------------- 1 file changed, 22 deletions(-) delete mode 100644 Test/AutoTestData/UsageData/INES_Definition.vtp diff --git a/Test/AutoTestData/UsageData/INES_Definition.vtp b/Test/AutoTestData/UsageData/INES_Definition.vtp deleted file mode 100644 index 23a71effa310..000000000000 --- a/Test/AutoTestData/UsageData/INES_Definition.vtp +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - From 734bd598ecba63a649edeeed3cab53cb455f4d32 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Fri, 20 Feb 2015 17:35:20 +0000 Subject: [PATCH 340/414] Re #7083 Add functions of log value --- .../PlotAsymmetryByLogValue.h | 2 ++ .../src/PlotAsymmetryByLogValue.cpp | 33 ++++++++++++------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h index 26508de9191b..e10891b09dc7 100644 --- a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h +++ b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h @@ -116,6 +116,8 @@ class DLLExport PlotAsymmetryByLogValue : public API::Algorithm { MantidVec m_diffX, m_diffY, m_diffE; // LogValue name std::string m_logName; + // LogValue function + std::string m_logFunc; }; } // namespace Algorithm diff --git a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp index c40e52dffe40..53b0ea679405 100644 --- a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp +++ b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp @@ -37,11 +37,21 @@ namespace // anonymous */ template bool convertLogToDouble(const Mantid::Kernel::Property *property, - double &value) { + double &value, const std::string& function) { const Mantid::Kernel::TimeSeriesProperty *log = dynamic_cast *>(property); if (log) { - value = static_cast(log->lastValue()); + if (function=="Mean") { + value = static_cast(log->timeAverageValue()); + } else if (function=="First") { + value = static_cast(log->firstValue()); + } else if (function=="Min") { + value = static_cast(log->minValue()); + } else if (function=="Max") { + value = static_cast(log->maxValue()); + } else { // Default + value = static_cast(log->lastValue()); + } return true; } auto tlog = @@ -160,6 +170,8 @@ void PlotAsymmetryByLogValue::exec() { // Get runs std::string firstFN = getProperty("FirstRun"); std::string lastFN = getProperty("LastRun"); + // Get function to apply to logValue + m_logFunc = getProperty("Function"); // Parse run names and get the number of runs std::string fnBase, fnExt; @@ -630,24 +642,23 @@ double PlotAsymmetryByLogValue::getLogValue(MatrixWorkspace &ws) { if (!property) { throw std::invalid_argument("Log " + m_logName + " does not exist."); } - double value = 0; // try different property types - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; // try if it's a string and can be lexically cast to double auto slog = From 0902d9f14f87c34b2ee7527b2dee862a3dca6de6 Mon Sep 17 00:00:00 2001 From: Steven Hahn Date: Fri, 20 Feb 2015 18:39:59 -0500 Subject: [PATCH 341/414] Refs #11153. Replace BRepMesh::Mesh with BRepMesh_IncrementalMesh. --- .../Framework/Geometry/src/Rendering/OCGeometryGenerator.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryGenerator.cpp b/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryGenerator.cpp index bab1459e647d..d7b2f36805bc 100644 --- a/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryGenerator.cpp +++ b/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryGenerator.cpp @@ -44,7 +44,7 @@ GCC_DIAG_OFF(cast-qual) #include #include #include -#include +#include #include #include #include @@ -121,7 +121,7 @@ void OCGeometryGenerator::AnalyzeObject() { TopoDS_Shape Result = AnalyzeRule(const_cast(top)); try { ObjSurface = new TopoDS_Shape(Result); - BRepMesh::Mesh(Result, 0.001); + BRepMesh_IncrementalMesh(Result, 0.001); } catch (StdFail_NotDone &) { g_log.error("Cannot build the geometry. Check the geometry definition"); } From 8d6a0fafbad4be90aab4ff9b51baa3c31e9e64a8 Mon Sep 17 00:00:00 2001 From: Andrei Savici Date: Fri, 20 Feb 2015 23:51:54 -0500 Subject: [PATCH 342/414] Update ScriptRepositoryImpl.cpp Unused variable reported in [cppcheck] (http://builds.mantidproject.org/view/Wall%20display/job/cppcheck_master/8/cppcheckResult/) --- .../Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp b/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp index d03969c8659d..1f0f1ea81759 100644 --- a/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp +++ b/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp @@ -1308,7 +1308,7 @@ void ScriptRepositoryImpl::doDownloadFile(const std::string &url_file, Kernel::InternetHelper inetHelper; inetHelper.setTimeout(3); // 3 seconds - std::stringstream ss; + //std::stringstream ss; int status = inetHelper.downloadFile(url_file,local_file_path); g_log.debug() << "Answer from mantid web: " << status << std::endl; From cc7fd1da8bea605ce2be3f9d42de68fd6146d141 Mon Sep 17 00:00:00 2001 From: Andrei Savici Date: Sat, 21 Feb 2015 00:49:42 -0500 Subject: [PATCH 343/414] Update CppCheck_Suppressions.txt There is a cppcheck issue "Unmatched suppression: unusedFunction". This happens because we don't have unused functions and we try to suppress the "unusedFunction" warning. The suppression happens globally, in CppCheck_Suppressions.txt --- Code/Mantid/Build/CMake/CppCheck_Suppressions.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Build/CMake/CppCheck_Suppressions.txt b/Code/Mantid/Build/CMake/CppCheck_Suppressions.txt index 16965a971a8b..c808e945f406 100644 --- a/Code/Mantid/Build/CMake/CppCheck_Suppressions.txt +++ b/Code/Mantid/Build/CMake/CppCheck_Suppressions.txt @@ -4,6 +4,6 @@ // suppress in all files - BE CAREFULL not to leave trailing spaces after the rule id. or empty lines // For a library this is not a problem per se -unusedFunction +// unusedFunction // cppcheck has problems handling the number of pre-processor definitions used in the DLL_EXPORTs -class_X_Y \ No newline at end of file +class_X_Y From e80b891afa24212f31db2b971567dd95223510fb Mon Sep 17 00:00:00 2001 From: Andrei Savici Date: Sat, 21 Feb 2015 04:00:06 -0500 Subject: [PATCH 344/414] Undo some changes that broke systemtests. Refs #11154 I accidentally deleted the content of ConjoinFiles algorithm. It was not picked up by the unittests since there is none for this algorithm. The sns_command_interface has a lot of unused imports. But those are passed on to be used in the systemtests. --- .../plugins/algorithms/ConjoinFiles.py | 66 +++++++++++++++++++ .../instruments/sans/sns_command_interface.py | 42 ++++++------ 2 files changed, 87 insertions(+), 21 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py index 5870377471bc..6acb8d39092f 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py @@ -1 +1,67 @@ #pylint: disable=no-init,invalid-name +from mantid.api import * +from mantid.kernel import * +from mantid.simpleapi import * +import os + +class ConjoinFiles(PythonAlgorithm): + def category(self): + return "DataHandling;PythonAlgorithms" + + def name(self): + return "ConjoinFiles" + + def summary(self): + return "Conjoin two file-based workspaces." + + def __load(self, directory, instr, run, loader, exts, wksp): + filename = None + for ext in exts: + filename = "%s_%s%s" % (instr, str(run), ext) + if len(directory) > 0: + filename = os.path.join(directory, filename) + if not os.path.exists(filename): + continue + try: + self.log().information("Trying to load '%s'" % filename) + loader(Filename=filename, OutputWorkspace=wksp) + return + except Exception, e: + logger.information(str(e)) + raise RuntimeError("Failed to load run %s from file %s" % (str(run), filename)) + + def PyInit(self): + greaterThanZero = IntArrayBoundedValidator() + greaterThanZero.setLower(0) + self.declareProperty(IntArrayProperty("RunNumbers",values=[0], validator=greaterThanZero), doc="Run numbers") + self.declareProperty(WorkspaceProperty("OutputWorkspace", "", direction=Direction.Output)) + self.declareProperty(FileProperty("Directory", "", FileAction.OptionalDirectory)) + + def PyExec(self): + # generic stuff for running + wksp = self.getPropertyValue("OutputWorkspace") + runs = self.getProperty("RunNumbers") + instr = config.getInstrument().shortName() + directory = self.getPropertyValue("Directory").strip() + + # change here if you want something other than gsas files + exts = ['.txt', '.gsa'] + loader = LoadGSS + + # load things and conjoin them + first = True + for run in runs.value: + run = str(run) + if first: + self.__load(directory, instr, run, loader, exts, wksp) + first = False + else: + self.__load(directory, instr, run, loader, exts, run) + ConjoinWorkspaces(InputWorkspace1=wksp, InputWorkspace2=run, CheckOverlapping=False) + if mtd.doesExist(run): + DeleteWorkspace(run) + + self.setProperty("OutputWorkspace", mtd[wksp]) + +AlgorithmFactory.subscribe(ConjoinFiles) + diff --git a/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_command_interface.py b/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_command_interface.py index 1911ed5c3943..38eec69d5a98 100644 --- a/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_command_interface.py +++ b/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_command_interface.py @@ -1,35 +1,35 @@ -#pylint: disable=invalid-name +#pylint: disable=invalid-name,unused-import """ Command set for EQSANS reduction """ -# Import the specific commands that we need +# Import the specific commands that we need - some of these are used in systemtests from reduction_workflow.command_interface import * -#from hfir_command_interface import DarkCurrent, NoDarkCurrent, NoNormalization -from hfir_command_interface import SolidAngle#, NoSolidAngle -#from hfir_command_interface import DirectBeamCenter, ScatteringBeamCenter +from hfir_command_interface import DarkCurrent, NoDarkCurrent, NoNormalization +from hfir_command_interface import SolidAngle, NoSolidAngle +from hfir_command_interface import DirectBeamCenter, ScatteringBeamCenter from hfir_command_interface import SetBeamCenter as BaseSetBeamCenter -#from hfir_command_interface import SensitivityCorrection, SetSensitivityBeamCenter -#from hfir_command_interface import SensitivityDirectBeamCenter, SensitivityScatteringBeamCenter -#from hfir_command_interface import NoSensitivityCorrection, DivideByThickness +from hfir_command_interface import SensitivityCorrection, SetSensitivityBeamCenter +from hfir_command_interface import SensitivityDirectBeamCenter, SensitivityScatteringBeamCenter +from hfir_command_interface import NoSensitivityCorrection, DivideByThickness -#from hfir_command_interface import IQxQy, NoIQxQy, SaveIq, NoSaveIq, SaveIqAscii +from hfir_command_interface import IQxQy, NoIQxQy, SaveIq, NoSaveIq, SaveIqAscii -#from hfir_command_interface import DirectBeamTransmission, TransmissionDarkCurrent -#from hfir_command_interface import ThetaDependentTransmission -#from hfir_command_interface import SetTransmissionBeamCenter, TransmissionDirectBeamCenter -#from hfir_command_interface import SetTransmission, NoTransmission +from hfir_command_interface import DirectBeamTransmission, TransmissionDarkCurrent +from hfir_command_interface import ThetaDependentTransmission +from hfir_command_interface import SetTransmissionBeamCenter, TransmissionDirectBeamCenter +from hfir_command_interface import SetTransmission, NoTransmission -#from hfir_command_interface import Background, NoBackground, NoBckTransmission -#from hfir_command_interface import SetBckTransmission, BckDirectBeamTransmission -#from hfir_command_interface import SetBckTransmissionBeamCenter, BckThetaDependentTransmission -#from hfir_command_interface import BckTransmissionDirectBeamCenter, BckTransmissionDarkCurrent +from hfir_command_interface import Background, NoBackground, NoBckTransmission +from hfir_command_interface import SetBckTransmission, BckDirectBeamTransmission +from hfir_command_interface import SetBckTransmissionBeamCenter, BckThetaDependentTransmission +from hfir_command_interface import BckTransmissionDirectBeamCenter, BckTransmissionDarkCurrent -#from hfir_command_interface import SetSampleDetectorOffset, SetSampleDetectorDistance -#from hfir_command_interface import Mask, MaskRectangle, MaskDetectors, MaskDetectorSide -#from hfir_command_interface import SetAbsoluteScale, SetDirectBeamAbsoluteScale -#from hfir_command_interface import Stitch +from hfir_command_interface import SetSampleDetectorOffset, SetSampleDetectorDistance +from hfir_command_interface import Mask, MaskRectangle, MaskDetectors, MaskDetectorSide +from hfir_command_interface import SetAbsoluteScale, SetDirectBeamAbsoluteScale +from hfir_command_interface import Stitch #from mantid.api import AlgorithmManager #from mantid.kernel import Logger From 37cc588857d6cf83b371b6652888e8a833f5f62c Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 15:21:42 +0000 Subject: [PATCH 345/414] check dynamic_cast, coverity issue 1075737, re #11151, --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 10 ++++++++++ Code/Mantid/MantidPlot/src/PlotDialog.h | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index eae4be1e6635..f31439122313 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -3110,6 +3110,16 @@ CurveTreeItem::CurveTreeItem(QwtPlotItem *curve, LayerItem *parent, const QStrin setIcon(0, getQPixmap("graph_disabled_xpm")); } +Graph* CurveTreeItem::graph() +{ + LayerItem *l = dynamic_cast(parent()); + if (l) { + return l->graph(); + } else { + return NULL; + } +} + void CurveTreeItem::setActive(bool on) { if (on) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.h b/Code/Mantid/MantidPlot/src/PlotDialog.h index cebfeacc1dce..f5e1d9017a55 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.h +++ b/Code/Mantid/MantidPlot/src/PlotDialog.h @@ -298,7 +298,7 @@ class CurveTreeItem : public QTreeWidgetItem enum {PlotCurveTreeItem = 1002}; CurveTreeItem(QwtPlotItem *curve, LayerItem *parent, const QString& s); - Graph* graph(){return dynamic_cast(parent())->graph();}; + Graph* graph(); void setActive(bool on); QwtPlotItem *plotItem() const{ return d_curve; }; From 796addaddaa2554bc85238ecc98c10f6e4018e7e Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 15:29:11 +0000 Subject: [PATCH 346/414] dynamic_cast in insertCurvesList, coverity issue 1075738, re #11151, --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index f31439122313..da89a49ad15f 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -3075,6 +3075,9 @@ void LayerItem::insertCurvesList() { PlotCurve *c = dynamic_cast(it); DataCurve* dc = dynamic_cast(it); + if (!c || !dc) + continue; + if (dc && c->type() != Graph::Function && dc->table()) { QString s = dc->plotAssociation(); From 9896620ac811582173e90f4e6f03ab1057b6d65f Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 15:33:51 +0000 Subject: [PATCH 347/414] dynamic_cast in editCurve, coverity issue 1075739, re #11151, --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index da89a49ad15f..0a2bf10aec09 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -356,7 +356,10 @@ void PlotDialog::editCurve() return; int index = item->plotItemIndex(); - int curveType = dynamic_cast(item->plotItem())->type(); + PlotCurve* pc = dynamic_cast(item->plotItem()); + if (!pc) + return; + int curveType = pc->type(); hide(); From d131525e5cfe2d62300d96d85cf64a13891ca671 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 15:42:53 +0000 Subject: [PATCH 348/414] dynamic_cast, showPlotAssociations, coverity issue 1075740, re #11151 --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index 0a2bf10aec09..62f8aad7ffad 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -324,7 +324,7 @@ void PlotDialog::showPlotAssociations(QTreeWidgetItem *item, int) if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram) { Spectrogram *sp = dynamic_cast(it); - if (sp->matrix()) + if (sp && sp->matrix()) sp->matrix()->showMaximized(); return; } From 6f052137b6c5088a5c18b2cf86319da6fa468dc6 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 15:51:00 +0000 Subject: [PATCH 349/414] dynamic_cast, showPlotAssociations, coverity issue 1075741, re #11151 --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index 62f8aad7ffad..fc5914481238 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -330,7 +330,10 @@ void PlotDialog::showPlotAssociations(QTreeWidgetItem *item, int) } hide(); - if (dynamic_cast(it)->type() == Graph::Function) + PlotCurve *pc = dynamic_cast(it); + if (!pc) + return; + if (pc->type() == Graph::Function) { FunctionDialog *fd = d_app->showFunctionDialog((dynamic_cast(item))->graph(), dynamic_cast(item)->plotItemIndex()); From 17f1f8ca674f8a3e0b0a99997564b62a3e8e234d Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 16:06:48 +0000 Subject: [PATCH 350/414] dynamic_casts, showPlotAssociations, coverity issue 1075742, re #11151 --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index fc5914481238..011de00bf535 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -317,7 +317,10 @@ void PlotDialog::showPlotAssociations(QTreeWidgetItem *item, int) if (item->type() != CurveTreeItem::PlotCurveTreeItem) return; - QwtPlotItem *it = dynamic_cast(dynamic_cast(item)->plotItem()); // crazy + CurveTreeItem *ctit = dynamic_cast(item); + if (!ctit) + return; + QwtPlotItem *it = dynamic_cast(ctit->plotItem()); if (!it) return; @@ -335,15 +338,16 @@ void PlotDialog::showPlotAssociations(QTreeWidgetItem *item, int) return; if (pc->type() == Graph::Function) { - FunctionDialog *fd = d_app->showFunctionDialog((dynamic_cast(item))->graph(), - dynamic_cast(item)->plotItemIndex()); + FunctionDialog *fd = d_app->showFunctionDialog(ctit->graph(), + ctit->plotItemIndex()); + if (fd) connect((QObject *) fd, SIGNAL(destroyed()), this, SLOT(show())); } else { - AssociationsDialog* ad = d_app->showPlotAssociations( - dynamic_cast(item)->plotItemIndex()); + AssociationsDialog* ad = d_app->showPlotAssociations(ctit->plotItemIndex()); + if (ad) connect((QObject *) ad, SIGNAL(destroyed()), this, SLOT(show())); } From 0cbecbf689cee00fbb8fbcd04a82a355689ccb9d Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 16:10:34 +0000 Subject: [PATCH 351/414] dynamic_cast, setEquidistantLevels, coverity issue 1075743, re #11151 --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index 011de00bf535..b5e5d553bbe3 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -283,6 +283,9 @@ void PlotDialog::setEquidistantLevels() return; CurveTreeItem *item = dynamic_cast(it); + if (!item) + return; + QwtPlotItem *plotItem = dynamic_cast(item->plotItem()); if (!plotItem) return; From e1152f9654856154b9d39bbd7cb3f002e0587fbd Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 16:15:00 +0000 Subject: [PATCH 352/414] dynamic_cast, contextMenuEvent, coverity issues 1075744,5, re #11151 --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index b5e5d553bbe3..0b703a4b70a6 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -1499,7 +1499,12 @@ void PlotDialog::contextMenuEvent(QContextMenuEvent *e) return; if (item->type() != CurveTreeItem::PlotCurveTreeItem) return; - QwtPlotItem *it = dynamic_cast(dynamic_cast(item)->plotItem()); + + CurveTreeItem *ctit = dynamic_cast(item); + if (!ctit) + return; + + QwtPlotItem *it = dynamic_cast(ctit->plotItem()); if (!it) return; @@ -1512,7 +1517,10 @@ void PlotDialog::contextMenuEvent(QContextMenuEvent *e) if (it->rtti() == QwtPlotItem::Rtti_PlotCurve) { - if (dynamic_cast(it)->type() == Graph::Function) + PlotCurve *pc = dynamic_cast(it); + if (!pc) + return; + if (pc->type() == Graph::Function) contextMenu.insertItem(tr("&Edit..."), this, SLOT(editCurve())); else contextMenu.insertItem(tr("&Plot Associations..."), this, SLOT(editCurve())); From bb97b77c17bef5337d3f9af4e978c16921d98d75 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 16:19:04 +0000 Subject: [PATCH 353/414] dynamic_cast, chooseLabelsFont, coverity issues 1075746, re #11151 --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index 0b703a4b70a6..b5be507d76a0 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -3023,8 +3023,12 @@ void PlotDialog::chooseLabelsFont() if (!item || item->type() != CurveTreeItem::PlotCurveTreeItem) return; - QwtPlotItem *i = dynamic_cast(item)->plotItem(); - Graph *graph = dynamic_cast(item)->graph(); + CurveTreeItem* ctit = dynamic_cast(item); + if (!ctit) + return; + + QwtPlotItem *i = ctit->plotItem(); + Graph *graph = ctit->graph(); if (!i || !graph) return; From d986d3fa13ca16a4b01c4ab62534f610df426f45 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 16:29:19 +0000 Subject: [PATCH 354/414] dynamic_casts, updateTabWindow, coverity issues 1075747,8, re #11151 --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 24 ++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index b5be507d76a0..df897d8e19f5 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -1569,18 +1569,32 @@ void PlotDialog::updateTabWindow(QTreeWidgetItem *currentItem, QTreeWidgetItem * forceClearTabs = true; } - if (previousItem->type() == CurveTreeItem::PlotCurveTreeItem) - dynamic_cast(previousItem)->setActive(false); - else if (previousItem->type() == LayerItem::LayerTreeItem) - dynamic_cast(previousItem)->setActive(false); + if (previousItem->type() == CurveTreeItem::PlotCurveTreeItem) { + CurveTreeItem *prev = dynamic_cast(previousItem); + if (!prev) + return; + prev->setActive(false); + } else if (previousItem->type() == LayerItem::LayerTreeItem) { + LayerItem *prev = dynamic_cast(previousItem); + if (!prev) + return; + prev->setActive(false); + } boxPlotType->blockSignals(true); if (currentItem->type() == CurveTreeItem::PlotCurveTreeItem) { CurveTreeItem *curveItem = dynamic_cast(currentItem); + if (!curveItem) + return; + + CurveTreeItem *pi = dynamic_cast(previousItem); + if (!pi) + return; + if (previousItem->type() != CurveTreeItem::PlotCurveTreeItem - || dynamic_cast(previousItem)->plotItemType() != curveItem->plotItemType() + || pi->plotItemType() != curveItem->plotItemType() || forceClearTabs) { clearTabWidget(); From 9e71e68b123fab1909a693ed06f90c25109b7fc8 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 16:40:51 +0000 Subject: [PATCH 355/414] dynamic_casts, setActiveCurve, coverity issues 1075749,51,52 re #11151 --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index df897d8e19f5..3c16450692b9 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -1920,6 +1920,8 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item) btnEditCurve->hide(); Spectrogram *sp = dynamic_cast(i); + if (!sp) + return; imageGroupBox->setChecked(sp->testDisplayMode(QwtPlotSpectrogram::ImageMode)); grayScaleBox->setChecked(sp->colorMapPolicy() == Spectrogram::GrayScale); @@ -1977,7 +1979,11 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item) privateTabWidget->showPage(labelsPage); return; } + PlotCurve *c = dynamic_cast(i); + if (!c) + return; + if (c->type() == Graph::Function) btnEditCurve->setText(tr("&Edit...")); else @@ -1987,6 +1993,8 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item) if (curveType == Graph::Pie) { QwtPieCurve *pie = dynamic_cast(i); + if (!pie) + return; boxPiePattern->setPattern(pie->pattern()); boxPieLineWidth->setValue(pie->pen().widthF()); boxPieLineColor->setColor(pie->pen().color()); From ae46dc1ec532248146217e2aeb09e6298eb78f29 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 16:43:13 +0000 Subject: [PATCH 356/414] dynamic_cast, showStatistics(), coverity issue 1075750, re #11151 --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index 3c16450692b9..c46c564398a2 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -1444,7 +1444,11 @@ void PlotDialog::showStatistics() if (it->type() != CurveTreeItem::PlotCurveTreeItem) return; - QwtPlotItem *plotItem = dynamic_cast(dynamic_cast(it)->plotItem()); + CurveTreeItem *ctit = dynamic_cast(it); + if (!ctit) + return; + + QwtPlotItem *plotItem = dynamic_cast(ctit->plotItem()); if (!plotItem) return; From 634b3a80c3e87502c0eb93415bdf29787ce24fc6 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 16:49:30 +0000 Subject: [PATCH 357/414] dynamic_cast, changePlotType(), coverity issue 1075753, re #11151 --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index c46c564398a2..667cf3db2d6d 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -416,6 +416,9 @@ void PlotDialog::changePlotType(int plotType) insertTabs(curveType); VectorCurve *v = dynamic_cast(item->plotItem()); + if (!v) + return; + if (plotType) { graph->setCurveType(item->plotItemIndex(), Graph::VectXYAM); From 040b50a8e92f29ba296e8053ce3eebd17b023fb4 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 16:58:35 +0000 Subject: [PATCH 358/414] dynamic_casts, acceptParams(), coverity issues 1075754, 55, re #11151 --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index 667cf3db2d6d..a9426d066287 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -2348,6 +2348,9 @@ bool PlotDialog::acceptParams() return false; CurveTreeItem *item = dynamic_cast(it); + if (!item) + return false; + QwtPlotItem *plotItem = dynamic_cast(item->plotItem()); if (!plotItem) return false; @@ -2529,6 +2532,9 @@ bool PlotDialog::acceptParams() else if (privateTabWidget->currentPage() == piePage) { QwtPieCurve *pie = dynamic_cast(plotItem); + if (!pie) + return false; + pie->setPen( QPen(boxPieLineColor->color(), boxPieLineWidth->value(), Graph::getPenStyle(boxPieLineStyle->currentIndex()))); @@ -2538,6 +2544,9 @@ bool PlotDialog::acceptParams() else if (privateTabWidget->currentPage() == pieGeometryPage) { QwtPieCurve *pie = dynamic_cast(plotItem); + if (!pie) + return false; + pie->setViewAngle(boxPieViewAngle->value()); pie->setThickness(boxPieThickness->value()); pie->setRadius(boxRadius->value()); @@ -2548,6 +2557,9 @@ bool PlotDialog::acceptParams() else if (privateTabWidget->currentPage() == pieLabelsPage) { QwtPieCurve *pie = dynamic_cast(plotItem); + if (!pie) + return false; + pie->setLabelsAutoFormat(pieAutoLabelsBox->isChecked()); pie->setLabelValuesFormat(boxPieValues->isChecked()); pie->setLabelPercentagesFormat(boxPiePercentages->isChecked()); From cc146a067a6a0f1955a79f36ad5343dbd4a41327 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 17:00:19 +0000 Subject: [PATCH 359/414] dynamic_casts, selectCurve(), coverity issues 1075756, re #11151 --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index a9426d066287..b9fa5f20015a 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -1431,7 +1431,10 @@ void PlotDialog::selectCurve(int index) QTreeWidgetItem *item = layerItem->child(index); if (item) { - (dynamic_cast(item))->setActive(true); + CurveTreeItem *ctit = dynamic_cast(item); + if (!ctit) + return; + ctit->setActive(true); listBox->setCurrentItem(item); } } From 089cd0671a4ac6a84e8bdc2be153a66b35e9eb58 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sat, 21 Feb 2015 17:03:16 +0000 Subject: [PATCH 360/414] dynamic_cast, insertTabs(), coverity issue 1075757, re #11151 --- Code/Mantid/MantidPlot/src/PlotDialog.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index b9fa5f20015a..839fd3f965ba 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -1727,7 +1727,11 @@ void PlotDialog::insertTabs(int plot_type) if (!item || item->type() != CurveTreeItem::PlotCurveTreeItem) return; - const DataCurve *c = dynamic_cast((dynamic_cast(item))->plotItem()); + CurveTreeItem *ctit = dynamic_cast(item); + if (!ctit) + return; + + const DataCurve *c = dynamic_cast(ctit->plotItem()); if (!c) return; if (c && c->type() != Graph::Function) From cd98bb4ed174548024b05b81c8e127927b2c7dfc Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 13:55:59 +0000 Subject: [PATCH 361/414] dynamic_cast, scaleFonts(), coverity issue 1075830, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index c791973a8530..bc019a22c17e 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -3685,9 +3685,13 @@ void Graph::scaleFonts(double factor) QObjectList lst = d_plot->children(); foreach(QObject *o, lst){ if (o->inherits("LegendWidget")){ - QFont font = dynamic_cast(o)->font(); + LegendWidget *lw = dynamic_cast(o); + if (!lw) + continue; + + QFont font = lw->font(); font.setPointSizeFloat(factor*font.pointSizeFloat()); - dynamic_cast(o)->setFont(font); + lw->setFont(font); } } From 98f1112253ccc989e0fa793052d376748337835c Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:18:15 +0000 Subject: [PATCH 362/414] dynamic_cast, insrtCurve(), coverity issue 1075829, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index bc019a22c17e..51af99a4853e 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -2780,7 +2780,9 @@ PlotCurve* Graph::insertCurve(Table* w, const QString& xColName, const QString& c = new QwtBarCurve(QwtBarCurve::Horizontal, w, xColName, yColName, startRow, endRow); } else if (style == Histogram){ c = new QwtHistogram(w, xColName, yColName, startRow, endRow); - dynamic_cast(c)->initData(Y.data(), size); + QwtHistogram *histo = dynamic_cast(c); + if (histo) + histo->initData(Y.data(), size); } else c = new DataCurve(w, xColName, yColName, startRow, endRow); From 777ff68fffb4a91ec9ca174a77dfd3cc76bea1d8 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:23:12 +0000 Subject: [PATCH 363/414] dynamic_casts, marterCurve(), coverity issues 1075827,8, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 51af99a4853e..820d1f5f5361 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -4970,7 +4970,8 @@ DataCurve* Graph::masterCurve(QwtErrorPlotCurve *er) continue; if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram) continue; - if (dynamic_cast(it)->type() == Function) + PlotCurve *pc = dynamic_cast(it); + if (!pc || pc->type() == Function) continue; DataCurve* dc = dynamic_cast(it); @@ -4992,7 +4993,8 @@ DataCurve* Graph::masterCurve(const QString& xColName, const QString& yColName) continue; if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram) continue; - if (dynamic_cast(it)->type() == Function) + PlotCurve *pc = dynamic_cast(it); + if (!pc || pc->type() == Function) continue; DataCurve* dc = dynamic_cast(it); From 1aecabcfa4e696b7e1b0fa2ff5b984bad9211c71 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:28:14 +0000 Subject: [PATCH 364/414] dynamic_cast, removeCurve(), coverity issue 1075826, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 820d1f5f5361..f4d9b8e0208d 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -3093,9 +3093,10 @@ void Graph::removeCurve(int index) if (it->rtti() != QwtPlotItem::Rtti_PlotSpectrogram) { - if (dynamic_cast(it)->type() == ErrorBars) - dynamic_cast(it)->detachFromMasterCurve(); - else if (c->type() != Function && dc){ + if (c->type() == ErrorBars) { + QwtErrorPlotCurve *epc = dynamic_cast(it); + epc->detachFromMasterCurve(); + } else if (c->type() != Function && dc) { dc->clearErrorBars(); dc->clearLabels(); } From 866ad1773bbd3f641db55dd5314cf02fd7d3caf0 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:30:18 +0000 Subject: [PATCH 365/414] dynamic_cast, removeCurves(), coverity issue 1075822, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index f4d9b8e0208d..18559796e955 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -3056,7 +3056,9 @@ void Graph::removeCurves(const QString& s) if (it->rtti() != QwtPlotItem::Rtti_PlotCurve) continue; - if (dynamic_cast(it)->type() == Function) + + PlotCurve *pc = dynamic_cast(it); + if (!pc || pc->type() == Function) continue; DataCurve * dc = dynamic_cast(it); From 93dd0f18a1e8be2bf24c1d490ef66214cabbf90e Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:35:02 +0000 Subject: [PATCH 366/414] dynamic_cast, setGrayScale(), coverity issues 1075819-21, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 18559796e955..b861ccdaf446 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -4843,12 +4843,14 @@ void Graph::setGrayScale() QwtPlotItem * it = plotItem(i); if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram) { - dynamic_cast(it)->setGrayScale(); + Spectrogram *spec = dynamic_cast(it); + if (spec) + spec->setGrayScale(); continue; } PlotCurve *c = dynamic_cast(it); - if (c->type() == ErrorBars) + if (!c || c->type() == ErrorBars) continue; QPen pen = c->pen(); @@ -4886,9 +4888,12 @@ void Graph::setGrayScale() continue; PlotCurve *c = dynamic_cast(it); - if (c->type() == ErrorBars) + if (c && c->type() == ErrorBars) { - QwtErrorPlotCurve *er = dynamic_cast(it); // QtiPlot: ErrorBarsCurve *er = (ErrorBarsCurve *) it; + // QtiPlot: ErrorBarsCurve *er = (ErrorBarsCurve *) it; + QwtErrorPlotCurve *er = dynamic_cast(it); + if (!er) + continue; DataCurve* mc = er->masterCurve(); if (mc) er->setColor(mc->pen().color()); From f24be58d84cce8846a51536f1a6a8d339f58eb0e Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:37:05 +0000 Subject: [PATCH 367/414] dynamic_cast, niceLogScales(), coverity issue 1075818-21, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index b861ccdaf446..a049a6bbe918 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -1074,17 +1074,23 @@ void Graph::niceLogScales(QwtPlot::Axis axis) double start = QMIN(scDiv->lBound(), scDiv->hBound()); double end = QMAX(scDiv->lBound(), scDiv->hBound()); - // log scales can't represent zero or negative values, 1e-10 as a low range is enough to display all data but still be plottable on a log scale + // log scales can't represent zero or negative values, 1e-10 as a + // low range is enough to display all data but still be plottable on + // a log scale start = start < 1e-90 ? 1e-10 : start; - // improve the scale labelling by ensuring that the graph starts and ends on numbers that can have major ticks e.g. 0.1 or 1 or 100 + // improve the scale labelling by ensuring that the graph starts and + // ends on numbers that can have major ticks e.g. 0.1 or 1 or 100 const double exponent = floor(log10(start)); start = pow(10.0, exponent); end = ceil(log10(end)); end = pow(10.0, end); ScaleEngine *scaleEng = dynamic_cast(d_plot->axisScaleEngine(axis)); + if (!scaleEng) + return; - // call the QTiPlot function set scale which takes many arguments, fill the arguments with the same settings the plot already has + // call the QTiPlot function set scale which takes many arguments, + // fill the arguments with the same settings the plot already has setScale(axis, start, end, axisStep(axis), scDiv->ticks(QwtScaleDiv::MajorTick).count(), d_plot->axisMaxMinor(axis), From aeb335a9d4c851d82b9ad16c36aae58831cd3739 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:39:00 +0000 Subject: [PATCH 368/414] dynamic_cast, axisFormatInfo(), coverity issue 1075817, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index a049a6bbe918..deeaa4cdf8fb 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -4754,7 +4754,11 @@ QString Graph::axisFormatInfo(int axis) if (axis < 0 || axis > QwtPlot::axisCnt) return QString(); - return dynamic_cast(d_plot->axisScaleDraw(axis))->formatString(); + ScaleDraw *sd = dynamic_cast(d_plot->axisScaleDraw(axis)); + if (sd) + return sd->formatString(); + else + return "Not available!"; } void Graph::updateCurveNames(const QString& oldName, const QString& newName, bool updateTableName) From b97348c3f9327056ca5c350e6c956f9815bd4307 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:40:39 +0000 Subject: [PATCH 369/414] dynamic_cast, deselectCurves(), coverity issue 1075816, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index deeaa4cdf8fb..42af8dc92ed4 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -1675,11 +1675,13 @@ void Graph::deselectCurves() foreach(QwtPlotItem *i, curves){ PlotCurve *c = dynamic_cast(i); DataCurve *dc = dynamic_cast(i); - if(dc && i->rtti() != QwtPlotItem::Rtti_PlotSpectrogram && - c->type() != Graph::Function && dc->hasSelectedLabels() ){ - dc->setLabelsSelected(false); - return; - } + if(c && dc && + i->rtti() != QwtPlotItem::Rtti_PlotSpectrogram && + c->type() != Graph::Function && dc->hasSelectedLabels() ) + { + dc->setLabelsSelected(false); + return; + } } } From 12a4cfad4259e4280d1afed31e9c9999b2be4597 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:42:56 +0000 Subject: [PATCH 370/414] dynamic_cast, setCurrentFont(), coverity issue 1075815, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 42af8dc92ed4..3a9143e1b541 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -5167,8 +5167,10 @@ void Graph::setCurrentFont(const QFont& f) QList curves = d_plot->curvesList(); foreach(QwtPlotItem *i, curves){ DataCurve* dc = dynamic_cast(i); - if(dc && i->rtti() != QwtPlotItem::Rtti_PlotSpectrogram && - dynamic_cast(i)->type() != Graph::Function){ + PlotCurve* pc = dynamic_cast(i); + if(pc && dc + && i->rtti() != QwtPlotItem::Rtti_PlotSpectrogram && + pc->type() != Graph::Function){ if(dc->hasSelectedLabels()){ dc->setLabelsFont(f); d_plot->replot(); From 745fad99db4a323228c516b97a52aaa823d59f99 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:44:43 +0000 Subject: [PATCH 371/414] dynamic_cast, deselectMarker(), coverity issue 1075814, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 3a9143e1b541..52ca22d25008 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -238,9 +238,12 @@ void Graph::deselectMarker() cp->disableEditing(); QObjectList lst = d_plot->children(); - foreach(QObject *o, lst){ - if (o->inherits("LegendWidget")) - dynamic_cast(o)->setSelected(false); + foreach(QObject *o, lst) { + if (o->inherits("LegendWidget")) { + LegendWidget *lw = dynamic_cast(o); + if (lw) + lw->setSelected(false); + } } } From 53e92d1231a13b8ea80fbdea89f497933336eda6 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:50:21 +0000 Subject: [PATCH 372/414] dynamic_cast, saveCurveLayout(), coverity issues 1075811-13, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 42 ++++++++++++++++------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 52ca22d25008..23d18a06ac1c 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -2006,30 +2006,36 @@ QString Graph::saveCurveLayout(int index) if(style == VerticalBars || style == HorizontalBars || style == Histogram){ QwtBarCurve *b = dynamic_cast(c); - s+=QString::number(b->gap())+"\t"; - s+=QString::number(b->offset())+"\t"; + if (b) { + s+=QString::number(b->gap())+"\t"; + s+=QString::number(b->offset())+"\t"; + } } if (style == Histogram){ QwtHistogram *h = dynamic_cast(c); - s+=QString::number(h->autoBinning())+"\t"; - s+=QString::number(h->binSize())+"\t"; - s+=QString::number(h->begin())+"\t"; - s+=QString::number(h->end())+"\t"; + if (h) { + s+=QString::number(h->autoBinning())+"\t"; + s+=QString::number(h->binSize())+"\t"; + s+=QString::number(h->begin())+"\t"; + s+=QString::number(h->end())+"\t"; + } } else if(style == VectXYXY || style == VectXYAM){ VectorCurve *v = dynamic_cast(c); - s+=v->color().name()+"\t"; - s+=QString::number(v->width())+"\t"; - s+=QString::number(v->headLength())+"\t"; - s+=QString::number(v->headAngle())+"\t"; - s+=QString::number(v->filledArrowHead())+"\t"; - - QStringList colsList = v->plotAssociation().split(",", QString::SkipEmptyParts); - s+=colsList[2].remove("(X)").remove("(A)")+"\t"; - s+=colsList[3].remove("(Y)").remove("(M)"); - if (style == VectXYAM) - s+="\t"+QString::number(v->position()); - s+="\t"; + if (v) { + s+=v->color().name()+"\t"; + s+=QString::number(v->width())+"\t"; + s+=QString::number(v->headLength())+"\t"; + s+=QString::number(v->headAngle())+"\t"; + s+=QString::number(v->filledArrowHead())+"\t"; + + QStringList colsList = v->plotAssociation().split(",", QString::SkipEmptyParts); + s+=colsList[2].remove("(X)").remove("(A)")+"\t"; + s+=colsList[3].remove("(Y)").remove("(M)"); + if (style == VectXYAM) + s+="\t"+QString::number(v->position()); + s+="\t"; + } } else if(style == Box){ BoxCurve *b = static_cast(c); s+=QString::number(SymbolBox::symbolIndex(b->maxStyle()))+"\t"; From ab44e13ceef14f1984292f058c3401154945b819 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:51:29 +0000 Subject: [PATCH 373/414] dynamic_cast, setIndexedColors(), coverity issue 1075810, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 23d18a06ac1c..1bfd793c4f9e 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -4944,7 +4944,7 @@ void Graph::setIndexedColors() continue; PlotCurve *c = dynamic_cast(it); - if (c->type() == ErrorBars) + if (!c || c->type() == ErrorBars) continue; QPen pen = c->pen(); From e95ab9ec262cb026fe3f88871748c04a507c30ea Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:53:29 +0000 Subject: [PATCH 374/414] dynamic_cast, setMajorTicksType(), coverity issue 1075809, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 1bfd793c4f9e..a6a406c50143 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -448,14 +448,17 @@ void Graph::setMajorTicksType(const QList& lst) for (int i=0;i<(int)lst.count();i++) { ScaleDraw *sd = dynamic_cast(d_plot->axisScaleDraw (i)); + if (!sd) + continue; + if (lst[i]==ScaleDraw::None || lst[i]==ScaleDraw::In) sd->enableComponent (QwtAbstractScaleDraw::Ticks, false); else { - sd->enableComponent (QwtAbstractScaleDraw::Ticks); - sd->setTickLength (QwtScaleDiv::MinorTick, d_plot->minorTickLength()); - sd->setTickLength (QwtScaleDiv::MediumTick, d_plot->minorTickLength()); - sd->setTickLength (QwtScaleDiv::MajorTick, d_plot->majorTickLength()); + sd->enableComponent(QwtAbstractScaleDraw::Ticks); + sd->setTickLength(QwtScaleDiv::MinorTick, d_plot->minorTickLength()); + sd->setTickLength(QwtScaleDiv::MediumTick, d_plot->minorTickLength()); + sd->setTickLength(QwtScaleDiv::MajorTick, d_plot->majorTickLength()); } sd->setMajorTicksStyle((ScaleDraw::TicksStyle)lst[i]); } From 9c1a9b52413f6869151dc10dd6dcb638b6d638e2 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:54:39 +0000 Subject: [PATCH 375/414] dynamic_cast, setIndexedColors(), coverity issue 1075808, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index a6a406c50143..48d7d877cc04 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -4981,7 +4981,11 @@ void Graph::setIndexedColors() PlotCurve *c = dynamic_cast(it); if (c->type() == ErrorBars) { - QwtErrorPlotCurve *er = dynamic_cast(it); // QtiPlot: ErrorBarsCurve *er = (ErrorBarsCurve *) it; + // QtiPlot: ErrorBarsCurve *er = (ErrorBarsCurve *) it; + QwtErrorPlotCurve *er = dynamic_cast(it); + if (!er) + continue; + DataCurve* mc = er->masterCurve(); if (mc) er->setColor(mc->pen().color()); From 65800d25f5f8b57cc9601957efb150513702180a Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 14:55:51 +0000 Subject: [PATCH 376/414] dynamic_cast, updateImageMarker(), coverity issue 1075807, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 48d7d877cc04..d2a7f7d37433 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -1766,6 +1766,9 @@ void Graph::removeLegend() void Graph::updateImageMarker(int x, int y, int w, int h) { ImageMarker* mrk = dynamic_cast(d_plot->marker(selectedMarker)); + if (!mrk) + return; + mrk->setRect(x, y, w, h); d_plot->replot(); emit modifiedGraph(); From 1116453c04b3ecf980e5929f993ad530345ff93d Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 15:07:18 +0000 Subject: [PATCH 377/414] dynamic_cast, setSelectedMarker(), coverity issue 1075806, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 44 ++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index d2a7f7d37433..62c1cb289f88 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -305,19 +305,33 @@ void Graph::setSelectedMarker(int _mrk, bool add) selectedMarker = mrk; if (add) { if (d_markers_selector) { - if (d_lines.contains(mrk)) - d_markers_selector->add(dynamic_cast(d_plot->marker(mrk))); - else if (d_images.contains(mrk)) - d_markers_selector->add(dynamic_cast(d_plot->marker(mrk))); - else + if (d_lines.contains(mrk)) { + ArrowMarker *am = dynamic_cast(d_plot->marker(mrk)); + if (!am) + return; + d_markers_selector->add(am); + } else if (d_images.contains(mrk)) { + ImageMarker *im = dynamic_cast(d_plot->marker(mrk)); + if (!im) + return; + d_markers_selector->add(im); + } else { return; + } } else { - if (d_lines.contains(mrk)) - d_markers_selector = new SelectionMoveResizer(dynamic_cast(d_plot->marker(mrk))); - else if (d_images.contains(mrk)) - d_markers_selector = new SelectionMoveResizer(dynamic_cast(d_plot->marker(mrk))); - else + if (d_lines.contains(mrk)) { + ArrowMarker *am = dynamic_cast(d_plot->marker(mrk)); + if (!am) + return; + d_markers_selector = new SelectionMoveResizer(am); + } else if (d_images.contains(mrk)) { + ImageMarker *im = dynamic_cast(d_plot->marker(mrk)); + if (!im) + return; + d_markers_selector = new SelectionMoveResizer(im); + } else { return; + } connect(d_markers_selector, SIGNAL(targetsChanged()), this, SIGNAL(modifiedGraph())); } @@ -328,14 +342,20 @@ void Graph::setSelectedMarker(int _mrk, bool add) return; delete d_markers_selector; } - d_markers_selector = new SelectionMoveResizer(dynamic_cast(d_plot->marker(mrk))); + ArrowMarker *am = dynamic_cast(d_plot->marker(mrk)); + if (!am) + return; + d_markers_selector = new SelectionMoveResizer(am); } else if (d_images.contains(mrk)) { if (d_markers_selector) { if (d_markers_selector->contains(dynamic_cast(d_plot->marker(mrk)))) return; delete d_markers_selector; } - d_markers_selector = new SelectionMoveResizer(dynamic_cast(d_plot->marker(mrk))); + ImageMarker *im = dynamic_cast(d_plot->marker(mrk)); + if (!im) + return; + d_markers_selector = new SelectionMoveResizer(im); } else return; From 9bdd2525ebde83aacc4c5b16304756c09e04e57d Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 15:10:19 +0000 Subject: [PATCH 378/414] dynamic_cast, savePieCurveLayout(), coverity issue 1075805, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 62c1cb289f88..41b3907df888 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -1969,6 +1969,9 @@ QString Graph::savePieCurveLayout() QString s="PieCurve\t"; QwtPieCurve *pie = dynamic_cast(curve(0)); + if (!pie) + return s; + s+= pie->title().text()+"\t"; QPen pen = pie->pen(); s+=QString::number(pen.widthF())+"\t"; From 27a4b6e9010108c9085c7a82b5fa648bd284690f Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 15:16:34 +0000 Subject: [PATCH 379/414] dynamic_cast, updateSecondaryAxis(), issues 1075799,800,803, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 41b3907df888..1b521b7d0f1f 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -954,7 +954,7 @@ void Graph::updateSecondaryAxis(int axis) if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram){ Spectrogram *sp = dynamic_cast(it); - if (sp->colorScaleAxis() == axis) + if (!sp || sp->colorScaleAxis() == axis) return; } @@ -971,7 +971,10 @@ void Graph::updateSecondaryAxis(int axis) return; ScaleEngine *sc_engine = dynamic_cast(d_plot->axisScaleEngine(axis)); - sc_engine->clone(dynamic_cast(d_plot->axisScaleEngine(a))); + if (sc_engine) { + ScaleEngine *a_engine = dynamic_cast(d_plot->axisScaleEngine(a)); + sc_engine->clone(a_engine); + } /*QwtScaleEngine *qwtsc_engine = d_plot->axisScaleEngine(axis); ScaleEngine *sc_engine=dynamic_cast(qwtsc_engine); From 0d626530ef5d40b1724c828295b6de93b16a3437 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 15:18:05 +0000 Subject: [PATCH 380/414] dynamic_cast, selectedCurveLabels(), issue 1075802, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 1b521b7d0f1f..db422879eefd 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -1720,8 +1720,9 @@ DataCurve* Graph::selectedCurveLabels() foreach(QwtPlotItem *i, curves){ PlotCurve *c = dynamic_cast(i); DataCurve *dc = dynamic_cast(i); - if(dc && i->rtti() != QwtPlotItem::Rtti_PlotSpectrogram && - c->type() != Graph::Function && dc->hasSelectedLabels()) + if(dc && c && + i->rtti() != QwtPlotItem::Rtti_PlotSpectrogram && + c->type() != Graph::Function && dc->hasSelectedLabels()) return dc; } return NULL; From 02c0f8360172b5a9c8bd0709d3fab9e8c9853238 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 15:20:06 +0000 Subject: [PATCH 381/414] dynamic_cast, setAxisTicksLength(), coverity issue 1075801, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index db422879eefd..1cec44586d17 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -525,6 +525,9 @@ void Graph::setAxisTicksLength(int axis, int majTicksType, int minTicksType, d_plot->setTickLength(minLength, majLength); ScaleDraw *sd = dynamic_cast(d_plot->axisScaleDraw(axis)); + if (!sd) + return; + sd->setMajorTicksStyle((ScaleDraw::TicksStyle)majTicksType); sd->setMinorTicksStyle((ScaleDraw::TicksStyle)minTicksType); From 3d721aca502cc725cc193fda321be6ff3c6af9a3 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 15:21:58 +0000 Subject: [PATCH 382/414] dynamic_cast, guessUniqueCurveLayout(), cvrty issue 1075797, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 1cec44586d17..c9e3163bb3b6 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -4496,6 +4496,9 @@ void Graph::guessUniqueCurveLayout(int& colorIndex, int& symbolIndex) if (curve_index >= 0 && c_type[curve_index] == ErrorBars) {// find out the pen color of the master curve QwtErrorPlotCurve *er = dynamic_cast(d_plot->curve(c_keys[curve_index])); + if (!er) + return; + DataCurve *master_curve = er->masterCurve(); if (master_curve){ colorIndex = ColorBox::colorIndex(master_curve->pen().color()); From 6d8efcb41d97a9cef79c516847259019a1a2b2b5 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 18:21:24 +0000 Subject: [PATCH 383/414] dynamic_casts, copy(), coverity issues 1075790-96,98, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 132 +++++++++++++++++++-------- 1 file changed, 96 insertions(+), 36 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index c9e3163bb3b6..9861bb09f1a1 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -4095,9 +4095,14 @@ void Graph::copy(Graph* g) QwtPlotItem *it = (QwtPlotItem *)g->plotItem(i); if (it->rtti() == QwtPlotItem::Rtti_PlotCurve){ DataCurve *cv = dynamic_cast(it); - if (!cv) continue; + if (!cv) + continue; + + PlotCurve *pc = dynamic_cast(it); + if (!pc) + continue; + int n = cv->dataSize(); - int style = dynamic_cast(it)->type(); QVector x(n); QVector y(n); for (int j=0; jy(j); } + int style = pc->type(); + PlotCurve *c = 0; c_keys.resize(++n_curves); c_type.resize(n_curves); @@ -4116,43 +4123,73 @@ void Graph::copy(Graph* g) } else if (style == Function) { c = new FunctionCurve(cv->title().text()); c_keys[i] = d_plot->insertCurve(c); - dynamic_cast(c)->copy(dynamic_cast(cv)); + FunctionCurve *fc = dynamic_cast(c); + if (fc) { + FunctionCurve *fcCV = dynamic_cast(cv); + if (fcCV) + fc->copy(fcCV); + } } else if (style == VerticalBars || style == HorizontalBars) { - c = new QwtBarCurve(dynamic_cast(cv)->orientation(), cv->table(), cv->xColumnName(), - cv->title().text(), cv->startRow(), cv->endRow()); - c_keys[i] = d_plot->insertCurve(c); - (dynamic_cast(c))->copy(dynamic_cast(cv)); + QwtBarCurve *bc = dynamic_cast(c); + if (bc) { + c = new QwtBarCurve(bc->orientation(), cv->table(), cv->xColumnName(), + cv->title().text(), cv->startRow(), cv->endRow()); + c_keys[i] = d_plot->insertCurve(c); + + const QwtBarCurve *cvBC = dynamic_cast(cv); + if (cvBC) + bc->copy(cvBC); + } } else if (style == ErrorBars) { QwtErrorPlotCurve *er = dynamic_cast(cv); - DataCurve *master_curve = masterCurve(er); - if (master_curve) { - c = new QwtErrorPlotCurve(cv->table(), cv->title().text()); - c_keys[i] = d_plot->insertCurve(c); - dynamic_cast(c)->copy(er); - dynamic_cast(c)->setMasterCurve(master_curve); + if (er) { + DataCurve *master_curve = masterCurve(er); + if (master_curve) { + c = new QwtErrorPlotCurve(cv->table(), cv->title().text()); + c_keys[i] = d_plot->insertCurve(c); + QwtErrorPlotCurve *epc = dynamic_cast(c); + if (epc) { + epc->copy(er); + epc->setMasterCurve(master_curve); + } + } } } else if (style == Histogram) { QwtHistogram *h = dynamic_cast(cv); - if (h->matrix()) + if (h && h->matrix()) c = new QwtHistogram(h->matrix()); else c = new QwtHistogram(cv->table(), cv->xColumnName(), cv->title().text(), cv->startRow(), cv->endRow()); c_keys[i] = d_plot->insertCurve(c); - dynamic_cast(c)->copy(h); + + QwtHistogram *cQH = dynamic_cast(c); + if (cQH) + cQH->copy(h); } else if (style == VectXYXY || style == VectXYAM) { VectorCurve::VectorStyle vs = VectorCurve::XYXY; if (style == VectXYAM) vs = VectorCurve::XYAM; - c = new VectorCurve(vs, cv->table(), cv->xColumnName(), cv->title().text(), - dynamic_cast(cv)->vectorEndXAColName(), - dynamic_cast(cv)->vectorEndYMColName(), - cv->startRow(), cv->endRow()); - c_keys[i] = d_plot->insertCurve(c); - dynamic_cast(c)->copy(dynamic_cast(cv)); + VectorCurve *cvVC = dynamic_cast(cv); + if (cvVC) { + c = new VectorCurve(vs, cv->table(), cv->xColumnName(), cv->title().text(), + cvVC->vectorEndXAColName(), + cvVC->vectorEndYMColName(), + cv->startRow(), cv->endRow()); + c_keys[i] = d_plot->insertCurve(c); + + VectorCurve *cVC = dynamic_cast(c); + if (cVC) // it really should be, just did 'c = new VectorCurve(...' + cVC->copy(cvVC); + } } else if (style == Box) { c = new BoxCurve(cv->table(), cv->title().text(), cv->startRow(), cv->endRow()); c_keys[i] = d_plot->insertCurve(c); - dynamic_cast(c)->copy(dynamic_cast(cv)); + BoxCurve *bc = dynamic_cast(c); + if (bc) { + const BoxCurve *cvBC = dynamic_cast(cv); + if (cvBC) + bc->copy(cvBC); + } QwtSingleArrayData dat(x[0], y, n); c->setData(dat); } else { @@ -4162,12 +4199,23 @@ void Graph::copy(Graph* g) if (c_type[i] != Box && c_type[i] != ErrorBars){ c->setData(x.data(), y.data(), n); - if (c->type() != Function && c->type() != Pie) - dynamic_cast(c)->clone(cv); - else if (c->type() == Pie) - dynamic_cast(c)->clone(dynamic_cast(cv)); + if (c->type() != Function && c->type() != Pie) { + DataCurve *dc = dynamic_cast(c); + if (dc) + dc->clone(cv); + } else if (c->type() == Pie) { + QwtPieCurve *cPie = dynamic_cast(c); + if (cPie) { + QwtPieCurve *cvPie = dynamic_cast(cv); + if (cvPie) + cPie->clone(cvPie); + } + } } + if (!c) + continue; + c->setPen(cv->pen()); c->setBrush(cv->brush()); c->setStyle(cv->style()); @@ -4184,8 +4232,11 @@ void Graph::copy(Graph* g) QListlst = g->fitCurvesList(); if (lst.contains(dynamic_cast(it))) d_fit_curves << c; - }else if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram){ - Spectrogram *sp = (dynamic_cast(it))->copy(); + } else if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram){ + Spectrogram *spc = (dynamic_cast(it)); + if (!spc) + continue; + Spectrogram *sp = spc->copy(); c_keys.resize(++n_curves); c_keys[i] = d_plot->insertCurve(sp); @@ -4219,7 +4270,7 @@ void Graph::copy(Graph* g) continue; ScaleDraw *sdg = dynamic_cast(g->plotWidget()->axisScaleDraw (i)); - if (sdg->hasComponent(QwtAbstractScaleDraw::Labels)) + if (sdg && sdg->hasComponent(QwtAbstractScaleDraw::Labels)) { ScaleDraw::ScaleType type = sdg->scaleType(); if (type == ScaleDraw::Numeric) @@ -4230,9 +4281,10 @@ void Graph::copy(Graph* g) setLabelsMonthFormat(i, sdg->nameFormat()); else if (type == ScaleDraw::Time || type == ScaleDraw::Date) setLabelsDateTimeFormat(i, type, sdg->formatString()); - else{ + else { ScaleDraw *sd = dynamic_cast(plot->axisScaleDraw(i)); - d_plot->setAxisScaleDraw(i, new ScaleDraw(d_plot, sd->labelsList(), sd->formatString(), sd->scaleType())); + if (sd) + d_plot->setAxisScaleDraw(i, new ScaleDraw(d_plot, sd->labelsList(), sd->formatString(), sd->scaleType())); } } else { ScaleDraw *sd = dynamic_cast(d_plot->axisScaleDraw (i)); @@ -4244,9 +4296,6 @@ void Graph::copy(Graph* g) if (!se) continue; - ScaleEngine *sc_engine = dynamic_cast(d_plot->axisScaleEngine(i)); - sc_engine->clone(se); - int majorTicks = plot->axisMaxMajor(i); int minorTicks = plot->axisMaxMinor(i); d_plot->setAxisMaxMajor (i, majorTicks); @@ -4254,6 +4303,12 @@ void Graph::copy(Graph* g) double step = g->axisStep(i); d_user_step[i] = step; + + ScaleEngine *sc_engine = dynamic_cast(d_plot->axisScaleEngine(i)); + if (!sc_engine) + continue; + + sc_engine->clone(se); const QwtScaleDiv *sd = plot->axisScaleDiv(i); QwtScaleDiv div = sc_engine->divideScale (QMIN(sd->lBound(), sd->hBound()), QMAX(sd->lBound(), sd->hBound()), majorTicks, minorTicks, step); @@ -6003,8 +6058,13 @@ void Graph::loadFromProject(const std::string& lines, ApplicationWindow* app, co if(plotType == Graph::Histogram) { QwtHistogram* h = dynamic_cast(curve(curveID)); - h->setBinning(curveValues[17].toInt(),curveValues[18].toDouble(),curveValues[19].toDouble(),curveValues[20].toDouble()); - h->loadData(); + if (h) { + h->setBinning(curveValues[17].toInt(), + curveValues[18].toDouble(), + curveValues[19].toDouble(), + curveValues[20].toDouble()); + h->loadData(); + } } if(plotType == Graph::VerticalBars From a8d647b7c95d07856d62ce9520b664c1fcfb7694 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 18:23:22 +0000 Subject: [PATCH 384/414] dynamic_casts, axistype(), coverity issue 1075789, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 9861bb09f1a1..46094d4c76ab 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -427,7 +427,11 @@ ScaleDraw::ScaleType Graph::axisType(int axis) if (!d_plot->axisEnabled(axis)) return ScaleDraw::Numeric; - return dynamic_cast(d_plot->axisScaleDraw(axis))->scaleType(); + ScaleDraw *sd = dynamic_cast(d_plot->axisScaleDraw(axis)); + if (sd) + return sd->scaleType(); + else // assuming this is a good default + return ScaleDraw::Numeric; } void Graph::setLabelsNumericFormat(int axis, int format, int prec, const QString& formula) From f769b73b457e62e4f41a9014997ef0401e11cf7a Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 18:26:57 +0000 Subject: [PATCH 385/414] dynamic_casts, setScale(), coverity issue 1075786,88, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 46094d4c76ab..0e75b937e975 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -1182,6 +1182,9 @@ void Graph::setScale(QwtPlot::Axis axis, QwtScaleTransformation::Type scaleType) { //check if the scale is already of the desired type, ScaleEngine *sc_engine = dynamic_cast(d_plot->axisScaleEngine(axis)); + if (!sc_engine) + return; + QwtScaleTransformation::Type type = sc_engine->type(); if ( scaleType == QwtScaleTransformation::Log10 ) { @@ -1200,8 +1203,11 @@ void Graph::setScale(QwtPlot::Axis axis, QwtScaleTransformation::Type scaleType) double end = QMAX(scDiv->lBound(), scDiv->hBound()); ScaleEngine *scaleEng = dynamic_cast(d_plot->axisScaleEngine(axis)); + if (!scaleEng) + return; - // call the QTiPlot function set scale which takes many arguments, fill the arguments with the same settings the plot already has + // call the QTiPlot function set scale which takes many arguments, + // fill the arguments with the same settings the plot already has setScale(axis, start, end, axisStep(axis), scDiv->ticks(QwtScaleDiv::MajorTick).count(), d_plot->axisMaxMinor(axis), scaleType, From 0ff0f9e71d77a668678e5e2bc5000b6a1d6930cc Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 18:29:32 +0000 Subject: [PATCH 386/414] dynamic_casts, showAxis(), coverity issue 1075785, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index 0e75b937e975..e68d8ee04902 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -591,11 +591,16 @@ void Graph::showAxis(int axis, int type, const QString& formatInfo, Table *table if (!axisOn) return; - QList majTicksTypeList = d_plot->getMajorTicksType(); - QList minTicksTypeList = d_plot->getMinorTicksType(); - QwtScaleWidget *scale = dynamic_cast(d_plot->axisWidget(axis)); + if (!scale) + return; + ScaleDraw *sd = dynamic_cast(d_plot->axisScaleDraw(axis)); + if (!sd) + return; + + QList majTicksTypeList = d_plot->getMajorTicksType(); + QList minTicksTypeList = d_plot->getMinorTicksType(); if (d_plot->axisEnabled (axis) == axisOn && majTicksTypeList[axis] == majTicksType && From 653dd8467ae8bf33fa3aead582d03a789258acfc Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Sun, 22 Feb 2015 18:32:31 +0000 Subject: [PATCH 387/414] dynamic_cast, removePie(), coverity issue 1075783, re #11152 --- Code/Mantid/MantidPlot/src/Graph.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index e68d8ee04902..a3fcaf85c6d6 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -3094,9 +3094,13 @@ void Graph::removePie() if (d_legend) d_legend->setText(QString::null); - QList labels = dynamic_cast(curve(0))->labelsList(); + QwtPieCurve *pieCurve = dynamic_cast(curve(0)); + if (!pieCurve) + return; + + QList labels = pieCurve->labelsList(); foreach(PieLabel *l, labels) - l->setPieCurve(0); + l->setPieCurve(0); d_plot->removeCurve(c_keys[0]); d_plot->replot(); From b0d18e480a8e1eab72c0c814fa01b02b083e4b57 Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Mon, 23 Feb 2015 08:53:38 +0000 Subject: [PATCH 388/414] remove doxy tags for parameters that were removed, re #11156 --- Code/Mantid/Framework/Kernel/src/InternetHelper.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp index 0642b39d799a..f881b729f0f9 100644 --- a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp +++ b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp @@ -178,10 +178,6 @@ int InternetHelper::processRelocation(const HTTPResponse &response, /** Performs a request using http or https depending on the url * @param url the address to the network resource * @param responseStream The stream to fill with the reply on success -* @param headers A optional key value pair map of any additional headers to -* include in the request. -* @param method Generally GET (default) or POST. -* @param body The request body to send. **/ int InternetHelper::sendRequest(const std::string &url, std::ostream &responseStream) { @@ -384,9 +380,6 @@ The answer, will be inserted at the local_file_path. @param localFilePath : Provide the destination of the file downloaded at the url_file. -@param headers [optional] : A key value pair map of any additional headers to -include in the request. - @exception Mantid::Kernel::Exception::InternetError : For any unexpected behaviour. */ From 6e7515fc79e78207df91effd76493751ca3ea5de Mon Sep 17 00:00:00 2001 From: Federico Montesino Pouzols Date: Mon, 23 Feb 2015 09:45:26 +0000 Subject: [PATCH 389/414] fix boost::shared_ptr constructors, re #11061 --- Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp b/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp index dcff64737513..341c06fa43df 100644 --- a/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp +++ b/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp @@ -45,12 +45,12 @@ Logger g_log("NexusFileIO"); } /// Empty default constructor -NexusFileIO::NexusFileIO() : fileID(), m_filehandle(NULL), +NexusFileIO::NexusFileIO() : fileID(), m_filehandle(), m_nexuscompression(NX_COMP_LZW), m_progress(0), m_filename() { } /// Constructor that supplies a progress object -NexusFileIO::NexusFileIO(Progress *prog) : fileID(), m_filehandle(NULL), +NexusFileIO::NexusFileIO(Progress *prog) : fileID(), m_filehandle(), m_nexuscompression(NX_COMP_LZW), m_progress(prog), m_filename() { } From 07023dbbeb3554eda986fc5131059611877e84a2 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Mon, 23 Feb 2015 10:21:18 +0000 Subject: [PATCH 390/414] Re #7083 Change property order in init method --- .../src/PlotAsymmetryByLogValue.cpp | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp index 53b0ea679405..f8b4ed0d3f3b 100644 --- a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp +++ b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp @@ -93,16 +93,6 @@ void PlotAsymmetryByLogValue::init() { boost::make_shared>(), "The name of the log values which will be used as the x-axis " "in the output workspace."); - declareProperty("Red", 1, "The period number for the 'red' data."); - declareProperty("Green", EMPTY_INT(), - "The period number for the 'green' data."); - - std::vector options; - options.push_back("Integral"); - options.push_back("Differential"); - declareProperty("Type", "Integral", - boost::make_shared(options), - "The calculation type: 'Integral' or 'Differential'."); std::vector optionsLog; optionsLog.push_back("Mean"); @@ -112,8 +102,18 @@ void PlotAsymmetryByLogValue::init() { optionsLog.push_back("Last"); declareProperty("Function", "Last", boost::make_shared(optionsLog), - "The calculation type: 'Integral' or 'Differential'."); + "The function to apply: 'Mean', 'Min', 'Max', 'First' or 'Last'."); + declareProperty("Red", 1, "The period number for the 'red' data."); + declareProperty("Green", EMPTY_INT(), + "The period number for the 'green' data."); + + std::vector options; + options.push_back("Integral"); + options.push_back("Differential"); + declareProperty("Type", "Integral", + boost::make_shared(options), + "The calculation type: 'Integral' or 'Differential'."); declareProperty( "TimeMin", EMPTY_DBL(), "The beginning of the time interval used in the calculations."); From bf371e4708f3434cc512a8c8e183187350d06e37 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Mon, 23 Feb 2015 10:38:13 +0000 Subject: [PATCH 391/414] Re #7083 Adding user example --- .../algorithms/PlotAsymmetryByLogValue-v1.rst | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Code/Mantid/docs/source/algorithms/PlotAsymmetryByLogValue-v1.rst b/Code/Mantid/docs/source/algorithms/PlotAsymmetryByLogValue-v1.rst index 0b65fd8ae3dd..f091f41e8c53 100644 --- a/Code/Mantid/docs/source/algorithms/PlotAsymmetryByLogValue-v1.rst +++ b/Code/Mantid/docs/source/algorithms/PlotAsymmetryByLogValue-v1.rst @@ -141,4 +141,22 @@ Output: Y values (asymmetry): [ 0.14542059 0.13674275 0.12017568] X values (sample magn. field): [ 1350. 1360. 1370.] +**Example - Calculating asymmetry as a function of the sample mean temperature:** + +.. testcode:: ExLogValueFunction + + ws = PlotAsymmetryByLogValue(FirstRun="MUSR00015189", + LastRun="MUSR00015191", + LogValue="sample_temp", + Function="Mean") + print "Y values (asymmetry):", ws.readY(0) + print "X values (sample magn. field):", ws.readX(0) + +Output: + +.. testoutput:: ExLogValueFunction + + Y values (asymmetry): [ 0.15004357 0.14289412 0.12837688] + X values (sample magn. field): [ 290. 290. 290.] + .. categories:: From 868cc77edc043633e3c3a489e3da6628cb31e0d6 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 23 Feb 2015 10:38:42 +0000 Subject: [PATCH 392/414] Start adding members for Python algorithms Refs #11145 --- .../plugins/algorithms/BASISReduction.py | 23 ++++++++++++++++ .../plugins/algorithms/BASISReduction311.py | 23 ++++++++++++++++ .../algorithms/CalculateSampleTransmission.py | 10 +++++-- .../CalibrateRectangularDetectors.py | 27 +++++++++++++++++++ .../plugins/algorithms/ConjoinFiles.py | 7 ++--- .../plugins/algorithms/ConjoinSpectra.py | 10 ++++--- .../algorithms/ConvertSnsRoiFileToMask.py | 6 +++++ .../plugins/algorithms/CorrectLogTimes.py | 2 ++ .../plugins/algorithms/DSFinterp.py | 2 ++ .../algorithms/ExaminePowderDiffProfile.py | 20 ++++++++++++++ 10 files changed, 122 insertions(+), 8 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py index ee9de2e8d78c..05af66bb925e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py @@ -11,6 +11,29 @@ DEFAULT_MASK_FILE = "BASIS_Mask.xml" class BASISReduction(PythonAlgorithm): + + _short_inst = None + _long_inst = None + _extension = None + _doIndiv = None + _etBins = None + _qBins = None + _noMonNorm = None + _maskFile = None + _groupDetOpt = None + _overrideMask = None + _dMask = None + _doNorm = None + _normRange = None + _norm_run_list = None + _normWs = None + _normMonWs = None + _run_list = None + _samWs = None + _samMonWs = None + _samWsRun = None + _samSqwWs = None + def category(self): return "Inelastic;PythonAlgorithms" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py index f0768df7473f..0a5b4200515d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py @@ -14,6 +14,29 @@ DEFAULT_ENERGY = 7.6368 class BASISReduction311(PythonAlgorithm): + + _short_inst = None + _long_inst = None + _extension = None + _doIndiv = None + _etBins = None + _qBins = None + _noMonNorm = None + _maskFile = None + _groupDetOpt = None + _overrideMask = None + _dMask = None + _doNorm = None + _normRange = None + _norm_run_list = None + _normWs = None + _normMonWs = None + _run_list = None + _samWs = None + _samMonWs = None + _samWsRun = None + _samSqwWs = None + def category(self): return "Inelastic;PythonAlgorithms" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py index 1f61e62c29aa..78979a25c8a7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py @@ -8,6 +8,12 @@ class CalculateSampleTransmission(PythonAlgorithm): + _bin_params = None + _chemical_formula = None + _density = None + _thickness = None + _output_ws = None + def category(self): return 'Sample' @@ -58,7 +64,7 @@ def PyExec(self): CreateWorkspace(OutputWorkspace=self._output_ws, NSpec=2, DataX=[0, 0], DataY=[0, 0]) Rebin(InputWorkspace=self._output_ws, OutputWorkspace=self._output_ws, Params=self._bin_params) - SetSampleMaterial(InputWorkspace=self._output_ws, ChemicalFormula=self._chamical_formula) + SetSampleMaterial(InputWorkspace=self._output_ws, ChemicalFormula=self._chemical_formula) ConvertToPointData(InputWorkspace=self._output_ws, OutputWorkspace=self._output_ws) workspace = mtd[self._output_ws] @@ -84,7 +90,7 @@ def _setup(self): """ self._bin_params = self.getPropertyValue('WavelengthRange') - self._chamical_formula = self.getPropertyValue('ChemicalFormula') + self._chemical_formula = self.getPropertyValue('ChemicalFormula') self._density = self.getProperty('NumberDensity').value self._thickness = self.getProperty('Thickness').value self._output_ws = self.getPropertyValue('OutputWorkspace') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py index e6afd8c5d44f..fa2074ea6d4a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py @@ -11,6 +11,33 @@ class CalibrateRectangularDetectors(PythonAlgorithm): + _instrument = None + _filterBadPulses = None + _xpixelbin = None + _ypixelbin = None + _grouping = None + _smoothoffsets = None + _smoothGroups = None + _peakpos = None + _peakpos1 = None + _peakmin = None + _peakmax = None + _peakpos2 = None + _peakmin2 = None + _peakmax2 = None + _peakpos3 = None + _peakmin3 = None + _peakmax3 = None + _lastpixel = None + _lastpixel2 = None + _lastpixel3 = None + _ccnumber = None + _maxoffset = None + _diffractionfocus = None + _outDir = None + _outTypes = None + _binning = None + def category(self): return "Diffraction;PythonAlgorithms" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py index 6acb8d39092f..333e56678d68 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py @@ -13,7 +13,7 @@ def name(self): def summary(self): return "Conjoin two file-based workspaces." - + def __load(self, directory, instr, run, loader, exts, wksp): filename = None for ext in exts: @@ -33,10 +33,11 @@ def __load(self, directory, instr, run, loader, exts, wksp): def PyInit(self): greaterThanZero = IntArrayBoundedValidator() greaterThanZero.setLower(0) - self.declareProperty(IntArrayProperty("RunNumbers",values=[0], validator=greaterThanZero), doc="Run numbers") + self.declareProperty(IntArrayProperty("RunNumbers",values=[0], + validator=greaterThanZero), doc="Run numbers") self.declareProperty(WorkspaceProperty("OutputWorkspace", "", direction=Direction.Output)) self.declareProperty(FileProperty("Directory", "", FileAction.OptionalDirectory)) - + def PyExec(self): # generic stuff for running wksp = self.getPropertyValue("OutputWorkspace") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py index 04155b4acb48..e3fd47463893 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py @@ -7,7 +7,8 @@ class ConjoinSpectra(PythonAlgorithm): """ Conjoins spectra from several workspaces into a single workspace - Spectra to be conjoined must be equally binned in order for ConjoinSpectra to work. If necessary use RebinToWorkspace first. + Spectra to be conjoined must be equally binned in order for ConjoinSpectra + to work. If necessary use RebinToWorkspace first. """ def category(self): @@ -58,7 +59,8 @@ def PyExec(self): DeleteWorkspace(Workspace=wsOutput) for wsName in wsNames: #extract the spectrum - ExtractSingleSpectrum(InputWorkspace=wsName,OutputWorkspace=wsTemp,WorkspaceIndex=wsIndex) + ExtractSingleSpectrum(InputWorkspace=wsName,OutputWorkspace=wsTemp, + WorkspaceIndex=wsIndex) labelString ="" if labelUsing != "": @@ -68,7 +70,9 @@ def PyExec(self): ta.setLabel(loopIndex,labelString) loopIndex += 1 if mtd.doesExist(wsOutput): - ConjoinWorkspaces(InputWorkspace1=wsOutput,InputWorkspace2=wsTemp,CheckOverlapping=False) + ConjoinWorkspaces(InputWorkspace1=wsOutput, + InputWorkspace2=wsTemp, + CheckOverlapping=False) if mtd.doesExist(wsTemp): DeleteWorkspace(Workspace=wsTemp) else: diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py index 5492ba7dd1a0..8ccb0c771437 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py @@ -16,6 +16,12 @@ class ConvertSnsRoiFileToMask(api.PythonAlgorithm): Class to handle reading old SNS reduction ROI files and turning it into a Mantid mask workspace. """ + + _roiFile = None + _instName = None + _filePrefix = None + _outputDir = None + def category(self): """ Set the category for the algorithm. diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py index 1839dcb61bc9..e1993299e005 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py @@ -7,6 +7,8 @@ class CorrectLogTimes(mantid.api.PythonAlgorithm): """ Class to shift log times to match proton charge """ + ws = None + def category(self): """ Mantid required """ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py index 83f1b9624edb..29a8549aeca8 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py @@ -6,6 +6,8 @@ class DSFinterp(PythonAlgorithm): + channelgroup = None + def category(self): return "Transforms\\Smoothing;Utility;PythonAlgorithms" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py index fde9c27489df..952a3f40991c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py @@ -8,6 +8,26 @@ class ExaminePowderDiffProfile(PythonAlgorithm): """ Create the input TableWorkspaces for LeBail Fitting """ + + loaddata = None + dataws = None + datawsname = None + datafilename = None + profiletype = None + loadinfofile = None + latticesize = None + irffilename = None + inputparamws = None + process_bkgd = None + usrbkgdpoints = None + bkgdwsname = None + bkgdtablews = None + backgroundtype = None + startx = None + endx = None + outwsname = None + inputbraggws = None + def category(self): """ """ From e4f2806eb3e026482a3ad5a1f41e04390a5d21e8 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Mon, 23 Feb 2015 11:29:01 +0000 Subject: [PATCH 393/414] Re #7083 Adding unit test --- .../test/PlotAsymmetryByLogValueTest.h | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h b/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h index e6bed858dac2..6839681d40c2 100644 --- a/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h +++ b/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h @@ -254,6 +254,44 @@ class PlotAsymmetryByLogValueTest : public CxxTest::TestSuite AnalysisDataService::Instance().remove(ws); } + void test_LogValueFunction () + { + const std::string ws = "Test_DeadTimeCorrection_FromRunData_Ws"; + + PlotAsymmetryByLogValue alg; + + TS_ASSERT_THROWS_NOTHING(alg.initialize()); + + alg.setPropertyValue("FirstRun", firstRun); + alg.setPropertyValue("LastRun", lastRun); + alg.setPropertyValue("OutputWorkspace", ws); + // We use 'beamlog_current' as log value because + // we want to test the 'Mean' function below and this is + // one of the few properties that contains different values over time + alg.setPropertyValue("LogValue","beamlog_current"); + alg.setPropertyValue("Function","Mean"); + alg.setPropertyValue("DeadTimeCorrType","None"); + + TS_ASSERT_THROWS_NOTHING(alg.execute()); + TS_ASSERT(alg.isExecuted()); + + MatrixWorkspace_sptr outWs = boost::dynamic_pointer_cast( + AnalysisDataService::Instance().retrieve(ws)); + + TS_ASSERT(outWs); + TS_ASSERT_EQUALS(outWs->blocksize(), 2); + TS_ASSERT_EQUALS(outWs->getNumberHistograms(),1); + + // Now we want to test X values (log values) in the output workspace + // rather than asymmetry (Y values) + const Mantid::MantidVec& X = outWs->readX(0); + + TS_ASSERT_DELTA(X[0], 179.078620, 0.00001); + TS_ASSERT_DELTA(X[1], 178.849998, 0.00001); + + AnalysisDataService::Instance().remove(ws); + } + private: std::string firstRun,lastRun; From 91c1954499ed2c55c746d4977392319a0db99feb Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 23 Feb 2015 11:30:17 +0000 Subject: [PATCH 394/414] Finished addressing member variables Refs #11145 --- .../plugins/algorithms/ExportExperimentLog.py | 19 +++++++- .../algorithms/ExportSampleLogsToCSVFile.py | 14 ++++++ .../plugins/algorithms/LoadFullprofFile.py | 6 ++- .../plugins/algorithms/LoadMultipleGSS.py | 7 ++- .../plugins/algorithms/MaskBTP.py | 5 ++ .../plugins/algorithms/PoldiProjectAddDir.py | 12 ----- .../plugins/algorithms/PoldiProjectRun.py | 4 -- .../algorithms/RefinePowderDiffProfileSeq.py | 46 +++++++++++++++++++ .../plugins/algorithms/SNSPowderReduction.py | 27 +++++++++++ .../algorithms/SelectPowderDiffPeaks.py | 3 ++ .../plugins/algorithms/Symmetrise.py | 12 +++++ .../UpdatePeakParameterTableValue.py | 3 ++ .../plugins/algorithms/VesuvioResolution.py | 3 ++ .../plugins/algorithms/sfCalculator.py | 5 ++ 14 files changed, 145 insertions(+), 21 deletions(-) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py index 0dfbd0139ab6..79d167d4e04e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py @@ -5,12 +5,28 @@ import datetime import time import os - + class ExportExperimentLog(PythonAlgorithm): """ Algorithm to export experiment log """ + _wksp = None + _sampleLogNames = None + _sampleLogOperations = None + _fileformat = None + _valuesep = None + _logfilename = None + _reorderOld = None + _timezone = None + _titleToOrder = None + _orderRecord = None + titleToOrder = None + _removeDupRecord = None + _ovrdTitleValueDict = None + _headerTitles = None + _filemode = None + def summmary(self): return "Exports experimental log." @@ -53,7 +69,6 @@ def PyInit(self): "Europe/Paris", "Europe/Copenhagen"] self.declareProperty("TimeZone", "America/New_York", StringListValidator(timezones)) - return diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py index 794c7aa47292..7b606e5828da 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py @@ -7,6 +7,20 @@ class ExportSampleLogsToCSVFile(PythonAlgorithm): """ Python algorithm to export sample logs to spread sheet file for VULCAN """ + + _wksp = None + _outputfilename = None + _sampleloglist = None + _headerconten = None + _writeheader = None + _headercontent = None + _timezone = None + _timeTolerance = None + _maxtimestamp = None + _maxtime = None + _starttime = None + _localtimediff = None + def category(self): """ Category """ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py index 7956ca69d90a..0c3456f81e20 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py @@ -9,6 +9,10 @@ class LoadFullprofFile(PythonAlgorithm): """ Create the input TableWorkspaces for LeBail Fitting """ + + _tableWS = None + _dataWS = None + def category(self): """ """ @@ -133,7 +137,7 @@ def _importFullprofHKLFile(self, hklfilename): if hkldict.has_key(dkey): if _OUTPUTLEVEL == "INFORMATION": - self.warning("Warning! Duplicate HKL %d, %d, %d" (h, k, l)) + self.warning("Warning! Duplicate HKL %d, %d, %d" % (h, k, l)) continue if fwhm < 1.0E-5: diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py index e226a6747e00..a74d3878d9eb 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py @@ -5,6 +5,10 @@ import os class LoadMultipleGSS(PythonAlgorithm): + + __exts = None + __loader = None + def category(self): return "DataHandling;PythonAlgorithms" @@ -25,7 +29,7 @@ def __load(self, directory, prefix): self.log().information("Trying to load '%s'" % filename) self.__loader(Filename=filename, OutputWorkspace=prefix, UseBankIDasSpectrumNumber=True) return - except Exception, e: + except Exception, _: pass raise RuntimeError("Failed to load run %s" % prefix) @@ -47,7 +51,6 @@ def PyExec(self): self.__loader = LoadGSS # load things and conjoin them - first = True for run in runs: wksp = "%s_%d" % (prefix,run) self.__load(directory, wksp) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py index 75d0f4a119d1..4bd2f7b122d4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py @@ -8,6 +8,11 @@ class MaskBTP(mantid.api.PythonAlgorithm): """ Class to generate grouping file """ + instname = None + instrument = None + bankmin = None + bankmax = None + def category(self): """ Mantid required """ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py index 5e17cbbf85a8..29f48bd87486 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py @@ -13,8 +13,6 @@ import re - - class PoldiProjectAddDir(PythonAlgorithm): def category(self): @@ -38,15 +36,10 @@ def PyInit(self): self.declareProperty(ITableWorkspaceProperty("PoldiAnalysis", "PoldiAnalysis", direction=Direction.Output), "Poldi analysis main worksheet") - - - - def path_leaf(path): head, tail = ntpath.split(path) return tail - def interpreteName(self, name): patern="(.*[ a-zA-Z]*/*\*)*poldi(?P[0-9]*)n(?P[0-9]*)" regex = re.match(patern, name, re.M|re.I) @@ -54,11 +47,6 @@ def interpreteName(self, name): numero = int(regex.group("numero")) return (year, numero) - - - - - def PyExec(self): """ Mantid required """ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py index 50d42c59855c..1976f889e970 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py @@ -63,10 +63,6 @@ def PyInit(self): direction = Direction.Input) - - - - def PyExec(self): """ Mantid required """ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py index b2bb76c6dad0..15a3af799a12 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py @@ -12,6 +12,25 @@ class RefinePowderDiffProfileSeq(PythonAlgorithm): """ Refine powder diffractometer profile by Le Bail algorithm sequentially """ + + dataws = None + wsindex = None + startx = None + endx = None + _lastStep = None + _projectID = None + functionoption = None + peaktype = None + bkgdtype = None + bkgdparws = None + profilews = None + braggpeakws = None + paramstofit = None + numcycles = None + outprojectfilename = None + inprojectfilename = None + datawsname = None + def category(self): """ Category """ @@ -195,6 +214,23 @@ class SeqRefineProfile: 4. If no further instruction, only need to set up parameters to refine the input/starting values should be from the last """ + + _datawsname = None + _profileWS = None + _braggpeakws = None + _bkgdtype = None + _bkgdparws = None + _wsgroup = None + datawsname = None + wsindex = None + _recordws = None + _recordwsLastRowValid = None + _lastValidStep = None + _lastValidRowIndex = None + _peakType = None + _bkgdType = None + _currstep = None + def __init__(self, ID, glog): """ """ @@ -712,6 +748,16 @@ def resetParametersGroups(tablews): class RefineProfileParameters: """ Class to refine profile parameters ONE step """ + + datawsname = None + inprofilewsname = None + inreflectionwsname = None + bkgdtype = None + bkgdtablewsname = None + outprofilewsname = None + outreflectionwsname = None + outbkgdtablewsname = None + def __init__(self, glog): """ Initialization """ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py index 305f27c46000..597b6da5e367 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py @@ -18,6 +18,33 @@ EVENT_WORKSPACE_ID = "EventWorkspace" class SNSPowderReduction(DataProcessorAlgorithm): + + _resampleX = None + _binning = None + _bin_in_dspace = None + _instrument = None + _filterBadPulses = None + _removePromptPulseWidth = None + _LRef = None + _DIFCref = None + _wavelengthMin = None + _vanPeakFWHM = None + _vanSmoothing = None + _scaleFactor = None + _outDir = None + _outPrefix = None + _outTypes = None + _infodict = None + _chunks = None + _splitws = None + _splitinfotablews = None + _normalisebycurrent = None + _lowResTOFoffset = None + _focusPos = None + _charTable = None + iparmFile = None + _info = None + def category(self): return "Diffraction;PythonAlgorithms" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py index f1f48228b43e..fac88e2cbd3b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py @@ -8,6 +8,9 @@ class SelectPowderDiffPeaks(PythonAlgorithm): """ Algorithm to select the powder diffraction peaks for Le Bail Fit """ + + mPeaks = None + def category(self): """ """ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py index 05eab60bd11d..3e5ecae529fc 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py @@ -13,6 +13,18 @@ class Symmetrise(PythonAlgorithm): + _sample = None + _x_min = None + _x_max = None + _plot = None + _save = None + _spectra_range = None + _output_workspace = None + _props_output_workspace = None + _positive_min_index = None + _positive_max_index = None + _negative_min_index = None + def category(self): return 'PythonAlgorithms' diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py index 09c2c90a91e4..998775666509 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py @@ -8,6 +8,9 @@ class UpdatePeakParameterTableValue(mantid.api.PythonAlgorithm): """ Class to generate grouping file """ + tableColNames = None + parameternames = None + def category(self): """ Mantid required """ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py index 5bae8cd4be4d..d78656c67617 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py @@ -7,6 +7,9 @@ class VesuvioResolution(PythonAlgorithm): + _spectrum_index = None + _mass = None + def category(self): return 'Inelastic' diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py index 6d4abb895598..3cc5c49da707 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py @@ -67,6 +67,11 @@ class sfCalculator(object): is_nexus_detector_rotated_flag = True + a = None + b = None + error_a = None + error_b = None + def __init__(self, numerator=None, denominator=None, tof_range=None): From 6477d24c2783772856641f46c996d0378ccd42ca Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Mon, 23 Feb 2015 11:51:36 +0000 Subject: [PATCH 395/414] Re #7083 Change workspace name in unit test --- .../Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h b/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h index 6839681d40c2..2ec9773aeab6 100644 --- a/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h +++ b/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h @@ -256,7 +256,7 @@ class PlotAsymmetryByLogValueTest : public CxxTest::TestSuite void test_LogValueFunction () { - const std::string ws = "Test_DeadTimeCorrection_FromRunData_Ws"; + const std::string ws = "Test_LogValueFunction"; PlotAsymmetryByLogValue alg; From df8d3d84d40888190eb1714474bd76c0757845b2 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 23 Feb 2015 12:14:40 +0000 Subject: [PATCH 396/414] Initial clean up of Python files in scripts Refs #11144 --- .../Calibration/Examples/TubeCalibDemoMaps_B1.py | 2 +- .../Examples/TubeCalibDemoWish_5panels.py | 2 +- .../scripts/Calibration/tube_calib_fit_params.py | 2 +- Code/Mantid/scripts/Calibration/tube_spec.py | 2 +- Code/Mantid/scripts/CrystalTools/PeakReport.py | 2 +- Code/Mantid/scripts/Engineering/EnginXUtils.py | 1 - Code/Mantid/scripts/FilterEvents/eventFilterGUI.py | 14 ++++++++------ .../scripts/Inelastic/Direct/NonIDF_Properties.py | 4 ++-- .../Inelastic/Direct/PropertiesDescriptors.py | 2 ++ .../scripts/Inelastic/Direct/PropertyManager.py | 2 +- .../scripts/Inelastic/Direct/ReductionWrapper.py | 2 +- .../scripts/Inelastic/Direct/RunDescriptor.py | 4 ++-- Code/Mantid/scripts/Inelastic/Direct/dgreduce.py | 2 +- .../Inelastic/IndirectDiffractionReduction.py | 3 ++- .../scripts/Inelastic/IndirectEnergyConversion.py | 6 ++++-- .../inelastic_indirect_reduction_steps.py | 1 + Code/Mantid/scripts/Inelastic/msg_reducer.py | 2 ++ 17 files changed, 31 insertions(+), 22 deletions(-) diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py index 8d73f4a61ef8..3a4d057be909 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py @@ -16,7 +16,7 @@ # Set initial parameters for peak finding ExpectedHeight = -1000.0 # Expected Height of Gaussian Peaks (initial value of fit parameter) ExpectedWidth = 8.0 # Expected width of Gaussian peaks in pixels (initial value of fit parameter) -ExpectedPositions = [4.0, 85.0, 128.0, 161.0, 252.0] +ExpectedPositions = [4.0, 85.0, 128.0, 161.0, 252.0] # Expected positions of the edges and Gaussian peaks in pixels (initial values of fit parameters) # Set what we want to calibrate (e.g whole intrument or one door ) diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py index f704352ba7d3..85711023f698 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py @@ -18,7 +18,7 @@ from tube_spec import TubeSpec -def CalibrateWish( run_per_panel_list): +def CalibrateWish(run_per_panel_list): ''' :param run_per_panel_list: is a list of tuples with the run number and the associated panel diff --git a/Code/Mantid/scripts/Calibration/tube_calib_fit_params.py b/Code/Mantid/scripts/Calibration/tube_calib_fit_params.py index 3610244e9a7a..3a2ccca35605 100644 --- a/Code/Mantid/scripts/Calibration/tube_calib_fit_params.py +++ b/Code/Mantid/scripts/Calibration/tube_calib_fit_params.py @@ -1,7 +1,7 @@ from mantid.simpleapi import * from mantid.kernel import * -class TubeCalibFitParams: +class TubeCalibFitParams(object): # This class is to take the fitting method and parameters for fitting the peaks crated by the calibration slits etc # and to deliver them to TubeCalib, so it can fit the peaks appropriately diff --git a/Code/Mantid/scripts/Calibration/tube_spec.py b/Code/Mantid/scripts/Calibration/tube_spec.py index 8b71923e42d4..64fcc9642109 100644 --- a/Code/Mantid/scripts/Calibration/tube_spec.py +++ b/Code/Mantid/scripts/Calibration/tube_spec.py @@ -108,7 +108,7 @@ def isTube(self, comp): """ # We simply assume it's a tube if it has a large number of children if hasattr( comp, "nelements"): - return comp.nelements() >= self.minNumDetsInTube + return comp.nelements() >= self.minNumDetsInTube else: return False diff --git a/Code/Mantid/scripts/CrystalTools/PeakReport.py b/Code/Mantid/scripts/CrystalTools/PeakReport.py index eb435047225e..c7a28c6c3e59 100644 --- a/Code/Mantid/scripts/CrystalTools/PeakReport.py +++ b/Code/Mantid/scripts/CrystalTools/PeakReport.py @@ -9,7 +9,7 @@ from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import * -class PeakReport: +class PeakReport(object): """ Peak Report is a class used to creating one or more peak integration reports as PDFs. """ diff --git a/Code/Mantid/scripts/Engineering/EnginXUtils.py b/Code/Mantid/scripts/Engineering/EnginXUtils.py index 6ca38533361e..26a6d6e9c505 100644 --- a/Code/Mantid/scripts/Engineering/EnginXUtils.py +++ b/Code/Mantid/scripts/Engineering/EnginXUtils.py @@ -43,4 +43,3 @@ def isIndexInBank(index): return filter(isIndexInBank, range(0, ws.getNumberHistograms())) - diff --git a/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py b/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py index a2e86978f080..cc246846f9aa 100644 --- a/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py +++ b/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py @@ -1,7 +1,7 @@ #pylint: disable=invalid-name import numpy -from Ui_MainWindow import Ui_MainWindow #import line for the UI python class +from FilterEvents.Ui_MainWindow import Ui_MainWindow #import line for the UI python class from PyQt4 import QtCore, QtGui from PyQt4.QtCore import * from PyQt4.QtGui import * @@ -33,7 +33,7 @@ class MyPopErrorMsg(QWidget): def __init__(self): """ Init """ - import Ui_ErrorMessage as errui + import FilterEvents.Ui_ErrorMessage as errui QWidget.__init__(self) @@ -58,10 +58,10 @@ def quit(self): return - def XpaintEvent(self, e): + def XpaintEvent(self, _): """ ??? """ - import Ui_ErrorMessage as errui + import FilterEvents.Ui_ErrorMessage as errui self.ui = errui.Ui_Dialog() self.ui.setupUi(self) @@ -107,6 +107,8 @@ class MainWindow(QtGui.QMainWindow): """ + _errMsgWindow = None + def __init__(self, parent=None): """ Intialization and set up """ @@ -445,8 +447,8 @@ def set_stopTime(self): # Correct value resetT = True - if irightvalue >= 100: - irightvalue == 100 + if irightvalue > 100: + irightvalue = 100 elif irightvalue < self._leftSlideValue: irightvalue = self._leftSlideValue else: diff --git a/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py b/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py index b4c1ed622716..102426faa1ce 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py +++ b/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py @@ -1,6 +1,6 @@ #pylint: disable=invalid-name -from PropertiesDescriptors import * -from RunDescriptor import RunDescriptor,RunDescriptorDependent +from Direct.PropertiesDescriptors import * +from Direct.RunDescriptor import RunDescriptor,RunDescriptorDependent class NonIDF_Properties(object): diff --git a/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py b/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py index b8494f8a5eb5..0459aa0c1819 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py +++ b/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py @@ -556,6 +556,8 @@ def _parce_string2list(self,val): #----------------------------------------------------------------------------------------- class PropertyFromRange(PropDescriptor): """ Descriptor for property, which can have one value from a list of values """ + _current_value = None + def __init__(self,availible_values,default_value): self._availible_values = availible_values self.__set__(None,default_value) diff --git a/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py b/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py index 5ab7fe6d8978..33c518c10e4c 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py +++ b/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py @@ -1,5 +1,5 @@ #pylint: disable=invalid-name -from NonIDF_Properties import * +from Direct.NonIDF_Properties import * from collections import OrderedDict diff --git a/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py b/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py index ee28a46f9c19..e18d3e1aa7de 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py +++ b/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py @@ -3,7 +3,7 @@ from mantid import config,api from mantid.kernel import funcreturns -from PropertyManager import PropertyManager +from Direct.PropertyManager import PropertyManager # this import is used by children from Direct.DirectEnergyConversion import DirectEnergyConversion #import inspect diff --git a/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py b/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py index 6b61fbc53dbf..edddf86fb180 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py +++ b/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py @@ -3,7 +3,7 @@ from mantid.simpleapi import * -from PropertiesDescriptors import * +from Direct.PropertiesDescriptors import * import re @@ -701,4 +701,4 @@ def __set__(self,instance,value): # DeleteWorkspace(self._ws_name) # object.__del__(self) - \ No newline at end of file + diff --git a/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py b/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py index 2c9d4ca926b0..9b4c61b5bcc3 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py +++ b/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py @@ -1,6 +1,6 @@ #pylint: disable=invalid-name """ Empty class temporary left for compatibility with previous interfaces """ -import DirectEnergyConversion as DRC +import Direct.DirectEnergyConversion as DRC from mantid.simpleapi import * from mantid.kernel import funcreturns diff --git a/Code/Mantid/scripts/Inelastic/IndirectDiffractionReduction.py b/Code/Mantid/scripts/Inelastic/IndirectDiffractionReduction.py index bf7fe6d626d9..af6f9f98bd8b 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectDiffractionReduction.py +++ b/Code/Mantid/scripts/Inelastic/IndirectDiffractionReduction.py @@ -69,5 +69,6 @@ def getStringProperty(workspace, property): inst = mantid.AnalysisDataService[workspace].getInstrument() try: prop = inst.getStringParameter(property)[0] - except IndexError: return "" + except IndexError: + return "" return prop diff --git a/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py b/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py index 477210de2277..efee01eca620 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py +++ b/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py @@ -34,8 +34,10 @@ def loadData(rawfiles, outWS='RawFile', Sum=False, SpecMin=-1, SpecMax=-1,\ return workspaces def createMappingFile(groupFile, ngroup, nspec, first): - if ngroup == 1 : return 'All' - if nspec == 1 : return 'Individual' + if ngroup == 1: + return 'All' + if nspec == 1: + return 'Individual' filename = config['defaultsave.directory'] filename = os.path.join(filename, groupFile) handle = open(filename, 'w') diff --git a/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py b/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py index d0248d8f88e9..70bec0c356c9 100644 --- a/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py +++ b/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py @@ -35,6 +35,7 @@ class LoadData(ReductionStep): _data_files = {} _extra_load_opts = {} _contains_event_data = False + _reducer = None def __init__(self): """Initialise the ReductionStep. Constructor should set the initial diff --git a/Code/Mantid/scripts/Inelastic/msg_reducer.py b/Code/Mantid/scripts/Inelastic/msg_reducer.py index df597f58c3dd..fe8a132e8758 100644 --- a/Code/Mantid/scripts/Inelastic/msg_reducer.py +++ b/Code/Mantid/scripts/Inelastic/msg_reducer.py @@ -26,6 +26,8 @@ class MSGReducer(reducer.Reducer): _save_formats = [] _info_table_props = None _extra_load_opts = {} + _reduction_steps = None + _data_files = None def __init__(self): super(MSGReducer, self).__init__() From a966d3b43f6f1ebb4d91115d1f54de8deca28ebb Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 23 Feb 2015 13:44:48 +0000 Subject: [PATCH 397/414] More refactoring of Python scripts This has extended to final newlines, semicolons, indentation Refs #11144 --- Code/Mantid/scripts/SANS/isis_instrument.py | 8 +- Code/Mantid/scripts/SANS/isis_reducer.py | 25 ++ .../scripts/SANS/isis_reduction_steps.py | 5 +- .../Mantid/scripts/SANS/reduction_settings.py | 2 +- .../scripts/TofConverter/converterGUI.py | 2 +- .../scripts/Vates/Diffraction_Workflow.py | 8 +- .../scripts/test/ConvertToWavelengthTest.py | 3 +- .../test/DirectEnergyConversionTest.py | 29 +- .../scripts/test/DirectPropertyManagerTest.py | 135 +++--- .../DirectPropertyManater_OldInterfaceXest.py | 123 +++--- .../test/DirectReductionHelpersTest.py | 393 +++++++++--------- Code/Mantid/scripts/test/MariReduction.py | 120 +++--- .../scripts/test/ReductionSettingsTest.py | 3 +- .../scripts/test/ReductionWrapperTest.py | 3 +- Code/Mantid/scripts/test/RunDescriptorTest.py | 24 +- Code/Mantid/scripts/test/SANSUtilitytests.py | 2 +- 16 files changed, 452 insertions(+), 433 deletions(-) diff --git a/Code/Mantid/scripts/SANS/isis_instrument.py b/Code/Mantid/scripts/SANS/isis_instrument.py index 3f1c3e6a23b7..1377abde7fae 100644 --- a/Code/Mantid/scripts/SANS/isis_instrument.py +++ b/Code/Mantid/scripts/SANS/isis_instrument.py @@ -88,8 +88,8 @@ def load_empty(self, workspace_name = None): return workspace_name -class DetectorBank: - class _DectShape: +class DetectorBank(object): + class _DectShape(object): """ Stores the dimensions of the detector, normally this is a square which is easy, but it can have a hole in it which is harder! @@ -128,7 +128,7 @@ def isRectangle(self): def n_pixels(self): return self._n_pixels - class _RescaleAndShift: + class _RescaleAndShift(object): """ Stores property about the detector which is used to rescale and shift data in the bank after data have been reduced. The scale attempts to @@ -1179,6 +1179,7 @@ def cur_detector_position(self, ws_name): return [-pos.getX(), -pos.getY()] + class LARMOR(ISISInstrument): _NAME = 'LARMOR' WAV_RANGE_MIN = 2.2 @@ -1232,6 +1233,5 @@ def cur_detector_position(self, ws_name): return [-pos.getX(), -pos.getY()] - if __name__ == '__main__': pass diff --git a/Code/Mantid/scripts/SANS/isis_reducer.py b/Code/Mantid/scripts/SANS/isis_reducer.py index f6bdb9599e9b..d22422c81400 100644 --- a/Code/Mantid/scripts/SANS/isis_reducer.py +++ b/Code/Mantid/scripts/SANS/isis_reducer.py @@ -136,6 +136,31 @@ class ISISReducer(Reducer): ## Path for user settings files _user_file_path = '.' + _can = None + _tidy = None + _conv_Q = None + _reduction_steps = None + user_settings = None + _out_name = None + event2hist = None + crop_detector = None + mask = None + to_wavelen = None + norm_mon = None + transmission_calculator = None + _corr_and_scale = None + prep_normalize = None + to_Q = None + _background_subtracter = None + geometry_correcter = None + _rem_nans = None + _sample_run = None + _can_run = None + _slices_def = None + _slice_index = None + samp_trans_load = None + can_trans_load = None + def _to_steps(self): """ Defines the steps that are run and their order diff --git a/Code/Mantid/scripts/SANS/isis_reduction_steps.py b/Code/Mantid/scripts/SANS/isis_reduction_steps.py index 9dd1305c0e4f..308d8e5e8ec0 100644 --- a/Code/Mantid/scripts/SANS/isis_reduction_steps.py +++ b/Code/Mantid/scripts/SANS/isis_reduction_steps.py @@ -368,6 +368,9 @@ class LoadTransmissions(): sample or can """ + _direct_name = None + _trans_name = None + def __init__(self, is_can=False, reload=True): """ Two settings can be set at initialization, if this is for @@ -2731,7 +2734,7 @@ def set_height(self, height): # For a cylinder and sphere the height=width=radius if (not self._shape is None) and (self._shape.startswith('cylinder')): self._width = self._height - self._use_wksp_widtht = False + self._use_wksp_width = False def get_height(self): self.raise_if_zero(self._height, "height") diff --git a/Code/Mantid/scripts/SANS/reduction_settings.py b/Code/Mantid/scripts/SANS/reduction_settings.py index 6b16926ccae1..97d4087e8776 100644 --- a/Code/Mantid/scripts/SANS/reduction_settings.py +++ b/Code/Mantid/scripts/SANS/reduction_settings.py @@ -79,7 +79,7 @@ def get_settings_object(settings_prop_man_name=REDUCTION_SETTINGS_OBJ_NAME): the ISIS SANS reduction code. Please make a single call to this function and then pass around the returned object to wherever it is needed. """ - class PropertyManagerPicklableWrapper: + class PropertyManagerPicklableWrapper(object): """ Pickling has not been enabled for PropertyManager, and this is needed in the Reducer so that the "deep copy" stuff does not complain. This diff --git a/Code/Mantid/scripts/TofConverter/converterGUI.py b/Code/Mantid/scripts/TofConverter/converterGUI.py index 23a0a7bd3bee..51b6bcd9f31b 100644 --- a/Code/Mantid/scripts/TofConverter/converterGUI.py +++ b/Code/Mantid/scripts/TofConverter/converterGUI.py @@ -1,5 +1,5 @@ #pylint: disable=invalid-name -from Ui_MainWindow import Ui_MainWindow #import line for the UI python class +from TofConverter.Ui_MainWindow import Ui_MainWindow #import line for the UI python class from PyQt4 import QtCore, QtGui import math diff --git a/Code/Mantid/scripts/Vates/Diffraction_Workflow.py b/Code/Mantid/scripts/Vates/Diffraction_Workflow.py index 657bb13c6a3f..b751920f698b 100644 --- a/Code/Mantid/scripts/Vates/Diffraction_Workflow.py +++ b/Code/Mantid/scripts/Vates/Diffraction_Workflow.py @@ -5,7 +5,7 @@ filename = ws_name +"_event.nxs" ws = LoadEventNexus(Filename=filename,FilterByTofMin=3000, FilterByTofMax=16000) -# ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +# ------------------------------------------------------------------------------------------------------------------------------------------ # Part 1. Basic Reduction # Spherical Absorption and Lorentz Corrections @@ -37,7 +37,7 @@ # Save for SHELX SaveHKL(InputWorkspace=PeaksLattice, Filename=ws_name + '.hkl') -# ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +# ------------------------------------------------------------------------------------------------------------------------------------------ # Part 2. Alternative/Advanced Processing Steps @@ -62,7 +62,7 @@ # Save for SHELX SaveHKL(InputWorkspace=PeaksLatticeFFT, Filename=ws_name + '.hkl') -# ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +# ------------------------------------------------------------------------------------------------------------------------------------------ # Part 3. Utilising the UB # Copy the UB matrix back to the original workspace @@ -73,7 +73,7 @@ HKL = ConvertToDiffractionMDWorkspace(InputWorkspace=ws,\ OutputDimensions='HKL',LorentzCorrection='0', SplitInto='2',SplitThreshold='150') -# ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +# ------------------------------------------------------------------------------------------------------------------------------------------ # Part 4. Displaying # Bin to a regular grid diff --git a/Code/Mantid/scripts/test/ConvertToWavelengthTest.py b/Code/Mantid/scripts/test/ConvertToWavelengthTest.py index a4ad82fb1423..e6e8c0467b2b 100644 --- a/Code/Mantid/scripts/test/ConvertToWavelengthTest.py +++ b/Code/Mantid/scripts/test/ConvertToWavelengthTest.py @@ -134,4 +134,5 @@ def test_convert(self): self.assertTrue(x_max <= 10.0) if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() + diff --git a/Code/Mantid/scripts/test/DirectEnergyConversionTest.py b/Code/Mantid/scripts/test/DirectEnergyConversionTest.py index 8575dba4e63a..897c2e03e105 100644 --- a/Code/Mantid/scripts/test/DirectEnergyConversionTest.py +++ b/Code/Mantid/scripts/test/DirectEnergyConversionTest.py @@ -128,7 +128,7 @@ def test_do_white_wb(self) : white_ws = tReducer.do_white(wb_ws, None, None) self.assertTrue(white_ws) - + def test_get_set_attributes(self): tReducer = self.reducer @@ -163,17 +163,17 @@ def test_get_abs_normalization_factor(self) : tReducer.prop_man.incident_energy = 5. tReducer.prop_man.monovan_integr_range=[-10,10] - (nf1,nf2,nf3,nf4) = tReducer.get_abs_normalization_factor(mono_ws.getName(),5.) + (nf1,nf2,nf3,nf4) = tReducer.get_abs_normalization_factor(mono_ws.getName(),5.) self.assertAlmostEqual(nf1,0.58561121802167193,7) self.assertAlmostEqual(nf1,nf2) self.assertAlmostEqual(nf2,nf3) self.assertAlmostEqual(nf3,nf4) - # check warning. WB spectra with 0 signal indicate troubles. + # check warning. WB spectra with 0 signal indicate troubles. mono_ws = CreateSampleWorkspace(NumBanks=1, BankPixelWidth=4, NumEvents=10000,XUnit='DeltaE',XMin=-5,XMax=15,BinWidth=0.1,function='Flat background') LoadInstrument(mono_ws,InstrumentName='MARI') sig = mono_ws.dataY(0) - sig[:]=0 + sig[:]=0 (nf1,nf2,nf3,nf4) = tReducer.get_abs_normalization_factor(mono_ws.getName(),5.) self.assertAlmostEqual(nf1,0.585611218022,7) @@ -204,8 +204,8 @@ def test_dgreduce_works(self): #abs_units(wb_for_run,sample_run,monovan_run,wb_for_monovanadium,samp_rmm,samp_mass,ei_guess,rebin,map_file='default',monovan_mapfile='default',**kwargs): ws = dgreduce.abs_units(wb_ws,run_ws,None,wb_ws,10,100,8.8,[-10,0.1,7],None,None,**par) self.assertTrue(isinstance(ws,api.MatrixWorkspace)) - - + + ##def test_diag_call(self): ## tReducer = self.reducer ## # should do nothing as already initialized above, but if not will initiate the instrument @@ -215,7 +215,7 @@ def test_dgreduce_works(self): def test_energy_to_TOF_range(self): ws = Load(Filename='MAR11001.raw',LoadMonitors='Include') - + en_range = [0.8*13,13,1.2*13] detIDs=[1,2,3,10] red = DirectEnergyConversion() @@ -273,7 +273,7 @@ def test_late_rebinning(self): # References used to test against ordinary reduction ref_ws = Rebin(run,Params=[tMin,1,tMax],PreserveEvents=False) ref_ws_monitors = CloneWorkspace('run_monitors') - # just in case, wb should work without clone too. + # just in case, wb should work without clone too. wb_clone = CloneWorkspace(wb_ws) # Run Mono @@ -339,7 +339,7 @@ def test_multirep_mode(self): XUnit='TOF',xMin=tMin,xMax=tMax) LoadInstrument(run,InstrumentName='MARI') - # do second + # do second run2 = CloneWorkspace(run) run2_monitors = CloneWorkspace(run_monitors) @@ -372,7 +372,7 @@ def test_multirep_mode(self): # rename samples from previous workspace to avoid deleting them on current run for ind,item in enumerate(result): result[ind]=RenameWorkspace(item,OutputWorkspace='SampleRez#'+str(ind)) - # + # result2 = tReducer.convert_to_energy(None,run2,[67.,122.],[-2,0.02,0.8]) rez = CheckWorkspacesMatch(result[0],result2[0]) @@ -438,7 +438,7 @@ def test_multirep_abs_units_mode(self): # rename samples from previous workspace to avoid deleting them on current run for ind,item in enumerate(result): result[ind]=RenameWorkspace(item,OutputWorkspace='SampleRez#'+str(ind)) - # + # result2 = tReducer.convert_to_energy(None,run2) rez = CheckWorkspacesMatch(result[0],result2[0]) @@ -447,9 +447,6 @@ def test_multirep_abs_units_mode(self): self.assertEqual(rez,'Success!') - - - - if __name__=="__main__": - unittest.main() + unittest.main() + diff --git a/Code/Mantid/scripts/test/DirectPropertyManagerTest.py b/Code/Mantid/scripts/test/DirectPropertyManagerTest.py index ba4e7ef402ed..2ef643c166d4 100644 --- a/Code/Mantid/scripts/test/DirectPropertyManagerTest.py +++ b/Code/Mantid/scripts/test/DirectPropertyManagerTest.py @@ -32,12 +32,12 @@ def getInstrument(InstrumentName='MAR'): idf_file=api.ExperimentInfo.getInstrumentFilename(InstrumentName) tmp_ws_name = '__empty_' + InstrumentName if not mtd.doesExist(tmp_ws_name): - LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) + LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) return mtd[tmp_ws_name].getInstrument() - + def test_init_reducer(self): - + propman=self.prop_man self.assertEqual(propman.deltaE_mode,'direct') @@ -50,7 +50,7 @@ def test_set_non_default_wrong_value(self): # non-existing property can not be set! self.assertRaises(KeyError,setattr,propman,'non_existing_property',"Something_Meaningfull") - # existing simple assignment works + # existing simple assignment works propman.load_monitors_with_workspace = False propman.load_monitors_with_workspace = True self.assertTrue(propman.load_monitors_with_workspace) @@ -154,7 +154,7 @@ def test_set_non_default_complex_value(self): self.assertEqual(propman.ei_mon_spectra,[2,3]," Default ei monitors on MARI should be as described in MARI_Parameters.xml file") - + propman.norm_mon_integration_range = [50,1050] range=propman.norm_mon_integration_range self.assertAlmostEqual(range[0],50.,7) @@ -183,7 +183,7 @@ def test_set_non_default_complex_value_synonims(self): self.assertTrue("ei-mon2-spec" in prop_changed,"changing test_ei2_mon_spectra should change ei-mon2-spectra") - propman.test_mon_spectra_composite = [10000,2000] + propman.test_mon_spectra_composite = [10000,2000] self.assertEqual(propman.ei_mon_spectra,[10000,2000]) prop_changed = propman.getChangedProperties() @@ -344,13 +344,13 @@ def test_diag_spectra(self): self.assertEqual(len(spectra),4) self.assertEqual(spectra[0],(1,17280)) self.assertEqual(spectra[3],(32257,41472)) - + def test_get_diagnostics_parameters(self): propman = self.prop_man params = propman.get_diagnostics_parameters() self.assertEqual(len(params),20) - + bkg_test_range0 = propman.background_test_range bkg_test_range = params['background_test_range'] bkg_range = propman.background_range @@ -362,25 +362,24 @@ def test_get_diagnostics_parameters(self): self.assertEqual(bkg_test_range,[1000,2000]) def test_check_monovan_changed(self): - propman = self.prop_man - - non_changed = propman._check_monovan_par_changed() - # nothing have changed initially - self.assertEqual(len(non_changed),2) + propman = self.prop_man + + non_changed = propman._check_monovan_par_changed() + # nothing have changed initially + self.assertEqual(len(non_changed),2) - propman.monovan_run = 102 - propman.log_changed_values() + propman.monovan_run = 102 + propman.log_changed_values() - propman.sample_mass = 1 - non_changed = propman._check_monovan_par_changed() - self.assertEqual(len(non_changed),1) - propman.sample_rmm = 200 - non_changed = propman._check_monovan_par_changed() - self.assertEqual(len(non_changed),0) + propman.sample_mass = 1 + non_changed = propman._check_monovan_par_changed() + self.assertEqual(len(non_changed),1) + propman.sample_rmm = 200 + non_changed = propman._check_monovan_par_changed() + self.assertEqual(len(non_changed),0) + propman.log_changed_values() - propman.log_changed_values() - def test_set_defailts_from_instrument(self) : ws = CreateSampleWorkspace(NumBanks=1, BankPixelWidth=4, NumEvents=100) @@ -394,7 +393,7 @@ def test_set_defailts_from_instrument(self) : self.assertAlmostEqual(propman.TestParam1,3.5) self.assertEquals(propman.TestParam2,"initial1") self.assertEquals(propman.TestParam3,"initial2") - + propman.TestParam2="gui_changed1" self.assertEquals(propman.TestParam2,"gui_changed1") @@ -408,7 +407,7 @@ def test_set_defailts_from_instrument(self) : self.assertTrue('TestParam2' in changes) self.assertTrue(not('TestParam3' in changes)) - + changes = propman.update_defaults_from_instrument(ws.getInstrument()) @@ -460,8 +459,8 @@ def test_set_complex_defailts_from_instrument(self) : self.assertEqual(propman.ParaPara,'OtherVal2') self.assertEqual(propman.BaseParam2,'OtherVal2') - - self.assertEquals(propman.BaseParam1,"OtherVal1") + + self.assertEquals(propman.BaseParam1,"OtherVal1") def test_set_all_defaults_from_instrument(self) : ws = CreateSampleWorkspace(NumBanks=1, BankPixelWidth=4, NumEvents=10) @@ -557,7 +556,7 @@ def test_set_energy_bins_and_ei(self): propman.energy_bins = None self.assertFalse(propman.energy_bins) - + def test_multirep_ei_iterate_over(self): propman = self.prop_man @@ -617,7 +616,7 @@ def test_multirep_ei_iterate_over(self): self.assertAlmostEqual(bins[2],0.8*en) ic+=1 self.assertEqual(ic,3) - # + # ic=0 for en in PropertyManager.incident_energy: self.assertAlmostEqual(en,eng[ic]) @@ -694,55 +693,55 @@ def test_ignore_complex_defailts_single_fom_instrument(self) : def test_monovan_integration_range(self): - propman = self.prop_man + propman = self.prop_man - propman.incident_energy = 10 - propman.monovan_lo_frac = -0.6 - propman.monovan_hi_frac = 0.7 + propman.incident_energy = 10 + propman.monovan_lo_frac = -0.6 + propman.monovan_hi_frac = 0.7 - range = propman.abs_units_van_range - self.assertAlmostEqual(range[0],-6.) - self.assertAlmostEqual(range[1], 7.) + range = propman.abs_units_van_range + self.assertAlmostEqual(range[0],-6.) + self.assertAlmostEqual(range[1], 7.) - range = propman.monovan_integr_range - self.assertAlmostEqual(range[0],-6.) - self.assertAlmostEqual(range[1], 7.) + range = propman.monovan_integr_range + self.assertAlmostEqual(range[0],-6.) + self.assertAlmostEqual(range[1], 7.) - propman.monovan_lo_value = -10 - propman.monovan_hi_value = 10 + propman.monovan_lo_value = -10 + propman.monovan_hi_value = 10 - range = propman.abs_units_van_range - self.assertAlmostEqual(range[0],-6.) - self.assertAlmostEqual(range[1], 7.) + range = propman.abs_units_van_range + self.assertAlmostEqual(range[0],-6.) + self.assertAlmostEqual(range[1], 7.) - propman.abs_units_van_range=[-40,40] - self.assertAlmostEqual(propman.monovan_lo_value,-40) - self.assertAlmostEqual(propman.monovan_hi_value,40) + propman.abs_units_van_range=[-40,40] + self.assertAlmostEqual(propman.monovan_lo_value,-40) + self.assertAlmostEqual(propman.monovan_hi_value,40) - range = propman.monovan_integr_range - self.assertAlmostEqual(range[0],-40) - self.assertAlmostEqual(range[1], 40) + range = propman.monovan_integr_range + self.assertAlmostEqual(range[0],-40) + self.assertAlmostEqual(range[1], 40) - propman.abs_units_van_range=None + propman.abs_units_van_range=None - range = propman.monovan_integr_range - self.assertAlmostEqual(range[0],-6.) - self.assertAlmostEqual(range[1], 7.) - # - propman.monovan_lo_frac = -0.7 - range = propman.monovan_integr_range - self.assertAlmostEqual(range[0],-7.) + range = propman.monovan_integr_range + self.assertAlmostEqual(range[0],-6.) + self.assertAlmostEqual(range[1], 7.) + # + propman.monovan_lo_frac = -0.7 + range = propman.monovan_integr_range + self.assertAlmostEqual(range[0],-7.) def test_save_filename(self): - propman = self.prop_man + propman = self.prop_man - propman.incident_energy = 10 - propman.sample_run = 0 - propman.monovan_run = None + propman.incident_energy = 10 + propman.sample_run = 0 + propman.monovan_run = None - name = propman.save_file_name - self.assertEqual(name,'MAR00000Ei10d00meV') + name = propman.save_file_name + self.assertEqual(name,'MAR00000Ei10d00meV') def test_log_to_Mantid(self): propman = self.prop_man @@ -781,7 +780,7 @@ def test_hadmask_options(self): self.assertTrue(propman.hard_mask_file is None) def test_hadmask_options_locked(self): - # + # propman1 = self.prop_man propman1.setChangedProperties() propman1.hardmaskPlus = 'a_hard_mask_file' @@ -815,7 +814,7 @@ def test_hadmask_options_locked(self): self.assertTrue(propman1.run_diagnostics) - + #def test_do_white(self) : # tReducer = self.reducer # monovan = 1000 @@ -823,8 +822,8 @@ def test_hadmask_options_locked(self): # name = tReducer.make_ckpt_name('do_white',monovan,data,'t1') # self.assertEqual('do_white1000t1',name) - - + + def test_monitors_list(self): propman = self.prop_man diff --git a/Code/Mantid/scripts/test/DirectPropertyManater_OldInterfaceXest.py b/Code/Mantid/scripts/test/DirectPropertyManater_OldInterfaceXest.py index bbc5e44094e5..c498af67b719 100644 --- a/Code/Mantid/scripts/test/DirectPropertyManater_OldInterfaceXest.py +++ b/Code/Mantid/scripts/test/DirectPropertyManater_OldInterfaceXest.py @@ -17,7 +17,7 @@ def __init__(self, methodName): def setUp(self): if self.reducer == None or type(self.reducer) != type(DirectEnergyConversion): - self.reducer = DirectEnergyConversion("MAPS"); + self.reducer = DirectEnergyConversion("MAPS") def tearDown(self): pass @@ -34,17 +34,17 @@ def test_set_non_default_wrong_value(self): def test_set_non_default_simple_value(self): tReducer = self.reducer # should do nothing as already initialized above - tReducer.initialise("MAP"); + tReducer.initialise("MAP") prop_changed=tReducer.set_input_parameters(van_mass=100,det_cal_file='det4to1_1912.dat') self.assertTrue("van_mass" in prop_changed) self.assertTrue("det_cal_file" in prop_changed) - self.assertEqual(tReducer.van_mass,100); - self.assertEqual(tReducer.det_cal_file,'det4to1_1912.dat'); + self.assertEqual(tReducer.van_mass,100) + self.assertEqual(tReducer.det_cal_file,'det4to1_1912.dat') self.assertAlmostEqual(tReducer.van_sig,0.,7) - kw=dict(); + kw=dict() kw["vanadium-mass"]=200 kw["diag_van_median_sigma"]=1 kw["det_cal_file"]=None @@ -54,8 +54,8 @@ def test_set_non_default_simple_value(self): self.assertTrue("van_mass" in prop_changed,"vanadium-mass should correspond to van_mass") self.assertTrue("van_sig" in prop_changed," diag_van_median_sigma should correspond to van_sig ") - self.assertEqual(tReducer.van_mass,200); - self.assertEqual(tReducer.det_cal_file,None); + self.assertEqual(tReducer.van_mass,200) + self.assertEqual(tReducer.det_cal_file,None) self.assertAlmostEqual(tReducer.van_sig,1.,7) @@ -63,7 +63,7 @@ def test_set_non_default_simple_value(self): def test_set_non_default_complex_value(self): tReducer = self.reducer # should do nothing as already initialized above, but if not will initiate the instrument - tReducer.initialise("MAP"); + tReducer.initialise("MAP") range = tReducer.norm_mon_integration_range self.assertAlmostEqual(range[0],1000.,7," Default integration min range on MAPS should be as described in MAPS_Parameters.xml file") @@ -73,7 +73,7 @@ def test_set_non_default_complex_value(self): self.assertRaises(KeyError,tReducer.set_input_parameters,mon_norm_range=1) self.assertRaises(KeyError,tReducer.set_input_parameters,mon_norm_range=[10,100,100]) - kw=dict(); + kw=dict() kw["norm_mon_integration_range"]=[50,1050] kw["ei-mon1-spec"]=10 prop_changed=tReducer.set_input_parameters(**kw) @@ -89,9 +89,9 @@ def test_set_non_default_complex_value(self): def test_set_non_default_complex_value_synonims(self): tReducer = self.reducer # should do nothing as already initialized above, but if not will initiate the instrument - tReducer.initialise("MAP"); + tReducer.initialise("MAP") # - kw = dict(); + kw = dict() kw["test_ei2_mon_spectra"]=10000 prop_changed=tReducer.set_input_parameters(**kw) @@ -106,7 +106,7 @@ def test_set_non_default_complex_value_synonims(self): def test_set_get_mono_range(self): tReducer = self.reducer # should do nothing as already initialized above, but if not will initiate the instrument - tReducer.initialise("MAP"); + tReducer.initialise("MAP") energy_incident = 100 tReducer.incident_energy = energy_incident @@ -118,7 +118,7 @@ def test_set_get_mono_range(self): def test_comlex_get(self): tReducer = self.reducer - van_rmm = tReducer.van_rmm; + van_rmm = tReducer.van_rmm self.assertEqual(50.9415,van_rmm) def test_comlex_set(self): @@ -154,7 +154,7 @@ def test_comlex_set(self): def test_set_format(self): tReducer = self.reducer - tReducer.save_format = ''; + tReducer.save_format = '' self.assertTrue(tReducer.save_format is None) #self.assertRaises(KeyError,tReducer.energy_bins=20,None) @@ -193,30 +193,27 @@ def test_get_parameter(self): def test_save_formats(self): - tReducer = self.reducer; + tReducer = self.reducer ws_name = '__empty_'+tReducer._instr_name pws = mtd[ws_name] - self.assertEqual(pws.name(),ws_name); + self.assertEqual(pws.name(),ws_name) self.assertTrue(tReducer.save_format is None) # do nothing tReducer.save_results(pws,'test_path') - tReducer.test_name=''; + tReducer.test_name='' def f_spe(workspace, filename): - tReducer.test_name += (workspace.name()+'_file_spe_' + filename) + tReducer.test_name += (workspace.name()+'_file_spe_' + filename) def f_nxspe(workspace, filename): - tReducer.test_name += (workspace.name()+'_file_nxspe_' + filename) + tReducer.test_name += (workspace.name()+'_file_nxspe_' + filename) def f_nxs(workspace, filename): - tReducer.test_name += (workspace.name()+'_file_nxs_' + filename) - + tReducer.test_name += (workspace.name()+'_file_nxs_' + filename) # redefine test save methors to produce test ouptut - tReducer._DirectEnergyConversion__save_formats['.spe']=lambda workspace,filename: f_spe(workspace,filename); - tReducer._DirectEnergyConversion__save_formats['.nxspe']=lambda workspace,filename : f_nxspe(workspace,filename); - tReducer._DirectEnergyConversion__save_formats['.nxs']=lambda workspace,filename : f_nxs(workspace,filename); - - + tReducer._DirectEnergyConversion__save_formats['.spe']=lambda workspace,filename: f_spe(workspace,filename) + tReducer._DirectEnergyConversion__save_formats['.nxspe']=lambda workspace,filename : f_nxspe(workspace,filename) + tReducer._DirectEnergyConversion__save_formats['.nxs']=lambda workspace,filename : f_nxs(workspace,filename) # set non-exisiting format tReducer.save_format = 'non-existing-format' @@ -228,62 +225,62 @@ def f_nxs(workspace, filename): tReducer.save_format = '.spe' self.assertEqual(tReducer.save_format,['.spe']) - tReducer.test_name=''; + tReducer.test_name='' tReducer.save_results(pws) self.assertEquals(ws_name+'_file_spe_'+ws_name+'.spe',tReducer.test_name) file_long_name = ws_name+'_file_spe_other_file_name.spe' - tReducer.test_name=''; + tReducer.test_name='' tReducer.save_results(pws,'other_file_name') self.assertEquals(file_long_name,tReducer.test_name) file_long_name=ws_name+'_file_nxspe_ofn.nxspe'+ws_name+'_file_nxs_ofn.nxs' - tReducer.test_name=''; + tReducer.test_name='' tReducer.save_results(pws,'ofn',['.nxspe','.nxs']) self.assertEquals(file_long_name,tReducer.test_name) #clear all previous default formats - tReducer.save_format=[]; + tReducer.save_format=[] self.assertTrue(tReducer.save_format is None) format_list = ['.nxspe','.nxs','.spe'] - file_long_name = ''; - tReducer.save_format = format_list; + file_long_name = '' + tReducer.save_format = format_list for i in xrange(len(format_list)): - self.assertEqual(tReducer.save_format[i],format_list[i]); - end = len(format_list[i]); + self.assertEqual(tReducer.save_format[i],format_list[i]) + end = len(format_list[i]) file_long_name+=ws_name+'_file_'+format_list[i][1:end]+'_ofn'+format_list[i] - tReducer.test_name=''; + tReducer.test_name='' tReducer.save_results(pws,'ofn') self.assertEquals(file_long_name,tReducer.test_name) def test_set_spectra_to_mon(self): - tReducer = self.reducer; + tReducer = self.reducer - self.assertTrue(tReducer.spectra_to_monitors_list is None); + self.assertTrue(tReducer.spectra_to_monitors_list is None) - tReducer.spectra_to_monitors_list = 35; - self.assertTrue(isinstance(tReducer.spectra_to_monitors_list,list)); - self.assertEquals(35,tReducer.spectra_to_monitors_list[0]); + tReducer.spectra_to_monitors_list = 35 + self.assertTrue(isinstance(tReducer.spectra_to_monitors_list,list)) + self.assertEquals(35,tReducer.spectra_to_monitors_list[0]) - tReducer.spectra_to_monitors_list = None; - self.assertTrue(tReducer.spectra_to_monitors_list is None); - tReducer.spectra_to_monitors_list = 'None'; - self.assertTrue(tReducer.spectra_to_monitors_list is None); - tReducer.spectra_to_monitors_list = []; - self.assertTrue(tReducer.spectra_to_monitors_list is None); + tReducer.spectra_to_monitors_list = None + self.assertTrue(tReducer.spectra_to_monitors_list is None) + tReducer.spectra_to_monitors_list = 'None' + self.assertTrue(tReducer.spectra_to_monitors_list is None) + tReducer.spectra_to_monitors_list = [] + self.assertTrue(tReducer.spectra_to_monitors_list is None) - tReducer.spectra_to_monitors_list = '467'; - self.assertEquals(467,tReducer.spectra_to_monitors_list[0]); + tReducer.spectra_to_monitors_list = '467' + self.assertEquals(467,tReducer.spectra_to_monitors_list[0]) - tReducer.spectra_to_monitors_list = '467,444'; - self.assertEquals(467,tReducer.spectra_to_monitors_list[0]); - self.assertEquals(444,tReducer.spectra_to_monitors_list[1]); + tReducer.spectra_to_monitors_list = '467,444' + self.assertEquals(467,tReducer.spectra_to_monitors_list[0]) + self.assertEquals(444,tReducer.spectra_to_monitors_list[1]) - tReducer.spectra_to_monitors_list = ['467','444']; - self.assertEquals(467,tReducer.spectra_to_monitors_list[0]); - self.assertEquals(444,tReducer.spectra_to_monitors_list[1]); + tReducer.spectra_to_monitors_list = ['467','444'] + self.assertEquals(467,tReducer.spectra_to_monitors_list[0]) + self.assertEquals(444,tReducer.spectra_to_monitors_list[1]) @@ -291,35 +288,35 @@ def test_set_spectra_to_mon(self): def test_process_copy_spectra_to_monitors(self): pass def test_set_get_ei_monitor(self): - tReducer = self.reducer; + tReducer = self.reducer self.assertEqual(41474,tReducer.ei_mon_spectra[0]) self.assertEqual(41475,tReducer.ei_mon_spectra[1]) # HOW TO MAKE IT WORK? it fails silently - # tReducer.ei_mon_spectra[1]=100; + # tReducer.ei_mon_spectra[1]=100 # self.assertEqual(41474,tReducer.ei_mon_spectra[0]) # self.assertEqual(100,tReducer.ei_mon_spectra[1]) - tReducer.ei_mon_spectra=[100,200]; + tReducer.ei_mon_spectra=[100,200] self.assertEqual(100,tReducer.ei_mon_spectra[0]) self.assertEqual(200,tReducer.ei_mon_spectra[1]) - tReducer.init_idf_params(True); + tReducer.init_idf_params(True) self.assertEqual(41474,tReducer.ei_mon_spectra[0]) self.assertEqual(41475,tReducer.ei_mon_spectra[1]) def test_load_monitors_with_workspacer(self): - tReducer =self.reducer; + tReducer =self.reducer self.assertFalse(tReducer.load_monitors_with_workspace) - tReducer.load_monitors_with_workspace=True; + tReducer.load_monitors_with_workspace=True self.assertTrue(tReducer.load_monitors_with_workspace) - tReducer.load_monitors_with_workspace=0; + tReducer.load_monitors_with_workspace=0 self.assertFalse(tReducer.load_monitors_with_workspace) - tReducer.load_monitors_with_workspace=10; + tReducer.load_monitors_with_workspace=10 self.assertTrue(tReducer.load_monitors_with_workspace) #def test_diag_call(self): @@ -331,4 +328,4 @@ def test_load_monitors_with_workspacer(self): if __name__=="__main__": - unittest.main() + unittest.main() diff --git a/Code/Mantid/scripts/test/DirectReductionHelpersTest.py b/Code/Mantid/scripts/test/DirectReductionHelpersTest.py index 9759ea4df4f7..016653ff3af1 100644 --- a/Code/Mantid/scripts/test/DirectReductionHelpersTest.py +++ b/Code/Mantid/scripts/test/DirectReductionHelpersTest.py @@ -1,26 +1,26 @@ import os -#os.environ["PATH"] = r"c:/Mantid/Code/builds/br_master/bin/Release;"+os.environ["PATH"] +#os.environ["PATH"] = r"c:/Mantid/Code/builds/br_master/bin/Release"+os.environ["PATH"] from mantid.simpleapi import * from mantid import api import unittest import Direct.ReductionHelpers as helpers class SomeDescriptor(object): - def __init__(self): - self._val=None + def __init__(self): + self._val=None - def __get__(self,instance,owner=None): - if instance is None: - return self + def __get__(self,instance,owner=None): + if instance is None: + return self - return self._val + return self._val - def __set__(self,instance,value): - self._val = value - def get_helper(self): - return "using helper" - def set_helper(self,value): - self._val=value + def __set__(self,instance,value): + self._val = value + def get_helper(self): + return "using helper" + def set_helper(self,value): + self._val=value @@ -35,42 +35,42 @@ def getInstrument(InstrumentName='MAR'): idf_file=api.ExperimentInfo.getInstrumentFilename(InstrumentName) tmp_ws_name = '__empty_' + InstrumentName if not mtd.doesExist(tmp_ws_name): - LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) - return mtd[tmp_ws_name].getInstrument(); + LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) + return mtd[tmp_ws_name].getInstrument() def test_build_subst_dictionary(self): - self.assertEqual(dict(), helpers.build_subst_dictionary("")) - self.assertEqual(dict(),helpers.build_subst_dictionary()) + self.assertEqual(dict(), helpers.build_subst_dictionary("")) + self.assertEqual(dict(),helpers.build_subst_dictionary()) - self.assertRaises(AttributeError,helpers.build_subst_dictionary,10) - self.assertRaises(AttributeError,helpers.build_subst_dictionary,"A=") - self.assertRaises(AttributeError,helpers.build_subst_dictionary,"B=C;A=") + self.assertRaises(AttributeError,helpers.build_subst_dictionary,10) + self.assertRaises(AttributeError,helpers.build_subst_dictionary,"A=") + self.assertRaises(AttributeError,helpers.build_subst_dictionary,"B=CA=") - rez=dict(); - rez['A']='B'; - self.assertEqual(rez, helpers.build_subst_dictionary(rez)) + rez=dict() + rez['A']='B' + self.assertEqual(rez, helpers.build_subst_dictionary(rez)) - myDict = helpers.build_subst_dictionary("A=B") - self.assertEqual(myDict['B'],'A') + myDict = helpers.build_subst_dictionary("A=B") + self.assertEqual(myDict['B'],'A') - myDict = helpers.build_subst_dictionary("A=B;C=DD") - self.assertEqual(myDict['B'],'A') - self.assertEqual(myDict['DD'],'C') - myDict = helpers.build_subst_dictionary("A=B=C=DD") - self.assertEqual(myDict['B'],'A') - self.assertEqual(myDict['DD'],'A') - self.assertEqual(myDict['C'],'A') + myDict = helpers.build_subst_dictionary("A=BC=DD") + self.assertEqual(myDict['B'],'A') + self.assertEqual(myDict['DD'],'C') + myDict = helpers.build_subst_dictionary("A=B=C=DD") + self.assertEqual(myDict['B'],'A') + self.assertEqual(myDict['DD'],'A') + self.assertEqual(myDict['C'],'A') - myDict = helpers.build_subst_dictionary("A = B = C=DD") - self.assertEqual(myDict['B'],'A') - self.assertEqual(myDict['DD'],'A') - self.assertEqual(myDict['C'],'A') + myDict = helpers.build_subst_dictionary("A = B = C=DD") + self.assertEqual(myDict['B'],'A') + self.assertEqual(myDict['DD'],'A') + self.assertEqual(myDict['C'],'A') def test_get_default_idf_param_list(self): - pInstr=self.getInstrument(); + pInstr=self.getInstrument() - param_list = helpers.get_default_idf_param_list(pInstr); + param_list = helpers.get_default_idf_param_list(pInstr) self.assertTrue(isinstance(param_list,dict)) # check couple of parameters which are certainly in IDF self.assertTrue('deltaE-mode' in param_list) @@ -79,31 +79,31 @@ def test_get_default_idf_param_list(self): def testbuild_properties_dict(self): - kkdict = {}; - kkdict['first']='kkk1:kkk2'; - kkdict['kkk1']=19; - kkdict['kkk2']=1000; - kkdict['other']='unrelated'; - kkdict['second']='ssss1:ssss2:third'; - kkdict['third']='Babara'; - - subst = {}; - subst['ssss1']='kkk1'; - subst['ssss2']='other'; + kkdict = {} + kkdict['first']='kkk1:kkk2' + kkdict['kkk1']=19 + kkdict['kkk2']=1000 + kkdict['other']='unrelated' + kkdict['second']='ssss1:ssss2:third' + kkdict['third']='Babara' + + subst = {} + subst['ssss1']='kkk1' + subst['ssss2']='other' subst_dict,descr = helpers.build_properties_dict(kkdict,subst) - self.assertEqual(len(subst_dict),6); + self.assertEqual(len(subst_dict),6) - val = subst_dict['_first']; + val = subst_dict['_first'] self.assertTrue(type(val) is helpers.ComplexProperty) - #self.assertEqual(val[0],'kkk1'); - #self.assertEqual(val[1],'kkk2'); + #self.assertEqual(val[0],'kkk1') + #self.assertEqual(val[1],'kkk2') val = subst_dict['other'] self.assertFalse(type(val) is helpers.ComplexProperty) - self.assertEqual(val,'unrelated'); + self.assertEqual(val,'unrelated') val = subst_dict['_second'] @@ -115,10 +115,10 @@ def testbuild_properties_dict(self): def testbuild_properties_dict_pref(self): - kkdict = {}; + kkdict = {} kkdict['first']='kkk1:kkk2' kkdict['kkk1']=19 - kkdict['kkk2']=1000; + kkdict['kkk2']=1000 kkdict['other']='unrelated' kkdict['second']='ssss1:ssss2:third' kkdict['third']='Babara' @@ -144,12 +144,12 @@ def testbuild_properties_dict_pref(self): val = prop_dict['_first'] self.assertTrue(type(val) is helpers.ComplexProperty) - #elf.assertEqual(val[0],'_kkk1'); - #self.assertEqual(val[1],'_kkk2'); + #elf.assertEqual(val[0],'_kkk1') + #self.assertEqual(val[1],'_kkk2') val = prop_dict['other'] self.assertFalse(type(val) is helpers.ComplexProperty) - self.assertEqual(val,'unrelated'); + self.assertEqual(val,'unrelated') val = prop_dict['_second'] self.assertTrue(type(val) is helpers.ComplexProperty) @@ -165,34 +165,34 @@ def testbuild_properties_dict_pref(self): def test_build_properties_dict_ksubst(self): - kkdict = {}; - kkdict['first']='kkk1:kkk2'; - kkdict['kkk1']=19; - kkdict['kkk2']=1000; - kkdict['other']='unrelated'; - kkdict['second']='ssss1:ssss2:third'; - kkdict['third']='Babara'; - - subst = {}; - subst['first']=1; - subst['ssss1']='kkk1'; - subst['ssss2']='other'; - subst['third']=3; - subst['second']=2; + kkdict = {} + kkdict['first']='kkk1:kkk2' + kkdict['kkk1']=19 + kkdict['kkk2']=1000 + kkdict['other']='unrelated' + kkdict['second']='ssss1:ssss2:third' + kkdict['third']='Babara' + + subst = {} + subst['first']=1 + subst['ssss1']='kkk1' + subst['ssss2']='other' + subst['third']=3 + subst['second']=2 subst_dict,descr_dict = helpers.build_properties_dict(kkdict,subst) - self.assertEqual(len(subst_dict),6); + self.assertEqual(len(subst_dict),6) val = subst_dict['_1'] self.assertTrue(type(val) is helpers.ComplexProperty) - #self.assertEqual(val[0],'kkk1'); - #self.assertEqual(val[1],'kkk2'); + #self.assertEqual(val[0],'kkk1') + #self.assertEqual(val[1],'kkk2') val = subst_dict['other'] self.assertFalse(type(val) is helpers.ComplexProperty) - self.assertEqual(val,'unrelated'); + self.assertEqual(val,'unrelated') val = subst_dict['_2'] self.assertTrue(type(val) is helpers.ComplexProperty) @@ -202,55 +202,55 @@ def test_build_properties_dict_ksubst(self): #self.assertEqual(val[2],'3') def test_gen_getter(self): - kkdict = {}; - kkdict['first']='kkk1:kkk2'; - kkdict['kkk1']=19; - kkdict['kkk2']=1000; - kkdict['other']='unrelated'; - kkdict['second']='ssss1:ssss2:third'; - kkdict['third']='Babara'; - - subst = {}; - subst['ssss1']='kkk1'; - subst['ssss2']='other'; + kkdict = {} + kkdict['first']='kkk1:kkk2' + kkdict['kkk1']=19 + kkdict['kkk2']=1000 + kkdict['other']='unrelated' + kkdict['second']='ssss1:ssss2:third' + kkdict['third']='Babara' + + subst = {} + subst['ssss1']='kkk1' + subst['ssss2']='other' subst_dict,descr = helpers.build_properties_dict(kkdict,subst) - self.assertEqual(helpers.gen_getter(subst_dict,'kkk1'),19); - self.assertEqual(helpers.gen_getter(subst_dict,'kkk2'),1000); - self.assertEqual(helpers.gen_getter(subst_dict,'first'),[19,1000]); - self.assertEqual(helpers.gen_getter(subst_dict,'other'),'unrelated'); - self.assertEqual(helpers.gen_getter(subst_dict,'second'),[19,'unrelated','Babara']); - self.assertEqual(helpers.gen_getter(subst_dict,'third'),'Babara'); + self.assertEqual(helpers.gen_getter(subst_dict,'kkk1'),19) + self.assertEqual(helpers.gen_getter(subst_dict,'kkk2'),1000) + self.assertEqual(helpers.gen_getter(subst_dict,'first'),[19,1000]) + self.assertEqual(helpers.gen_getter(subst_dict,'other'),'unrelated') + self.assertEqual(helpers.gen_getter(subst_dict,'second'),[19,'unrelated','Babara']) + self.assertEqual(helpers.gen_getter(subst_dict,'third'),'Babara') def test_gen_setter(self): - kkdict = {}; - kkdict['A']=helpers.ComplexProperty(['B','C']); - kkdict['B']=19; - kkdict['C']=1000; - + kkdict = {} + kkdict['A']=helpers.ComplexProperty(['B','C']) + kkdict['B']=19 + kkdict['C']=1000 + helpers.gen_setter(kkdict,'B',0) - self.assertEqual(kkdict['B'],0); + self.assertEqual(kkdict['B'],0) helpers.gen_setter(kkdict,'C',10) - self.assertEqual(kkdict['C'],10); + self.assertEqual(kkdict['C'],10) self.assertRaises(KeyError,helpers.gen_setter,kkdict,'A',100) - self.assertEqual(kkdict['B'],0); + self.assertEqual(kkdict['B'],0) helpers.gen_setter(kkdict,'A',[1,10]) - self.assertEqual(kkdict['B'],1); - self.assertEqual(kkdict['C'],10); + self.assertEqual(kkdict['B'],1) + self.assertEqual(kkdict['C'],10) def test_class_property_setter(self): - + class test_class(object): def __init__(self): object.__setattr__(self,'A',helpers.ComplexProperty(['B','C'])) #kkdict['A']= - kkdict = {}; - kkdict['B']=19; - kkdict['C']=1000; + kkdict = {} + kkdict['B']=19 + kkdict['C']=1000 self.__dict__.update(kkdict) oveloaded_prop = SomeDescriptor() @@ -269,130 +269,130 @@ def __setattr__(self,name,val): #object.__setattr__(self,name,val) return raise KeyError("Property {0} is not defined for class {1}".format(name,self.__class__)) - #helpers.gen_setter(self,name,val); + #helpers.gen_setter(self,name,val) #object.__setattr__(self,name,val) - + def __getattribute__(self,name): if name[:2] == '__': - attr = object.__getattribute__(self,name); + attr = object.__getattribute__(self,name) return attr else: - attr_dic = object.__getattribute__(self,'__dict__'); + attr_dic = object.__getattribute__(self,'__dict__') if name is '__dict__': - return attr_dic; + return attr_dic else: return helpers.gen_getter(attr_dic,name) pass - t1 =test_class(); + t1 =test_class() - self.assertEqual(t1.B,19); + self.assertEqual(t1.B,19) - t1.B=0; - self.assertEqual(t1.B,0); + t1.B=0 + self.assertEqual(t1.B,0) self.assertRaises(KeyError,setattr,t1,'non_existing_property','some value') - t1.A = [1,10]; - self.assertEqual(t1.A,[1,10]); + t1.A = [1,10] + self.assertEqual(t1.A,[1,10]) # This does not work as the assignment occurs to temporary vector # lets ban partial assignment - #t1.D[0] = 200; - #self.assertEqual(t1.B,200); - # This kind of assignment requests the whole list to be setup + #t1.D[0] = 200 + #self.assertEqual(t1.B,200) + # This kind of assignment requests the whole list to be setup self.assertRaises(KeyError,setattr,t1,'A',200) # Very bad -- fails silently - t1.A[0] = 10; - self.assertEqual(t1.A,[1,10]); + t1.A[0] = 10 + self.assertEqual(t1.A,[1,10]) t1.oveloaded_prop = 'BlaBla' #And this become too complicated:: to implement access to __class__.__dict__ - #self.assertEqual(t1.oveloaded_prop ,'BlaBla'); + #self.assertEqual(t1.oveloaded_prop ,'BlaBla') def test_class_property_setter2(self): class test_class(object): def __init__(self): - kkdict = {}; - kkdict['_A']=helpers.ComplexProperty(['B','C']); - kkdict['B']=19; - kkdict['C']=1000; - class_decor = '_'+type(self).__name__; + kkdict = {} + kkdict['_A']=helpers.ComplexProperty(['B','C']) + kkdict['B']=19 + kkdict['C']=1000 + class_decor = '_'+type(self).__name__ - kkdict[class_decor+'__special']='D'; + kkdict[class_decor+'__special']='D' self.__dict__.update(kkdict) some_descriptor = SomeDescriptor() def __setattr__(self,name,val): if name is 'special': - return; + return elif name in self.__class__.__dict__: fp = self.__class__.__dict__[name] fp.__set__(self,val) else: - helpers.gen_setter(self.__dict__,name,val); + helpers.gen_setter(self.__dict__,name,val) + - def __getattr__(self,name): if name is 'special': - return self.__special; + return self.__special else: - tDict = object.__getattribute__(self,'__dict__'); + tDict = object.__getattribute__(self,'__dict__') return helpers.gen_getter(tDict,name) - + def access(self,obj_name): - try: - obj = self.__class__.__dict__[obj_name] - return obj - except: - priv_name = '_'+obj_name - if priv_name in self.__dict__: - return self.__dict__[priv_name] - else: - raise KeyError("Property {0} is not among class descriptors or complex properties ".format(obj_name)) - + try: + obj = self.__class__.__dict__[obj_name] + return obj + except: + priv_name = '_'+obj_name + if priv_name in self.__dict__: + return self.__dict__[priv_name] + else: + raise KeyError("Property {0} is not among class descriptors or complex properties ".format(obj_name)) + t1 =test_class() - self.assertEqual(t1.B,19); + self.assertEqual(t1.B,19) - t1.B=0; - self.assertEqual(t1.B,0); + t1.B=0 + self.assertEqual(t1.B,0) self.assertRaises(KeyError,setattr,t1,'non_existing_property','some value') - t1.A = [1,10]; - self.assertEqual(t1.A,[1,10]); + t1.A = [1,10] + self.assertEqual(t1.A,[1,10]) # This does not work as the assignment occurs to temporary vector # lets ban partial assignment - #t1.D[0] = 200; - #self.assertEqual(t1.B,200); - # This kind of assignment requests the whole list to be setup + #t1.D[0] = 200 + #self.assertEqual(t1.B,200) + # This kind of assignment requests the whole list to be setup self.assertRaises(KeyError,setattr,t1,'A',200) # Very bad -- fails silently - t1.A[0] = 10; - self.assertEqual(t1.A,[1,10]); + t1.A[0] = 10 + self.assertEqual(t1.A,[1,10]) - t1.special = 10; - self.assertEqual(t1.special,'D'); + t1.special = 10 + self.assertEqual(t1.special,'D') t1.some_descriptor = 'blaBla' - self.assertEqual(t1.some_descriptor ,'blaBla'); + self.assertEqual(t1.some_descriptor ,'blaBla') - self.assertEqual(t1.access('some_descriptor').get_helper() ,'using helper'); + self.assertEqual(t1.access('some_descriptor').get_helper() ,'using helper') t1.access('some_descriptor').set_helper('other') - self.assertEqual(t1.some_descriptor ,'other'); + self.assertEqual(t1.some_descriptor ,'other') dep = t1.access('A').dependencies() self.assertEqual(dep[0],'B') @@ -406,14 +406,14 @@ def __init__(self): for meth in all_methods: if meth[:1] != '_': existing.append(meth) - kkdict = {}; - kkdict['_A']=helpers.ComplexProperty(['B','C']); - kkdict['B']=19; - kkdict['C']=1000; + kkdict = {} + kkdict['_A']=helpers.ComplexProperty(['B','C']) + kkdict['B']=19 + kkdict['C']=1000 - class_decor = '_'+type(self).__name__; + class_decor = '_'+type(self).__name__ object.__setattr__(self,class_decor+'__exmeth',existing) - + self.__dict__.update(kkdict) @@ -423,57 +423,57 @@ def __setattr__(self,name,val): if name in self.__exmeth: object.__setattr__(self,name,val) else: - helpers.gen_setter(self.__dict__,name,val); + helpers.gen_setter(self.__dict__,name,val) #raise KeyError("Property {0} is not among recognized properties".format(name)) def __getattr__(self,name): - return helpers.gen_getter(self.__dict__,name); + return helpers.gen_getter(self.__dict__,name) + - def access(self,obj_name): - try: - obj = self.__class__.__dict__[obj_name] - return obj - except: - priv_name = '_'+obj_name - if priv_name in self.__dict__: - return self.__dict__[priv_name] - else: - raise KeyError("Property {0} is not among class descriptors or complex properties ".format(obj_name)) - + try: + obj = self.__class__.__dict__[obj_name] + return obj + except: + priv_name = '_'+obj_name + if priv_name in self.__dict__: + return self.__dict__[priv_name] + else: + raise KeyError("Property {0} is not among class descriptors or complex properties ".format(obj_name)) + t1 =test_class() - self.assertEqual(t1.B,19); + self.assertEqual(t1.B,19) - t1.B=0; - self.assertEqual(t1.B,0); + t1.B=0 + self.assertEqual(t1.B,0) self.assertRaises(KeyError,setattr,t1,'non_existing_property','some value') - t1.A = [1,10]; - self.assertEqual(t1.A,[1,10]); + t1.A = [1,10] + self.assertEqual(t1.A,[1,10]) # This does not work as the assignment occurs to temporary vector # lets ban partial assignment - #t1.D[0] = 200; - #self.assertEqual(t1.B,200); - # This kind of assignment requests the whole list to be setup + #t1.D[0] = 200 + #self.assertEqual(t1.B,200) + # This kind of assignment requests the whole list to be setup self.assertRaises(KeyError,setattr,t1,'A',200) # Very bad -- fails silently - t1.A[0] = 10; - self.assertEqual(t1.A,[1,10]); + t1.A[0] = 10 + self.assertEqual(t1.A,[1,10]) t1.some_descriptor = 'blaBla' - self.assertEqual(t1.some_descriptor ,'blaBla'); + self.assertEqual(t1.some_descriptor ,'blaBla') self.assertEqual(t1.access('some_descriptor').get_helper() ,'using helper') t1.access('some_descriptor').set_helper('other') - self.assertEqual(t1.some_descriptor ,'other'); + self.assertEqual(t1.some_descriptor ,'other') dep = t1.access('A').dependencies() self.assertEqual(dep[0],'B') @@ -501,10 +501,7 @@ def test_split_file_name(self): self.assertEqual(len(nums),5) - -if __name__=="__main__": - unittest.main() - - +if __name__=="__main__": + unittest.main() diff --git a/Code/Mantid/scripts/test/MariReduction.py b/Code/Mantid/scripts/test/MariReduction.py index 4c7f2909eda2..44a63b6fa310 100644 --- a/Code/Mantid/scripts/test/MariReduction.py +++ b/Code/Mantid/scripts/test/MariReduction.py @@ -1,4 +1,4 @@ -""" Sample MARI reduction scrip used in testing ReductionWrapper """ +""" Sample MARI reduction scrip used in testing ReductionWrapper """ from Direct.ReductionWrapper import * try: @@ -11,49 +11,49 @@ class ReduceMARI(ReductionWrapper): #-------------------------------------------------------------------------------------------------# - @MainProperties - def def_main_properties(self): - """ Define main properties used in reduction """ - prop = {} - prop['sample_run'] = 11001 - prop['wb_run'] = 11060 - prop['incident_energy'] = 12 - prop['energy_bins'] = [-11,0.05,11] + @MainProperties + def def_main_properties(self): + """ Define main properties used in reduction """ + prop = {} + prop['sample_run'] = 11001 + prop['wb_run'] = 11060 + prop['incident_energy'] = 12 + prop['energy_bins'] = [-11,0.05,11] - # Absolute units reduction properties. - prop['monovan_run'] = 11015 - prop['sample_mass'] = 10 - prop['sample_rmm'] = 435.96 - return prop + # Absolute units reduction properties. + prop['monovan_run'] = 11015 + prop['sample_mass'] = 10 + prop['sample_rmm'] = 435.96 + return prop #-------------------------------------------------------------------------------------------------# - @AdvancedProperties - def def_advanced_properties(self): - """ separation between simple and advanced properties depends - on scientist, experiment and user. - main properties override advanced properties. - """ - prop = {} - prop['map_file'] = "mari_res.map" - prop['monovan_mapfile'] = "mari_res.map" - prop['hard_mask_file'] = "mar11015.msk" - prop['det_cal_file'] = "11060" - prop['save_format'] = '' - return prop + @AdvancedProperties + def def_advanced_properties(self): + """ separation between simple and advanced properties depends + on scientist, experiment and user. + main properties override advanced properties. + """ + prop = {} + prop['map_file'] = "mari_res.map" + prop['monovan_mapfile'] = "mari_res.map" + prop['hard_mask_file'] = "mar11015.msk" + prop['det_cal_file'] = "11060" + prop['save_format'] = '' + return prop # #-------------------------------------------------------------------------------------------------# - @iliad - def reduce(self,input_file=None,output_directory=None): - """ Method executes reduction over single file + @iliad + def reduce(self,input_file=None,output_directory=None): + """ Method executes reduction over single file - Overload only if custom reduction is needed - """ - ws = ReductionWrapper.reduce(input_file,output_directory) - #SaveNexus(ws,Filename = 'MARNewReduction.nxs') - return ws + Overload only if custom reduction is needed + """ + ws = ReductionWrapper.reduce(input_file,output_directory) + #SaveNexus(ws,Filename = 'MARNewReduction.nxs') + return ws - def __init__(self,web_var=None): - """ sets properties defaults for the instrument with Name""" - ReductionWrapper.__init__(self,'MAR',web_var) + def __init__(self,web_var=None): + """ sets properties defaults for the instrument with Name""" + ReductionWrapper.__init__(self,'MAR',web_var) #-------------------------------------------------------------------------------------------------# #-------------------------------------------------------------------------------------------------# #-------------------------------------------------------------------------------------------------# @@ -64,10 +64,10 @@ def main(input_file=None,output_directory=None): exception to change the output folder to save data to """ - # note web variables initialization + # note web variables initialization rd = ReduceMARI(web_var) rd.reduce(input_file,output_directory) - + # Define folder for web service to copy results to output_folder = '' return output_folder @@ -77,30 +77,30 @@ def main(input_file=None,output_directory=None): # SECTION USED TO RUN REDUCTION FROM MANTID SCRIPT WINDOW # #-------------------------------------------------------------------------------------------------# ##### Here one sets up folders where to find input data and where to save results ##### - # It can be done here or from Mantid GUI + # It can be done here or from Mantid GUI # Folder where map files are located: - map_mask_dir = 'd:/Data/MantidSystemTests/Data' + map_mask_dir = 'd:/Data/MantidSystemTests/Data' # folder where input data can be found - data_dir = 'd:/Data/Mantid_Testing/14_11_27' - # auxiliary folder with results - ref_data_dir = 'd:/Data/MantidSystemTests/SystemTests/AnalysisTests/ReferenceResults' - # Set input path to - config.setDataSearchDirs('{0};{1};{2}'.format(data_dir,map_mask_dir,ref_data_dir)) - # use appendDataSearch directory to add to existing data search path - #config.appendDataSearchDir('d:/Data/Mantid_GIT/Test/AutoTestData') - # folder to save resulting spe/nxspe files. - config['defaultsave.directory'] = data_dir + data_dir = 'd:/Data/Mantid_Testing/14_11_27' + # auxiliary folder with results + ref_data_dir = 'd:/Data/MantidSystemTests/SystemTests/AnalysisTests/ReferenceResults' + # Set input path to + config.setDataSearchDirs('{0};{1};{2}'.format(data_dir,map_mask_dir,ref_data_dir)) + # use appendDataSearch directory to add to existing data search path + #config.appendDataSearchDir('d:/Data/Mantid_GIT/Test/AutoTestData') + # folder to save resulting spe/nxspe files. + config['defaultsave.directory'] = data_dir ###### Initialize reduction class above and set up reduction properties. Note no parameters ###### - rd = ReduceMARI() - # set up advanced and main properties - rd.def_advanced_properties() - rd.def_main_properties() + rd = ReduceMARI() + # set up advanced and main properties + rd.def_advanced_properties() + rd.def_main_properties() - # uncomment rows below to save web variables to use in web services. - #run_dir = os.path.dirname(os.path.realpath(__file__)) - #file = os.path.join(run_dir,'reduce_vars.py') - #rd.save_web_variables(file) + # uncomment rows below to save web variables to use in web services. + #run_dir = os.path.dirname(os.path.realpath(__file__)) + #file = os.path.join(run_dir,'reduce_vars.py') + #rd.save_web_variables(file) - rd.reduce() + rd.reduce() diff --git a/Code/Mantid/scripts/test/ReductionSettingsTest.py b/Code/Mantid/scripts/test/ReductionSettingsTest.py index 3b4a2b51d0a4..ac4491750ad1 100644 --- a/Code/Mantid/scripts/test/ReductionSettingsTest.py +++ b/Code/Mantid/scripts/test/ReductionSettingsTest.py @@ -74,4 +74,5 @@ def test_clone_name_already_exists_is_cleared(self): self.assertFalse("a" in c) if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() + diff --git a/Code/Mantid/scripts/test/ReductionWrapperTest.py b/Code/Mantid/scripts/test/ReductionWrapperTest.py index ed8b1e042043..cda0accc84f1 100644 --- a/Code/Mantid/scripts/test/ReductionWrapperTest.py +++ b/Code/Mantid/scripts/test/ReductionWrapperTest.py @@ -20,7 +20,6 @@ class ReductionWrapperTest(unittest.TestCase): def __init__(self, methodName): return super(ReductionWrapperTest, self).__init__(methodName) - pass def setUp(self): pass @@ -80,5 +79,5 @@ def test_export_advanced_values(self): os.remove(fcomp) if __name__=="__main__": - unittest.main() + unittest.main() diff --git a/Code/Mantid/scripts/test/RunDescriptorTest.py b/Code/Mantid/scripts/test/RunDescriptorTest.py index 77a7ecb06a12..5ab61fe01be7 100644 --- a/Code/Mantid/scripts/test/RunDescriptorTest.py +++ b/Code/Mantid/scripts/test/RunDescriptorTest.py @@ -1,5 +1,5 @@ import os,sys,inspect -#os.environ["PATH"] = r"c:/Mantid/Code/builds/br_master/bin/Release;"+os.environ["PATH"] +#os.environ["PATH"] = r"c:/Mantid/Code/builds/br_master/bin/Release"+os.environ["PATH"] from mantid.simpleapi import * from mantid import api import unittest @@ -20,7 +20,7 @@ def __init__(self, methodName): def setUp(self): if self.prop_man == None or type(self.prop_man) != type(PropertyManager): - self.prop_man = PropertyManager("MAR"); + self.prop_man = PropertyManager("MAR") def tearDown(self): pass @@ -31,17 +31,17 @@ def getInstrument(InstrumentName='MAR'): idf_file=api.ExperimentInfo.getInstrumentFilename(InstrumentName) tmp_ws_name = '__empty_' + InstrumentName if not mtd.doesExist(tmp_ws_name): - LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) + LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) return mtd[tmp_ws_name].getInstrument() - + def test_descr_basic(self): propman = PropertyManager('MAR') self.assertTrue(propman.sample_run is None) self.assertTrue(PropertyManager.sample_run.get_workspace() is None) - - propman.sample_run = 10; + + propman.sample_run = 10 self.assertEqual(propman.sample_run,10) run_ws = CreateSampleWorkspace( Function='Multiple Peaks', NumBanks=1, BankPixelWidth=4, NumEvents=100) @@ -84,7 +84,7 @@ def test_find_file(self): # create two test files to check search for appropriate extension f=open(testFile1,'w') - f.write('aaaaaa'); + f.write('aaaaaa') f.close() f=open(testFile2,'w') @@ -118,8 +118,8 @@ def test_load_workspace(self): mon_ws = PropertyManager.sample_run.get_monitors_ws() self.assertTrue(isinstance(mon_ws, api.Workspace)) - self.assertEqual(mon_ws.name(),ws.name()) - + self.assertEqual(mon_ws.name(),ws.name()) + def test_copy_spectra2monitors(self): propman = self.prop_man run_ws = CreateSampleWorkspace( Function='Multiple Peaks', WorkspaceType = 'Event',NumBanks=1, BankPixelWidth=5, NumEvents=100) @@ -183,7 +183,7 @@ def test_ws_name(self): propman.sample_run = None self.assertFalse(ws_name+'_monitors' in mtd) - # name of empty property workspace + # name of empty property workspace self.assertEqual(PropertyManager.sample_run.get_ws_name(),'SR_') @@ -231,7 +231,7 @@ def test_sum_runs(self): self.assertEqual(ws.name(),ws_name) - + def test_assign_fname(self): propman = self.prop_man propman.sample_run = 'MAR11001.RAW' @@ -330,7 +330,7 @@ def test_chop_ws_part(self): api.AnalysisDataService.clear() - + if __name__=="__main__": unittest.main() diff --git a/Code/Mantid/scripts/test/SANSUtilitytests.py b/Code/Mantid/scripts/test/SANSUtilitytests.py index 764ab7cbc3f6..81ff7648cb09 100644 --- a/Code/Mantid/scripts/test/SANSUtilitytests.py +++ b/Code/Mantid/scripts/test/SANSUtilitytests.py @@ -6,7 +6,7 @@ class TestSliceStringParser(unittest.TestCase): def checkValues(self, list1, list2): def _check_single_values( v1, v2): - self.assertAlmostEqual(v1, v2) + self.assertAlmostEqual(v1, v2) self.assertEqual(len(list1), len(list2)) for v1,v2 in zip(list1, list2): From efcd9887655f064dfa6c99d17c8132326e5c96f0 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 23 Feb 2015 14:00:49 +0000 Subject: [PATCH 398/414] Refactor remaining scripts Refs #11144 --- .../ScalingFactorCalculation/sfCalculator.py | 4 ++-- .../scripts/LargeScaleStructures/geometry_writer.py | 3 ++- Code/Mantid/scripts/PyChop/fluxGUI.py | 10 ++++++++++ Code/Mantid/scripts/reducer_singleton.py | 4 ++-- Code/Mantid/scripts/reduction/__init__.py | 6 +++--- Code/Mantid/scripts/reduction/command_interface.py | 4 ++-- Code/Mantid/scripts/reduction/reducer.py | 6 +++--- .../scripts/reduction_workflow/command_interface.py | 4 ++-- 8 files changed, 26 insertions(+), 15 deletions(-) diff --git a/Code/Mantid/scripts/LargeScaleStructures/ScalingFactorCalculation/sfCalculator.py b/Code/Mantid/scripts/LargeScaleStructures/ScalingFactorCalculation/sfCalculator.py index 8fc284bffaec..03baa7e92672 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/ScalingFactorCalculation/sfCalculator.py +++ b/Code/Mantid/scripts/LargeScaleStructures/ScalingFactorCalculation/sfCalculator.py @@ -149,7 +149,7 @@ def _calculateFinalYAxis(self, bNumerator=True): ws_event_data = LoadEventNexus(Filename=nexus_file_numerator, OutputWorkspace='EventDataWks') mt1 = mtd['EventDataWks'] - + is_nexus_detector_rotated_flag = wks_utility.isNexusTakeAfterRefDate(ws_event_data.getRun().getProperty('run_start').value) if is_nexus_detector_rotated_flag: self.alpha_pixel_nbr = 304 @@ -376,7 +376,7 @@ def plotObject(instance): linestyle='', label='Exp. data') - if (instance.a is not None): + if instance.a is not None: x = linspace(10000, 22000, 100) _label = "%.3f + x*%.2e" % (instance.a, instance.b) plot(x, instance.a + instance.b * x, label=_label) diff --git a/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py b/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py index 97556c8b8122..d22a91ab2e2d 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py +++ b/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py @@ -2,7 +2,8 @@ from xml.dom.minidom import getDOMImplementation from datetime import datetime import re -class MantidGeom: + +class MantidGeom(object): def __init__(self, instname, valid_from=None): if valid_from is None: diff --git a/Code/Mantid/scripts/PyChop/fluxGUI.py b/Code/Mantid/scripts/PyChop/fluxGUI.py index 99fc48fc9e30..7f6444bff60c 100644 --- a/Code/Mantid/scripts/PyChop/fluxGUI.py +++ b/Code/Mantid/scripts/PyChop/fluxGUI.py @@ -13,6 +13,16 @@ class MainWindow(QtGui.QMainWindow): + flux_matrix = None + flux_energies = None + res_matrix = None + res_energies = None + frequencies = None + ei = None + ei_min = None + ei_max = None + interpolation = None + def __init__(self, parent=None): QtGui.QMainWindow.__init__(self,parent) self.ui = Ui_MainWindow() diff --git a/Code/Mantid/scripts/reducer_singleton.py b/Code/Mantid/scripts/reducer_singleton.py index fa786b1ac71b..5b2a860adff4 100644 --- a/Code/Mantid/scripts/reducer_singleton.py +++ b/Code/Mantid/scripts/reducer_singleton.py @@ -35,7 +35,7 @@ def execute(self, reducer, inputworkspace=None, outputworkspace=None): @param inputworkspace: Name of the workspace to apply this step to @param outputworkspace: Name of the workspace to have as an output. If this is None it will be set to inputworkspace """ - raise NotImplemented + raise NotImplementedError class Reducer(object): """ @@ -159,7 +159,7 @@ def reduce(self): -class ReductionSingleton: +class ReductionSingleton(object): """ Singleton reduction class """ ## storage for the instance reference diff --git a/Code/Mantid/scripts/reduction/__init__.py b/Code/Mantid/scripts/reduction/__init__.py index 1b13dcf29211..7093c3f8f1e8 100644 --- a/Code/Mantid/scripts/reduction/__init__.py +++ b/Code/Mantid/scripts/reduction/__init__.py @@ -1,3 +1,3 @@ -from reducer import * -from instrument import * -from find_data import find_data, find_file +from reduction.reducer import * +from reduction.instrument import * +from reduction.find_data import find_data, find_file diff --git a/Code/Mantid/scripts/reduction/command_interface.py b/Code/Mantid/scripts/reduction/command_interface.py index 8c48534ccdbb..ad07259ac804 100644 --- a/Code/Mantid/scripts/reduction/command_interface.py +++ b/Code/Mantid/scripts/reduction/command_interface.py @@ -3,9 +3,9 @@ List of user commands. """ -from reducer import Reducer +from reduction.reducer import Reducer -class ReductionSingleton: +class ReductionSingleton(object): """ Singleton reduction class """ ## storage for the instance reference diff --git a/Code/Mantid/scripts/reduction/reducer.py b/Code/Mantid/scripts/reduction/reducer.py index a8c388058e45..fa33ef3385d1 100644 --- a/Code/Mantid/scripts/reduction/reducer.py +++ b/Code/Mantid/scripts/reduction/reducer.py @@ -23,14 +23,14 @@ import time import types import inspect -from instrument import Instrument +from reduction.instrument import Instrument import mantid from mantid import simpleapi import warnings import inspect import random import string -from find_data import find_data +from reduction.find_data import find_data ## Version number @@ -538,7 +538,7 @@ def execute(self, reducer, inputworkspace=None, outputworkspace=None): @param inputworkspace: Name of the workspace to apply this step to @param outputworkspace: Name of the workspace to have as an output. If this is None it will be set to inputworkspace """ - raise NotImplemented + raise NotImplementedError def extract_workspace_name(filepath, suffix=''): diff --git a/Code/Mantid/scripts/reduction_workflow/command_interface.py b/Code/Mantid/scripts/reduction_workflow/command_interface.py index 3b18688874a0..6df622f1a156 100644 --- a/Code/Mantid/scripts/reduction_workflow/command_interface.py +++ b/Code/Mantid/scripts/reduction_workflow/command_interface.py @@ -3,9 +3,9 @@ List of user commands. """ -from reducer import Reducer +from reduction_workflow.reducer import Reducer -class ReductionSingleton: +class ReductionSingleton(object): """ Singleton reduction class """ ## storage for the instance reference From 313b67cfc0a25cf320935630a01430443e240ec5 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Mon, 23 Feb 2015 14:04:01 +0000 Subject: [PATCH 399/414] Re #7083 Get property value --- .../Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp index f8b4ed0d3f3b..3c158a3b403b 100644 --- a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp +++ b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp @@ -171,7 +171,7 @@ void PlotAsymmetryByLogValue::exec() { std::string firstFN = getProperty("FirstRun"); std::string lastFN = getProperty("LastRun"); // Get function to apply to logValue - m_logFunc = getProperty("Function"); + m_logFunc = getPropertyValue("Function"); // Parse run names and get the number of runs std::string fnBase, fnExt; From 3d7c8c1232da30fb9e5b478efb377dd32a66b3fe Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 23 Feb 2015 14:16:15 +0000 Subject: [PATCH 400/414] Fix broken unit test for direct reduction helper Refs #11144 --- .../scripts/test/DirectReductionHelpersTest.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Code/Mantid/scripts/test/DirectReductionHelpersTest.py b/Code/Mantid/scripts/test/DirectReductionHelpersTest.py index 016653ff3af1..e0878b314686 100644 --- a/Code/Mantid/scripts/test/DirectReductionHelpersTest.py +++ b/Code/Mantid/scripts/test/DirectReductionHelpersTest.py @@ -41,28 +41,28 @@ def getInstrument(InstrumentName='MAR'): def test_build_subst_dictionary(self): self.assertEqual(dict(), helpers.build_subst_dictionary("")) - self.assertEqual(dict(),helpers.build_subst_dictionary()) + self.assertEqual(dict(), helpers.build_subst_dictionary()) - self.assertRaises(AttributeError,helpers.build_subst_dictionary,10) - self.assertRaises(AttributeError,helpers.build_subst_dictionary,"A=") - self.assertRaises(AttributeError,helpers.build_subst_dictionary,"B=CA=") + self.assertRaises(AttributeError, helpers.build_subst_dictionary, 10) + self.assertRaises(AttributeError, helpers.build_subst_dictionary, "A=") + self.assertRaises(AttributeError, helpers.build_subst_dictionary, "B=C;A=") rez=dict() rez['A']='B' self.assertEqual(rez, helpers.build_subst_dictionary(rez)) - myDict = helpers.build_subst_dictionary("A=B") + myDict = helpers.build_subst_dictionary("A=B") self.assertEqual(myDict['B'],'A') - myDict = helpers.build_subst_dictionary("A=BC=DD") + myDict = helpers.build_subst_dictionary("A=B;C=DD") self.assertEqual(myDict['B'],'A') self.assertEqual(myDict['DD'],'C') - myDict = helpers.build_subst_dictionary("A=B=C=DD") + myDict = helpers.build_subst_dictionary("A=B=C=DD") self.assertEqual(myDict['B'],'A') self.assertEqual(myDict['DD'],'A') self.assertEqual(myDict['C'],'A') - myDict = helpers.build_subst_dictionary("A = B = C=DD") + myDict = helpers.build_subst_dictionary("A = B = C=DD") self.assertEqual(myDict['B'],'A') self.assertEqual(myDict['DD'],'A') self.assertEqual(myDict['C'],'A') From 91d9053169f668ebfb04ccdd739ea0d4c61ea377 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Mon, 23 Feb 2015 15:58:01 +0000 Subject: [PATCH 401/414] Re #10068 Search for first/last run in the other directory --- .../src/PlotAsymmetryByLogValue.cpp | 73 ++++++++++++++----- 1 file changed, 53 insertions(+), 20 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp index bc9cb6bda5c6..82ce4393460d 100644 --- a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp +++ b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp @@ -8,6 +8,7 @@ #include #include "MantidAPI/FileProperty.h" +#include #include "MantidAPI/Progress.h" #include "MantidAPI/ScopedWorkspace.h" #include "MantidAPI/TableRow.h" @@ -21,6 +22,7 @@ #include "MantidKernel/MandatoryValidator.h" #include "MantidKernel/PropertyWithValue.h" #include "MantidKernel/TimeSeriesProperty.h" +#include "Poco/File.h" #include #include @@ -353,34 +355,65 @@ void PlotAsymmetryByLogValue::populateOutputWorkspace (MatrixWorkspace_sptr &out void PlotAsymmetryByLogValue::parseRunNames (std::string& firstFN, std::string& lastFN, std::string& fnBase, std::string& fnExt) { - if ( firstFN.size() != lastFN.size() ) - { - throw std::runtime_error("First and last runs are not in the same directory\n"); - } - - fnExt = firstFN.substr(firstFN.find_last_of(".")); - + // Parse first run's name + std::string firstExt = firstFN.substr(firstFN.find_last_of(".")); firstFN.erase(firstFN.size() - 4); - lastFN.erase(lastFN.size() - 4); - fnBase = firstFN; - size_t i = fnBase.size() - 1; - while (isdigit(fnBase[i])) + std::string firstBase = firstFN; + size_t i = firstBase.size() - 1; + while (isdigit(firstBase[i])) i--; - if (i == fnBase.size() - 1) { + if (i == firstBase.size() - 1) { throw Exception::FileError("File name must end with a number.", firstFN); } - fnBase.erase(i + 1); + firstBase.erase(i + 1); + firstFN.erase(0, firstBase.size()); - std::string fnBase2 = lastFN; - fnBase2.erase(i + 1); - if ( fnBase != fnBase2 ) - { - throw std::runtime_error("First and last runs are not in the same directory\n"); + // Parse last run's name + std::string lastExt = lastFN.substr(lastFN.find_last_of(".")); + lastFN.erase(lastFN.size() - 4); + + std::string lastBase = lastFN; + i = lastBase.size() - 1; + while (isdigit(lastBase[i])) + i--; + if (i == lastBase.size() - 1) { + throw Exception::FileError("File name must end with a number.", lastFN); } + lastBase.erase(i + 1); + lastFN.erase(0, lastBase.size()); + + // Compare first and last + if ( firstBase != lastBase ) { + // Runs are not in the same directory + + // First run number with last base name + std::ostringstream tempFirst; + tempFirst << lastBase << firstFN << firstExt << std::endl; + std::string pathFirst = FileFinder::Instance().getFullPath(tempFirst.str()); + // Last run number with first base name + std::ostringstream tempLast; + tempLast << firstBase << lastFN << lastExt << std::endl; + std::string pathLast = FileFinder::Instance().getFullPath(tempLast.str()); + + // Try to correct this on the fly by + // checking if the last run can be found in the first directory... + if ( Poco::File(pathLast).exists() ) { + fnBase = firstBase; + fnExt = firstExt; + } else if (Poco::File(pathFirst).exists()) { + // ...or viceversa + fnBase = lastBase; + fnExt = lastExt; + } else { + throw std::runtime_error("First and last runs are not in the same directory."); + } + + } else { - firstFN.erase(0, fnBase.size()); - lastFN.erase(0, fnBase.size()); + fnBase = firstBase; + fnExt = firstExt; + } } /** Apply dead-time corrections. The calculation is done by ApplyDeadTimeCorr algorithm From dce28af9c3cedfb88bb58d9fa3aa0001d8454e9b Mon Sep 17 00:00:00 2001 From: Roman Tolchenov Date: Mon, 23 Feb 2015 16:30:50 +0000 Subject: [PATCH 402/414] Re #11160. Sleep for a second at the end of the script. --- Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst b/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst index 4aa18f206dd4..57b0f920bea2 100644 --- a/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst +++ b/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst @@ -197,7 +197,7 @@ Output: wsOut = mtd["wsOut"] print "The workspace contains %i periods" % wsOut.getNumberOfEntries() print "Each period contains %i spectra" % wsOut.getItem(0).getNumberHistograms() - + time.sleep(1) Output: From 76f41f097a4a96ca7f95163bffc1a131f57d64d2 Mon Sep 17 00:00:00 2001 From: Pete Peterson Date: Mon, 23 Feb 2015 11:50:23 -0500 Subject: [PATCH 403/414] Re #11161. Fixing gitignore --- Code/Mantid/Framework/Kernel/.gitignore | 3 +++ Code/Mantid/Framework/Kernel/src/.gitignore | 3 --- 2 files changed, 3 insertions(+), 3 deletions(-) create mode 100644 Code/Mantid/Framework/Kernel/.gitignore delete mode 100644 Code/Mantid/Framework/Kernel/src/.gitignore diff --git a/Code/Mantid/Framework/Kernel/.gitignore b/Code/Mantid/Framework/Kernel/.gitignore new file mode 100644 index 000000000000..0fee3cc6e352 --- /dev/null +++ b/Code/Mantid/Framework/Kernel/.gitignore @@ -0,0 +1,3 @@ +inc/MantidKernel/PocoVersion.h +src/MantidVersion.cpp +src/ParaViewVersion.cpp diff --git a/Code/Mantid/Framework/Kernel/src/.gitignore b/Code/Mantid/Framework/Kernel/src/.gitignore deleted file mode 100644 index a6ab44e00db2..000000000000 --- a/Code/Mantid/Framework/Kernel/src/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -MantidVersion.cpp -PocoVersion.h -ParaViewVersion.cpp From 6b872e4177bb4e8a99f8acb42f275fb562648521 Mon Sep 17 00:00:00 2001 From: Pete Peterson Date: Mon, 23 Feb 2015 12:21:10 -0500 Subject: [PATCH 404/414] Re #11159. Adding enviroment variable for qt. --- Code/Mantid/Build/CMake/Packaging/launch_mantidplot.sh.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Mantid/Build/CMake/Packaging/launch_mantidplot.sh.in b/Code/Mantid/Build/CMake/Packaging/launch_mantidplot.sh.in index 94ac4695d25a..33556e1b1c79 100644 --- a/Code/Mantid/Build/CMake/Packaging/launch_mantidplot.sh.in +++ b/Code/Mantid/Build/CMake/Packaging/launch_mantidplot.sh.in @@ -21,4 +21,4 @@ else fi # Launch -LD_PRELOAD=${LOCAL_PRELOAD} TCMALLOC_RELEASE_RATE=${TCM_RELEASE} LD_LIBRARY_PATH=${LOCAL_LDPATH} @WRAPPER_PREFIX@$INSTALLDIR/@MANTIDPLOT_EXEC@ $*@WRAPPER_POSTFIX@ +LD_PRELOAD=${LOCAL_PRELOAD} TCMALLOC_RELEASE_RATE=${TCM_RELEASE} LD_LIBRARY_PATH=${LOCAL_LDPATH} QT_API=pyqt @WRAPPER_PREFIX@$INSTALLDIR/@MANTIDPLOT_EXEC@ $*@WRAPPER_POSTFIX@ From 5523a659e87671d789378f7d2e0f7219c6380d2d Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Mon, 23 Feb 2015 17:41:11 +0000 Subject: [PATCH 405/414] Replace link that previously lead to a 404 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 71a05dea8d76..0057183c12e8 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Useful links ------------ * Homepage: http://www.mantidproject.org * Download: http://download.mantidproject.org - * Asking for help: http://download.mantidproject.org/webmailer/index.php + * Asking for help: http://www.mantidproject.org/Contact * Issue tracking: http://trac.mantidproject.org/mantid/ * Build server: http://builds.mantidproject.org * Developer site: http://developer.mantidproject.org From a29befa9d042870c5df4c66ab8b5ee316985c0a9 Mon Sep 17 00:00:00 2001 From: Vickie Lynch Date: Mon, 23 Feb 2015 15:52:13 -0500 Subject: [PATCH 406/414] Refs #11034 change structure of if tests --- .../Framework/MDEvents/src/IntegrateEllipsoids.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Code/Mantid/Framework/MDEvents/src/IntegrateEllipsoids.cpp b/Code/Mantid/Framework/MDEvents/src/IntegrateEllipsoids.cpp index c413ae0d2bd5..a6ce772e81bd 100644 --- a/Code/Mantid/Framework/MDEvents/src/IntegrateEllipsoids.cpp +++ b/Code/Mantid/Framework/MDEvents/src/IntegrateEllipsoids.cpp @@ -277,11 +277,12 @@ void IntegrateEllipsoids::exec() { axes_radii, inti, sigi); peaks[i].setIntensity(inti); peaks[i].setSigmaIntensity(sigi); - if (axes_radii.size() == 3 && (inti/sigi > cutoffIsigI || cutoffIsigI == EMPTY_DBL())) - { - principalaxis1.push_back(axes_radii[0]); - principalaxis2.push_back(axes_radii[1]); - principalaxis3.push_back(axes_radii[2]); + if (axes_radii.size() == 3) { + if (inti/sigi > cutoffIsigI || cutoffIsigI == EMPTY_DBL()){ + principalaxis1.push_back(axes_radii[0]); + principalaxis2.push_back(axes_radii[1]); + principalaxis3.push_back(axes_radii[2]); + } } } else { peaks[i].setIntensity(0.0); From c4a3184faad133b4a8e0550cd20c5b3eb5d0bb9f Mon Sep 17 00:00:00 2001 From: Pete Peterson Date: Mon, 23 Feb 2015 13:36:30 -0500 Subject: [PATCH 407/414] Re #1100. Updated cmake_mimimum_required --- Code/Mantid/CMakeLists.txt | 4 ++-- Code/Mantid/Framework/CMakeLists.txt | 2 +- .../MDEWRebinningCutterOperator/CMakeLists.txt | 2 +- Code/Mantid/Vates/VatesAPI/CMakeLists.txt | 2 +- .../Mantid/Vates/VatesSimpleGui/StandAloneExec/CMakeLists.txt | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Code/Mantid/CMakeLists.txt b/Code/Mantid/CMakeLists.txt index 2b79286d6eb5..ab8bbf7f3180 100644 --- a/Code/Mantid/CMakeLists.txt +++ b/Code/Mantid/CMakeLists.txt @@ -1,8 +1,8 @@ ########################################################################### # CMake version check. -# Only versions after 2.8.5 will find the HL component for HDF5 +# Only versions after 2.8.12 will find the HL component for HDF5 ########################################################################### -cmake_minimum_required ( VERSION 2.8.5 ) +cmake_minimum_required ( VERSION 2.8.12 ) # System package target is important for the windows builds as it allows us to package only the dlls and exes and exclude libs. Defaults to empty for other platforms. set ( SYSTEM_PACKAGE_TARGET "") diff --git a/Code/Mantid/Framework/CMakeLists.txt b/Code/Mantid/Framework/CMakeLists.txt index 03c5ab5792d2..630c149b4db8 100644 --- a/Code/Mantid/Framework/CMakeLists.txt +++ b/Code/Mantid/Framework/CMakeLists.txt @@ -1,5 +1,5 @@ # This is mainly here so you don't get a complaint when running cmake -cmake_minimum_required (VERSION 2.8.5) +cmake_minimum_required (VERSION 2.8.12) # Add the path to our custom 'find' modules set ( CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../Build/CMake") diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/MDEWRebinningCutterOperator/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/MDEWRebinningCutterOperator/CMakeLists.txt index de4001a08005..605bc5c0a1e6 100644 --- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/MDEWRebinningCutterOperator/CMakeLists.txt +++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/MDEWRebinningCutterOperator/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required( VERSION 2.6) +cmake_minimum_required( VERSION 2.8.12 ) project( MantidParaViewMDEWRebinningCutter ) add_paraview_plugin( MantidParaViewMDEWRebinningCutterSMPlugin "1.0" diff --git a/Code/Mantid/Vates/VatesAPI/CMakeLists.txt b/Code/Mantid/Vates/VatesAPI/CMakeLists.txt index 72465397a248..8384d524d947 100644 --- a/Code/Mantid/Vates/VatesAPI/CMakeLists.txt +++ b/Code/Mantid/Vates/VatesAPI/CMakeLists.txt @@ -1,5 +1,5 @@ # This is mainly here so you don't get a complaint when running cmake -cmake_minimum_required( VERSION 2.6 ) +cmake_minimum_required( VERSION 2.8.12 ) project( VatesAPI ) diff --git a/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/CMakeLists.txt b/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/CMakeLists.txt index 974b1551cf30..0b35b412adfe 100644 --- a/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/CMakeLists.txt +++ b/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required( VERSION 2.8 ) +cmake_minimum_required( VERSION 2.8.12 ) project( VatesSimpleGui ) set( PROJECT_NAME VatesSimpleGui ) From 519cca19201f4a9589aa4dc333ec06ef37b0bc59 Mon Sep 17 00:00:00 2001 From: Pete Peterson Date: Mon, 23 Feb 2015 14:22:27 -0500 Subject: [PATCH 408/414] Re #11000. Removing un-needed Find*.cmake files --- Code/Mantid/Build/CMake/FindMatlab.cmake | 57 ----- Code/Mantid/Build/CMake/FindPythonLibs.cmake | 218 ------------------- 2 files changed, 275 deletions(-) delete mode 100644 Code/Mantid/Build/CMake/FindMatlab.cmake delete mode 100644 Code/Mantid/Build/CMake/FindPythonLibs.cmake diff --git a/Code/Mantid/Build/CMake/FindMatlab.cmake b/Code/Mantid/Build/CMake/FindMatlab.cmake deleted file mode 100644 index 685006f10be6..000000000000 --- a/Code/Mantid/Build/CMake/FindMatlab.cmake +++ /dev/null @@ -1,57 +0,0 @@ -# Based upon FindMatlab.cmake from the CMake 2.8.3 distribution -# The script included with the distribution fails to find Matlab as it contains references -# to paths that no longer exist within Matlab - -# NOTE: Unsupported on Linux/Mac as I can't get a working version there to test it. Plus it was never built there before ... - -# Defines: -# MATLAB_INCLUDE_DIR: include path for mex.h, engine.h -# MATLAB_LIBRARIES: required libraries: libmex, etc -# MATLAB_MEX_LIBRARY: path to libmex.lib -# MATLAB_MX_LIBRARY: path to libmx.lib -# MATLAB_ENG_LIBRARY: path to libeng.lib - -if ( MATLAB_INCLUDE_DIR AND MATLAB_LIBRARIES ) - # Already in cache, be silent - set ( MATLAB_FOUND TRUE ) -endif () - -set ( MATLAB_FOUND FALSE ) -if ( WIN32 ) - # There seems to be know better way of querying the keys in the registry so we'll have to assume that all of the versions are 7.XX and search for these - set ( MATLAB_MAJOR_VERSION "7" ) - set ( REGISTRY_ROOT "HKEY_LOCAL_MACHINE\\SOFTWARE\\MathWorks\\MATLAB" ) - set ( REGISTRY_KEY "MATLABROOT" ) - set ( EXTERN_INCLUDE "/extern/include") - set ( EXTERN_SRC "/extern/src") - if( CMAKE_CL_64 ) - set( EXTERN_LIB "/extern/lib/win64/microsoft/" ) - else () - set( EXTERN_LIB "/extern/lib/win32/microsoft/" ) - endif () - # We'll assume we want to link to the oldest version so that it is most likely to be forward compatible. - # 2010 = 7.11 so stop at 15? - foreach ( MATLAB_MINOR_VERSION RANGE 1 15 ) - find_library ( MATLAB_MEX_LIBRARY libmex "[${REGISTRY_ROOT}\\${MATLAB_MAJOR_VERSION}.${MATLAB_MINOR_VERSION};${REGISTRY_KEY}]${EXTERN_LIB}" ) - find_library ( MATLAB_MX_LIBRARY libmx "[${REGISTRY_ROOT}\\${MATLAB_MAJOR_VERSION}.${MATLAB_MINOR_VERSION};${REGISTRY_KEY}]${EXTERN_LIB}" ) - find_library ( MATLAB_ENG_LIBRARY libeng "[${REGISTRY_ROOT}\\${MATLAB_MAJOR_VERSION}.${MATLAB_MINOR_VERSION};${REGISTRY_KEY}]${EXTERN_LIB}" ) - find_library ( MATLAB_MAT_LIBRARY libmat "[${REGISTRY_ROOT}\\${MATLAB_MAJOR_VERSION}.${MATLAB_MINOR_VERSION};${REGISTRY_KEY}]${EXTERN_LIB}" ) - set ( MATLAB_LIBRARIES ${MATLAB_MEX_LIBRARY} ${MATLAB_MX_LIBRARY} ${MATLAB_ENG_LIBRARY} ${MATLAB_MAT_LIBRARY} ) - find_path( MATLAB_INCLUDE_DIR "mex.h" "[${REGISTRY_ROOT}\\${MATLAB_MAJOR_VERSION}.${MATLAB_MINOR_VERSION};${REGISTRY_KEY}]${EXTERN_INCLUDE}" ) - find_path( MATLAB_EXTERN_SRC "mwdebug.c" "[${REGISTRY_ROOT}\\${MATLAB_MAJOR_VERSION}.${MATLAB_MINOR_VERSION};${REGISTRY_KEY}]${EXTERN_SRC}" ) - if ( MATLAB_INCLUDE_DIR AND MATLAB_LIBRARIES AND MATLAB_EXTERN_SRC ) - if ( NOT MATLAB_FIND_QUIETLY ) - message ( STATUS "Found Matlab: ${MATLAB_INCLUDE_DIR}" ) - endif () - set ( MATLAB_FOUND 1 ) - break () - endif () - endforeach ( MATLAB_MINOR_VERSION ) - - # Clean up temporary variables - set ( MATLAB_MAJOR_VERSION ) - set ( REGISTRY_ROOT ) - set ( REGISTRY_KEY ) - set ( EXTERN_INCLUDE ) - -endif () diff --git a/Code/Mantid/Build/CMake/FindPythonLibs.cmake b/Code/Mantid/Build/CMake/FindPythonLibs.cmake deleted file mode 100644 index acd7ff4ba5c3..000000000000 --- a/Code/Mantid/Build/CMake/FindPythonLibs.cmake +++ /dev/null @@ -1,218 +0,0 @@ -# Taken from the CMake 2.8.3 distribution -# Contains a fix to find the shared library on Linux, which isn't present -# in default Redhat CMake version (2.6.4) - -# - Find python libraries -# This module finds if Python is installed and determines where the -# include files and libraries are. It also determines what the name of -# the library is. This code sets the following variables: -# -# PYTHONLIBS_FOUND - have the Python libs been found -# PYTHON_LIBRARIES - path to the python library -# PYTHON_INCLUDE_PATH - path to where Python.h is found (deprecated) -# PYTHON_INCLUDE_DIRS - path to where Python.h is found -# PYTHON_DEBUG_LIBRARIES - path to the debug library -# - -#============================================================================= -# CMake - Cross Platform Makefile Generator -# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# * Neither the names of Kitware, Inc., the Insight Software Consortium, -# nor the names of their contributors may be used to endorse or promote -# products derived from this software without specific prior written -# permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#============================================================================= - -INCLUDE(CMakeFindFrameworks) -# Search for the python framework on Apple. -CMAKE_FIND_FRAMEWORKS(Python) - -FOREACH(_CURRENT_VERSION 2.7 2.6 2.5 2.4 2.3 2.2 2.1 2.0 1.6 1.5) - STRING(REPLACE "." "" _CURRENT_VERSION_NO_DOTS ${_CURRENT_VERSION}) - IF(WIN32) - FIND_LIBRARY(PYTHON_DEBUG_LIBRARY - NAMES python${_CURRENT_VERSION_NO_DOTS}_d python - PATHS - [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs/Debug - [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs - [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs/Debug - [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs"${CMAKE_LIBRARY_PATH}/Python"${_CURRENT_VERSION_NO_DOTS}) - ENDIF(WIN32) - - FIND_LIBRARY(PYTHON_LIBRARY - NAMES python${_CURRENT_VERSION_NO_DOTS} python${_CURRENT_VERSION} - PATHS - [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs - [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs - # Avoid finding the .dll in the PATH. We want the .lib. - NO_SYSTEM_ENVIRONMENT_PATH - ) - # Look for the static library in the Python config directory - FIND_LIBRARY(PYTHON_LIBRARY - NAMES python${_CURRENT_VERSION_NO_DOTS} python${_CURRENT_VERSION} - # Avoid finding the .dll in the PATH. We want the .lib. - NO_SYSTEM_ENVIRONMENT_PATH - # This is where the static library is usually located - PATH_SUFFIXES python${_CURRENT_VERSION}/config - ) - - # For backward compatibility, honour value of PYTHON_INCLUDE_PATH, if - # PYTHON_INCLUDE_DIR is not set. - IF(DEFINED PYTHON_INCLUDE_PATH AND NOT DEFINED PYTHON_INCLUDE_DIR) - SET(PYTHON_INCLUDE_DIR "${PYTHON_INCLUDE_PATH}" CACHE PATH - "Path to where Python.h is found" FORCE) - ENDIF(DEFINED PYTHON_INCLUDE_PATH AND NOT DEFINED PYTHON_INCLUDE_DIR) - - SET(PYTHON_FRAMEWORK_INCLUDES) - IF(Python_FRAMEWORKS AND NOT PYTHON_INCLUDE_DIR) - FOREACH(dir ${Python_FRAMEWORKS}) - SET(PYTHON_FRAMEWORK_INCLUDES ${PYTHON_FRAMEWORK_INCLUDES} - ${dir}/Versions/${_CURRENT_VERSION}/include/python${_CURRENT_VERSION}) - ENDFOREACH(dir) - ENDIF(Python_FRAMEWORKS AND NOT PYTHON_INCLUDE_DIR) - - FIND_PATH(PYTHON_INCLUDE_DIR - NAMES Python.h - PATHS - ${PYTHON_FRAMEWORK_INCLUDES} - [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/include - [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/include - PATH_SUFFIXES - python${_CURRENT_VERSION} - ) - - # For backward compatibility, set PYTHON_INCLUDE_PATH, but make it internal. - SET(PYTHON_INCLUDE_PATH "${PYTHON_INCLUDE_DIR}" CACHE INTERNAL - "Path to where Python.h is found (deprecated)") - -ENDFOREACH(_CURRENT_VERSION) - -MARK_AS_ADVANCED( - PYTHON_DEBUG_LIBRARY - PYTHON_LIBRARY - PYTHON_INCLUDE_DIR -) - -# We use PYTHON_INCLUDE_DIR, PYTHON_LIBRARY and PYTHON_DEBUG_LIBRARY for the -# cache entries because they are meant to specify the location of a single -# library. We now set the variables listed by the documentation for this -# module. -SET(PYTHON_INCLUDE_DIRS "${PYTHON_INCLUDE_DIR}") -SET(PYTHON_LIBRARIES "${PYTHON_LIBRARY}") -SET(PYTHON_DEBUG_LIBRARIES "${PYTHON_DEBUG_LIBRARY}") - - -INCLUDE(FindPackageHandleStandardArgs) -FIND_PACKAGE_HANDLE_STANDARD_ARGS(PythonLibs DEFAULT_MSG PYTHON_LIBRARIES PYTHON_INCLUDE_DIRS) - - -# PYTHON_ADD_MODULE( src1 src2 ... srcN) is used to build modules for python. -# PYTHON_WRITE_MODULES_HEADER() writes a header file you can include -# in your sources to initialize the static python modules -FUNCTION(PYTHON_ADD_MODULE _NAME ) - GET_PROPERTY(_TARGET_SUPPORTS_SHARED_LIBS - GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS) - OPTION(PYTHON_ENABLE_MODULE_${_NAME} "Add module ${_NAME}" TRUE) - OPTION(PYTHON_MODULE_${_NAME}_BUILD_SHARED - "Add module ${_NAME} shared" ${_TARGET_SUPPORTS_SHARED_LIBS}) - - # Mark these options as advanced - MARK_AS_ADVANCED(PYTHON_ENABLE_MODULE_${_NAME} - PYTHON_MODULE_${_NAME}_BUILD_SHARED) - - IF(PYTHON_ENABLE_MODULE_${_NAME}) - IF(PYTHON_MODULE_${_NAME}_BUILD_SHARED) - SET(PY_MODULE_TYPE MODULE) - ELSE(PYTHON_MODULE_${_NAME}_BUILD_SHARED) - SET(PY_MODULE_TYPE STATIC) - SET_PROPERTY(GLOBAL APPEND PROPERTY PY_STATIC_MODULES_LIST ${_NAME}) - ENDIF(PYTHON_MODULE_${_NAME}_BUILD_SHARED) - - SET_PROPERTY(GLOBAL APPEND PROPERTY PY_MODULES_LIST ${_NAME}) - ADD_LIBRARY(${_NAME} ${PY_MODULE_TYPE} ${ARGN}) -# TARGET_LINK_LIBRARIES(${_NAME} ${PYTHON_LIBRARIES}) - - IF(PYTHON_MODULE_${_NAME}_BUILD_SHARED) - SET_TARGET_PROPERTIES(${_NAME} PROPERTIES PREFIX "${PYTHON_MODULE_PREFIX}") - IF(WIN32 AND NOT CYGWIN) - SET_TARGET_PROPERTIES(${_NAME} PROPERTIES SUFFIX ".pyd") - ENDIF(WIN32 AND NOT CYGWIN) - ENDIF(PYTHON_MODULE_${_NAME}_BUILD_SHARED) - - ENDIF(PYTHON_ENABLE_MODULE_${_NAME}) -ENDFUNCTION(PYTHON_ADD_MODULE) - -FUNCTION(PYTHON_WRITE_MODULES_HEADER _filename) - - GET_PROPERTY(PY_STATIC_MODULES_LIST GLOBAL PROPERTY PY_STATIC_MODULES_LIST) - - GET_FILENAME_COMPONENT(_name "${_filename}" NAME) - STRING(REPLACE "." "_" _name "${_name}") - STRING(TOUPPER ${_name} _nameUpper) - - SET(_filenameTmp "${_filename}.in") - FILE(WRITE ${_filenameTmp} "/*Created by cmake, do not edit, changes will be lost*/\n") - FILE(APPEND ${_filenameTmp} -"#ifndef ${_nameUpper} -#define ${_nameUpper} - -#include - -#ifdef __cplusplus -extern \"C\" { -#endif /* __cplusplus */ - -") - - FOREACH(_currentModule ${PY_STATIC_MODULES_LIST}) - FILE(APPEND ${_filenameTmp} "extern void init${PYTHON_MODULE_PREFIX}${_currentModule}(void);\n\n") - ENDFOREACH(_currentModule ${PY_STATIC_MODULES_LIST}) - - FILE(APPEND ${_filenameTmp} -"#ifdef __cplusplus -} -#endif /* __cplusplus */ - -") - - - FOREACH(_currentModule ${PY_STATIC_MODULES_LIST}) - FILE(APPEND ${_filenameTmp} "int ${_name}_${_currentModule}(void) \n{\n static char name[]=\"${PYTHON_MODULE_PREFIX}${_currentModule}\"; return PyImport_AppendInittab(name, init${PYTHON_MODULE_PREFIX}${_currentModule});\n}\n\n") - ENDFOREACH(_currentModule ${PY_STATIC_MODULES_LIST}) - - FILE(APPEND ${_filenameTmp} "void ${_name}_LoadAllPythonModules(void)\n{\n") - FOREACH(_currentModule ${PY_STATIC_MODULES_LIST}) - FILE(APPEND ${_filenameTmp} " ${_name}_${_currentModule}();\n") - ENDFOREACH(_currentModule ${PY_STATIC_MODULES_LIST}) - FILE(APPEND ${_filenameTmp} "}\n\n") - FILE(APPEND ${_filenameTmp} "#ifndef EXCLUDE_LOAD_ALL_FUNCTION\nvoid CMakeLoadAllPythonModules(void)\n{\n ${_name}_LoadAllPythonModules();\n}\n#endif\n\n#endif\n") - -# with CONFIGURE_FILE() cmake complains that you may not use a file created using FILE(WRITE) as input file for CONFIGURE_FILE() - EXECUTE_PROCESS(COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_filenameTmp}" "${_filename}" OUTPUT_QUIET ERROR_QUIET) - -ENDFUNCTION(PYTHON_WRITE_MODULES_HEADER) From 5c8849fb29b1995ce198d4c0ce3e3abd665489a5 Mon Sep 17 00:00:00 2001 From: Raquel Alvarez Banos Date: Tue, 24 Feb 2015 08:41:42 +0000 Subject: [PATCH 409/414] Re #10068 Adding warning message --- .../Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp index 82ce4393460d..89c039cfa4cd 100644 --- a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp +++ b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp @@ -401,10 +401,14 @@ void PlotAsymmetryByLogValue::parseRunNames (std::string& firstFN, std::string& if ( Poco::File(pathLast).exists() ) { fnBase = firstBase; fnExt = firstExt; + g_log.warning() << "First and last run are not in the same directory. File " + << pathLast << " will be used instead." << std::endl; } else if (Poco::File(pathFirst).exists()) { // ...or viceversa fnBase = lastBase; fnExt = lastExt; + g_log.warning() << "First and last run are not in the same directory. File " + << pathFirst << " will be used instead." << std::endl; } else { throw std::runtime_error("First and last runs are not in the same directory."); } From ba8ef822e7ea4dfc573942700cfd6eb55415692c Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Tue, 24 Feb 2015 11:01:51 +0000 Subject: [PATCH 410/414] Fix broken indirect interfcaes Refs #11166 --- .../MantidQtCustomInterfaces/Indirect/ApplyCorr.ui | 2 +- .../CustomInterfaces/src/Indirect/ApplyCorr.cpp | 13 ++----------- .../MantidQt/CustomInterfaces/src/Indirect/Fury.cpp | 2 -- .../CustomInterfaces/src/Indirect/Quasi.cpp | 2 +- .../CustomInterfaces/src/Indirect/ResNorm.cpp | 2 +- .../CustomInterfaces/src/Indirect/Stretch.cpp | 2 +- 6 files changed, 6 insertions(+), 17 deletions(-) diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyCorr.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyCorr.ui index dff69d081f13..4c9363a65e14 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyCorr.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyCorr.ui @@ -97,7 +97,7 @@ - false + true diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ApplyCorr.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ApplyCorr.cpp index 2af7c0b021bc..7ca36c482874 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ApplyCorr.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ApplyCorr.cpp @@ -60,7 +60,7 @@ namespace IDA geom = "cyl"; } - QString pyInput = "from IndirectDataAnalysis import abscorFeeder, loadNexus\n"; + QString pyInput = "from IndirectDataAnalysis import abscorFeeder\n"; QString sample = m_uiForm.dsSample->getCurrentDataName(); MatrixWorkspace_const_sptr sampleWs = AnalysisDataService::Instance().retrieveWS(sample.toStdString()); @@ -102,16 +102,7 @@ namespace IDA { pyInput += "useCor = True\n"; QString corrections = m_uiForm.dsCorrections->getCurrentDataName(); - if ( !Mantid::API::AnalysisDataService::Instance().doesExist(corrections.toStdString()) ) - { - pyInput += - "corrections = loadNexus(r'" + m_uiForm.dsCorrections->getFullFilePath() + "')\n"; - } - else - { - pyInput += - "corrections = '" + corrections + "'\n"; - } + pyInput += "corrections = '" + corrections + "'\n"; } else { diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Fury.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Fury.cpp index c7c3867669e9..e131644b51ea 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Fury.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Fury.cpp @@ -105,7 +105,6 @@ namespace IDA furyAlg->setProperty("NumBins", numBins); furyAlg->setProperty("Plot", plot); - furyAlg->setProperty("Verbose", true); furyAlg->setProperty("Save", save); furyAlg->setProperty("DryRun", false); @@ -205,7 +204,6 @@ namespace IDA furyAlg->setProperty("NumBins", numBins); furyAlg->setProperty("Plot", false); - furyAlg->setProperty("Verbose", true); furyAlg->setProperty("Save", false); furyAlg->setProperty("DryRun", true); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp index aab618bf18e3..7cb65da529e0 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp @@ -190,7 +190,7 @@ namespace MantidQt pyInput += "QLRun('"+program+"','"+sampleName+"','"+resName+"','"+resNormFile+"',"+eRange+"," " "+nBins+","+fitOps+",'"+fixedWidthFile+"',"+sequence+", " - " Save="+save+", Plot='"+plot+"', Verbose=True)\n"; + " Save="+save+", Plot='"+plot+"')\n"; runPythonScript(pyInput); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ResNorm.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ResNorm.cpp index 354d1f50df9e..6cd8e4e43a6a 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ResNorm.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ResNorm.cpp @@ -97,7 +97,7 @@ namespace MantidQt QString plot = m_uiForm.cbPlot->currentText(); pyInput += "ResNormRun('"+VanName+"', '"+ResName+"', "+ERange+", "+nBin+"," - " Save="+save+", Plot='"+plot+"', Verbose=True)\n"; + " Save="+save+", Plot='"+plot+"')\n"; runPythonScript(pyInput); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp index 98a8c958ed76..78f13b6113eb 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp @@ -126,7 +126,7 @@ namespace MantidQt QString plot = m_uiForm.cbPlot->currentText(); pyInput += "QuestRun('"+sampleName+"','"+resName+"',"+betaSig+","+eRange+","+nBins+","+fitOps+","+sequence+"," - " Save="+save+", Plot='"+plot+"', Verbose=True)\n"; + " Save="+save+", Plot='"+plot+"')\n"; runPythonScript(pyInput); } From fce761a022b1d45c514b9c599095a6bb253f73a4 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Tue, 24 Feb 2015 11:51:44 +0000 Subject: [PATCH 411/414] Fix Docygen warnings in PreviewPlot Refs #11168 --- Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index 376582042ef4..5edd1d493f9b 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -194,7 +194,7 @@ QPair PreviewPlot::getCurveRange(const Mantid::API::MatrixWorksp /** * Gets the X range of a curve given its name. * - * @param wsName Name of curve + * @param curveName Name of curve */ QPair PreviewPlot::getCurveRange(const QString & curveName) { @@ -217,7 +217,7 @@ QPair PreviewPlot::getCurveRange(const QString & curveName) * Adds a workspace to the preview plot given a pointer to it. * * @param curveName Name of curve - * @param wsName Name of workspace in ADS + * @param ws Pointer to the workspace * @param specIndex Spectrum index to plot * @param curveColour Colour of curve to plot */ @@ -292,7 +292,7 @@ void PreviewPlot::removeSpectrum(const MatrixWorkspace_sptr ws) /** * Removes spectra from a gievn workspace from the plot given its name. * - * @param wsName Name of curve + * @param curveName Name of curve */ void PreviewPlot::removeSpectrum(const QString & curveName) { @@ -460,7 +460,7 @@ void PreviewPlot::hardReplot() * * Removes it from the plot (via removeSpectrum). * - * @param pNF Poco notification + * @param pNf Poco notification */ void PreviewPlot::handleRemoveEvent(WorkspacePreDeleteNotification_ptr pNf) { @@ -625,7 +625,7 @@ QString PreviewPlot::getAxisType(int axisID) /** * Gets a list of curve names that are plotted form the given workspace. * - * @param Pointer to workspace + * @param ws Pointer to workspace * @return List of curve names */ QStringList PreviewPlot::getCurvesForWorkspace(const MatrixWorkspace_sptr ws) From 57ba3aebdbae9c17407b2e74cce1a013978d5c26 Mon Sep 17 00:00:00 2001 From: Michael Wedel Date: Tue, 24 Feb 2015 13:39:42 +0100 Subject: [PATCH 412/414] Refs #11169. Fixing doxygen errors in PeakFunctionIntegrator. --- Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp b/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp index 75fcc48e3c40..b36896423ffc 100644 --- a/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp +++ b/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp @@ -12,7 +12,7 @@ namespace API { * See also PeakFunctionIntegrator::setRequiredRelativePrecision. * * @param requiredRelativePrecision :: Desired relative precision of the - *integral estimations. + * integral estimations. */ PeakFunctionIntegrator::PeakFunctionIntegrator(double requiredRelativePrecision) : m_integrationWorkspace(gsl_integration_workspace_alloc(1000)), @@ -69,6 +69,7 @@ IntegrationResult PeakFunctionIntegrator::integrateInfinity( * gsl_integration_qagiu is used for this. * * @param peakFunction :: Peak function to integrate. + * @param lowerLimit :: Lower limit of the integration. */ IntegrationResult PeakFunctionIntegrator::integratePositiveInfinity( const IPeakFunction &peakFunction, double lowerLimit) const { @@ -89,6 +90,7 @@ IntegrationResult PeakFunctionIntegrator::integratePositiveInfinity( * gsl_integration_qagil is used for this. * * @param peakFunction :: Peak function to integrate. + * @param upperLimit :: Upper limit of the integration. */ IntegrationResult PeakFunctionIntegrator::integrateNegativeInfinity( const IPeakFunction &peakFunction, double upperLimit) const { @@ -109,6 +111,8 @@ IntegrationResult PeakFunctionIntegrator::integrateNegativeInfinity( * gsl_integration_qags is used for this. * * @param peakFunction :: Peak function to integrate. + * @param lowerLimit :: Lower limit of the integration. + * @param upperLimit :: Upper limit of the integration. */ IntegrationResult PeakFunctionIntegrator::integrate(const IPeakFunction &peakFunction, From adc900f226f1b311b4f3d79cb5e056056c44bef4 Mon Sep 17 00:00:00 2001 From: Dan Nixon Date: Tue, 24 Feb 2015 13:58:21 +0000 Subject: [PATCH 413/414] Correct some spelling errors Refs #11168 --- .../MantidQt/MantidWidgets/src/PreviewPlot.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp index 5edd1d493f9b..b235a3935591 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -274,9 +274,9 @@ void PreviewPlot::addSpectrum(const QString & curveName, const QString & wsName, /** - * Removes spectra from a gievn workspace from the plot given a pointer to it. + * Removes spectra from a given workspace from the plot given a pointer to it. * - * If multiple curves are plotted form the smae workspace then all wil lbe removed. + * If multiple curves are plotted form the same workspace then all will be removed. * * @param ws Pointer to workspace */ @@ -290,7 +290,7 @@ void PreviewPlot::removeSpectrum(const MatrixWorkspace_sptr ws) /** - * Removes spectra from a gievn workspace from the plot given its name. + * Removes spectra from a given workspace from the plot given its name. * * @param curveName Name of curve */ @@ -316,7 +316,7 @@ void PreviewPlot::removeSpectrum(const QString & curveName) /** - * Checks to see if a given curne name is present on the plot. + * Checks to see if a given curve name is present on the plot. * * @param curveName Curve name * @return True if curve is on plot @@ -564,7 +564,7 @@ void PreviewPlot::removeCurve(QwtPlotCurve * curve) /** - * Helper function for adding a set of items to an exclusive menu oon the context menu. + * Helper function for adding a set of items to an exclusive menu on the context menu. * * @param menuName Name of sub menu * @param group Pointer to ActionGroup @@ -598,7 +598,7 @@ QList PreviewPlot::addOptionsToMenus(QString menuName, QActionGroup * /** - * Returns the type of axis scale specified for a giev axis. + * Returns the type of axis scale specified for a given axis. * * @param axisID ID of axis * @return Axis type as string From bc3e5e596faf8b9b390e1189f9cd686396d25ba8 Mon Sep 17 00:00:00 2001 From: Anders Markvardsen Date: Tue, 24 Feb 2015 15:07:38 +0000 Subject: [PATCH 414/414] Parameter name change. re #10987 --- .../src/TOFSANSResolutionByPixel.cpp | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/src/TOFSANSResolutionByPixel.cpp b/Code/Mantid/Framework/Algorithms/src/TOFSANSResolutionByPixel.cpp index bd062648c9c4..6b2cb131d0ce 100644 --- a/Code/Mantid/Framework/Algorithms/src/TOFSANSResolutionByPixel.cpp +++ b/Code/Mantid/Framework/Algorithms/src/TOFSANSResolutionByPixel.cpp @@ -3,14 +3,10 @@ //---------------------------------------------------------------------- #include "MantidAlgorithms/TOFSANSResolutionByPixel.h" #include "MantidAPI/WorkspaceValidators.h" -#include "MantidDataObjects/EventWorkspace.h" -#include "MantidDataObjects/EventList.h" #include "MantidDataObjects/Workspace2D.h" -#include "MantidKernel/RebinParamsValidator.h" #include "MantidKernel/ArrayProperty.h" -#include "MantidKernel/VectorHelper.h" -#include "MantidKernel/Interpolation.h" #include "MantidKernel/BoundedValidator.h" +#include "MantidKernel/Interpolation.h" #include "boost/math/special_functions/fpclassify.hpp" @@ -28,7 +24,7 @@ using namespace DataObjects; void TOFSANSResolutionByPixel::init() { declareProperty(new WorkspaceProperty<>( - "InputWorkspace", "", Direction::InOut, + "Workspace", "", Direction::InOut, boost::make_shared("Wavelength")), "Name the workspace to calculate the resolution for, for " "each pixel and wavelenght"); @@ -55,7 +51,7 @@ double TOFSANSResolutionByPixel::getTOFResolution(double wl) { } void TOFSANSResolutionByPixel::exec() { - MatrixWorkspace_sptr inOutWS = getProperty("InputWorkspace"); + MatrixWorkspace_sptr inOutWS = getProperty("Workspace"); double deltaR = getProperty("DeltaR"); double R1 = getProperty("SourceApertureRadius"); double R2 = getProperty("SampleApertureRadius"); @@ -99,9 +95,7 @@ void TOFSANSResolutionByPixel::exec() { const int numberOfSpectra = static_cast(inOutWS->getNumberHistograms()); Progress progress(this, 0.0, 1.0, numberOfSpectra); - // PARALLEL_FOR1(inOutWS) for (int i = 0; i < numberOfSpectra; i++) { - // PARALLEL_START_INTERUPT_REGION IDetector_const_sptr det; try { det = inOutWS->getDetector(i); @@ -109,11 +103,6 @@ void TOFSANSResolutionByPixel::exec() { g_log.information() << "Spectrum index " << i << " has no detector assigned to it - discarding" << std::endl; - // Catch if no detector. Next line tests whether this happened - test - // placed - // outside here because Mac Intel compiler doesn't like 'continue' in a - // catch - // in an openmp block. } // If no detector found or if it's masked or a monitor, skip onto the next // spectrum @@ -168,7 +157,6 @@ void TOFSANSResolutionByPixel::exec() { } progress.report("Computing Q resolution"); - // PARALLEL_END_INTERUPT_REGION } } } // namespace Algorithms