diff --git a/Code/Mantid/CMakeLists.txt b/Code/Mantid/CMakeLists.txt index 2b79286d6eb5..aa0093eee2df 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,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)," + "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() diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py index 4e8c1750c553..2d6ef948abd6 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py @@ -19,7 +19,8 @@ def PyInit(self): self.declareProperty(WorkspaceProperty('OutputWorkspace', '', optional=PropertyMode.Optional, direction=Direction.Output), - doc='Output resolution workspace (if left blank a name will be gernerated automatically)') + doc='Output resolution workspace (if left blank a name will ' + 'be gernerated automatically)') self.declareProperty(name='Instrument', defaultValue='', validator=StringListValidator(['IRIS', 'OSIRIS', 'TOSCA']), @@ -40,8 +41,6 @@ def PyInit(self): 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, @@ -77,11 +76,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) @@ -104,7 +98,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._plot = self.getProperty('Plot').value self._save = self.getProperty('Save').value @@ -122,9 +115,6 @@ def _post_process(self): 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', diff --git a/Code/Mantid/MantidPlot/CMakeLists.txt b/Code/Mantid/MantidPlot/CMakeLists.txt index 68daaff89d6f..63f091d4a3b0 100644 --- a/Code/Mantid/MantidPlot/CMakeLists.txt +++ b/Code/Mantid/MantidPlot/CMakeLists.txt @@ -880,6 +880,21 @@ 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 ########################################################################### @@ -887,7 +902,7 @@ copy_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} ${CONFIG_RESET_SCRIPT_FILE} ${MTDPLOT_FUTURE_INSTALL_FILES} ${IPYTHON_INSTALL_FILES} + ${PYTHON_INSTALL_FILES} ${MTDPLOT_INSTALL_FILES} ${CONFIG_RESET_SCRIPT_FILE} ${MTDPLOT_FUTURE_INSTALL_FILES} ${IPYTHON_INSTALL_FILES} ${SYSMON_INSTALL_FILES} ) # Library dependencies @@ -1035,6 +1050,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() install ( FILES ${CONFIG_RESET_SCRIPT} DESTINATION ${BIN_DIR} ) # file make_package.rb contains hard-coded path to the libraries @@ -1042,11 +1060,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 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..638813a2990d --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/SysMon.pyw @@ -0,0 +1,114 @@ +#!/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 new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/Code/Mantid/MantidPlot/SysMon/_version.py b/Code/Mantid/MantidPlot/SysMon/_version.py new file mode 100644 index 000000000000..b88b26dd7c4b --- /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.29" \ No newline at end of file diff --git a/Code/Mantid/MantidPlot/SysMon/config.py b/Code/Mantid/MantidPlot/SysMon/config.py new file mode 100644 index 000000000000..f52dcf1e520e --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/config.py @@ -0,0 +1,20 @@ + +#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 new file mode 100644 index 000000000000..33249856c52c --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/sysmon.py @@ -0,0 +1,272 @@ + + +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 new file mode 100644 index 000000000000..e0dc66da4615 --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/sysmon_tools.py @@ -0,0 +1,658 @@ +#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 new file mode 100644 index 000000000000..351c80dd4287 --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.py @@ -0,0 +1,390 @@ +# -*- 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 new file mode 100644 index 000000000000..265c066807af --- /dev/null +++ b/Code/Mantid/MantidPlot/SysMon/ui_sysmon.ui @@ -0,0 +1,735 @@ + + + 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 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 a13343453c9d..299958fd8dee 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -179,8 +179,9 @@ #include //Mantid -#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" @@ -438,6 +439,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(); @@ -568,7 +573,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); @@ -578,6 +583,54 @@ 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 @@ -641,13 +694,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; } @@ -1255,6 +1308,12 @@ 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); @@ -6114,7 +6173,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 { @@ -7118,7 +7177,7 @@ void ApplicationWindow::showGeneralPlotDialog() return; } if (ml && ml->layers()) - showPlotDialog(); + showPlotDialog(); } else if (plot->isA("Graph3D")) { @@ -7127,7 +7186,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"; @@ -7158,7 +7217,7 @@ void ApplicationWindow::showAxisDialog() return; } if (ml && ml->layers()) - dynamic_cast(gd)->showAxesPage(); + dynamic_cast(gd)->showAxesPage(); } else if (gd && plot->isA("Graph3D")) { @@ -11606,13 +11665,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; } @@ -14627,7 +14686,7 @@ bool ApplicationWindow::deleteFolder(Folder *f) auto newParent = dynamic_cast(currentFolder()->parent()); if(newParent) parent = newParent; - } + } } folders->blockSignals(true); @@ -15525,6 +15584,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 c984bd2ea01a..451818e34762 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.h +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.h @@ -226,7 +226,9 @@ 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); @@ -595,8 +597,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); @@ -1005,12 +1007,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(); @@ -1320,7 +1322,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; @@ -1354,7 +1356,8 @@ private slots: QString defaultScriptingLang; QDockWidget *m_interpreterDock; - + QDockWidget *m_sysMonitorDock; + QSet allCategories() const { return m_allCategories; } private: @@ -1400,7 +1403,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; @@ -1483,7 +1486,7 @@ private slots: QList d_user_actions; QList d_user_menus; //Mantid - + QList m_interfaceActions; /// list of mantidmatrix windows opened from project file. @@ -1502,7 +1505,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 e9434bad6802..4cbce1df41e6 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 ); m_appParent = parent; @@ -72,13 +71,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); @@ -198,7 +197,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())); @@ -683,7 +682,7 @@ void MantidDockWidget::filterWorkspaceTree(const QString &text) //show all items QTreeWidgetItemIterator it(m_tree); - while (*it) + while (*it) { (*it)->setHidden(false); ++it; @@ -706,7 +705,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); @@ -715,12 +714,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) @@ -771,10 +770,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 @@ -812,7 +811,7 @@ void MantidDockWidget::clickedWorkspace(QTreeWidgetItem* item, int) } void MantidDockWidget::workspaceSelected() -{ +{ QList selectedItems=m_tree->selectedItems(); if(selectedItems.isEmpty()) return; @@ -1077,7 +1076,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); @@ -1241,7 +1240,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); } @@ -1257,7 +1256,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); } @@ -1304,16 +1303,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 @@ -1530,11 +1529,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) @@ -1545,7 +1544,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 { @@ -1560,7 +1559,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(); @@ -1894,7 +1893,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); @@ -2007,4 +2005,3 @@ void AlgorithmDockWidget::hideProgressBar() //-------------------- ----------------------// - diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h b/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h index d776af0a3779..744af6c1eaf9 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,6 +314,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 @@ -484,11 +493,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; @@ -523,13 +532,6 @@ 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 2d12a0cb2431..a15734f9e842 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,6 +1207,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 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 9ef83b7f1d66..dff69d081f13 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 - - - + @@ -335,6 +319,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ConvFit.h index 39655a9a1a11..2c4c4959d4bc 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 @@ -32,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); @@ -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/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 3dde2bc260c4..a3ae0af137d7 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 + +
@@ -161,6 +172,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/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/IndirectCalibration.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.h index c01b42bbd5d2..295f3e5229b3 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectCalibration.h @@ -48,7 +48,7 @@ namespace CustomInterfaces virtual bool validate(); private slots: - void algorithmsComplete(bool error); + void algorithmComplete(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 0d29291d3f18..1c86fc8dab5d 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 +
@@ -108,7 +111,15 @@ - + + + + 255 + 255 + 255 + + +
@@ -161,6 +172,9 @@ 999.990000000000009 + + 1.0 +
@@ -168,7 +182,15 @@
- + + + + 255 + 255 + 255 + + + @@ -220,6 +242,12 @@ QWidget
MantidQtMantidWidgets/MWRunFiles.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDiagnostics.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectDiagnostics.ui index e4f7d8977f85..86d24761770d 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 + + + @@ -119,7 +127,15 @@ - + + + + 255 + 255 + 255 + + + @@ -173,6 +189,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 960ce84c3fc6..d31ce9b5b209 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 + + + @@ -117,54 +125,18 @@ 6 - - - - - - - - color: green; - - - M0 - - - - - - - color: black; - - - M2 - - - - - - - color: red; - - - M4 - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - + + + + 255 + 255 + 255 + + + + true + + @@ -213,6 +185,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSymmetrise.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectSymmetrise.ui index 0cea042c349f..8887984e52d0 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 + + + @@ -133,6 +149,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
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/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.ui index 38326cd9dfb5..d3f4ab2e34a3 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmission.ui @@ -104,55 +104,18 @@
- - - QLayout::SetMinimumSize + + + + 255 + 255 + 255 + + + + true - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - color: rgb(255, 0, 0); - - - Sample - - - - - - - Background - - - - - - - color: rgb(0, 255, 0); - - - Transmission - - - - + @@ -201,6 +164,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/JumpFit.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/JumpFit.ui index 70ac6bfe11e0..af311b1f8914 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 + + @@ -210,6 +173,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 5234f6acfb56..27cb65f3956a 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 - - - @@ -192,6 +186,9 @@ + + true + Plot Result @@ -231,6 +228,12 @@ QWidget
MantidQtMantidWidgets/DataSelector.h
+ + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Quasi.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Quasi.ui index a1f7399e41b1..99445c9c4c63 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); - - - @@ -419,6 +403,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 7ff51fa05f69..a948780a326c 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); - - - @@ -236,6 +230,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 f6110a32ae9f..a1c18fb09e45 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 + + @@ -249,6 +260,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 2f28cedf6e14..2af7c0b021bc 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() @@ -171,7 +162,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 @@ -256,33 +247,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/ConvFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ConvFit.cpp index cd4068268181..ebf92f8aec32 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 @@ -112,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); @@ -162,7 +159,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 +210,6 @@ namespace IDA */ bool ConvFit::validate() { - using Mantid::API::AnalysisDataService; - UserInputValidator uiv; uiv.checkDataSelectorIsValid("Sample", m_uiForm.dsSampleInput); @@ -250,7 +245,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; @@ -334,18 +329,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 +370,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 +398,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 +409,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 +426,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 +446,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 +476,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 +558,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(); @@ -690,10 +685,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); } @@ -709,21 +707,19 @@ 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*) + void ConvFit::plotGuess() { - if ( ! m_uiForm.ckPlotGuess->isChecked() || m_curves["CFDataCurve"] == NULL ) - { + 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); - Mantid::API::CompositeFunction_sptr function = createFunction(tieCentres); + CompositeFunction_sptr function = createFunction(tieCentres); if ( m_cfInputWS == NULL ) { @@ -750,8 +746,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 +758,18 @@ 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"); + + m_uiForm.ppPlot->addSpectrum("Guess", guessWs, 0, Qt::green); } void ConvFit::singleFit() @@ -778,15 +779,9 @@ namespace IDA plotInput(); - if ( m_curves["CFDataCurve"] == NULL ) - { - showMessageBox("There was an error reading the data file."); - return; - } - 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 +796,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()); @@ -821,12 +816,10 @@ 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); - 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/Elwin.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Elwin.cpp index d1d59ab7e27a..db1e27990a7c 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("Sample"); 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 12811b0e7ef9..c7c3867669e9 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))); @@ -247,10 +240,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&) { @@ -258,13 +251,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("Sample"); 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); @@ -305,8 +300,6 @@ namespace IDA //set default value for width m_dblManager->setValue(m_properties["EWidth"], 0.005); } - - replot("FuryPlot"); } catch(std::invalid_argument & exc) { diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/FuryFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/FuryFit.cpp index 39c20d54222e..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); @@ -690,15 +689,18 @@ 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); - replot("FuryFitPlot"); + 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"); + + m_uiForm.ppPlot->addSpectrum("Guess", guessWs, 0, Qt::green); } void FuryFit::fitContextMenu(const QPoint &) 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 b25f19b4a3de..4554eb11e15d 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 @@ -150,6 +136,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))); } //---------------------------------------------------------------------------------------------- @@ -165,8 +153,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(","); @@ -184,7 +170,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 +198,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"); @@ -224,10 +210,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"])); @@ -238,24 +220,60 @@ namespace CustomInterfaces QString background = QString::number(m_dblManager->value(m_properties["ResStart"])) + "," + QString::number(m_dblManager->value(m_properties["ResEnd"])); - Mantid::API::IAlgorithm_sptr resAlg = Mantid::API::AlgorithmManager::Instance().create("IndirectResolution", -1); + bool smooth = m_uiForm.ckSmoothResolution->isChecked(); + bool save = m_uiForm.ckSave->isChecked(); + + IAlgorithm_sptr resAlg = 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("ScaleFactor", m_uiForm.spScale->value()); - resAlg->setProperty("Smooth", m_uiForm.ckSmoothResolution->isChecked()); - resAlg->setProperty("Plot", m_uiForm.ckPlot->isChecked()); - resAlg->setProperty("Save", m_uiForm.ckSave->isChecked()); + resAlg->setProperty("Save", save); + + 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) + { + IAlgorithm_sptr smoothAlg = 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); + + if(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); + } + } + // When creating resolution file take the resolution workspace as the result m_pythonExportWsName = resolutionWsName.toStdString(); } @@ -263,19 +281,17 @@ namespace CustomInterfaces m_batchAlgoRunner->executeBatchAsync(); } - void IndirectCalibration::algorithmsComplete(bool error) + void IndirectCalibration::algorithmComplete(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))); + // 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() @@ -329,11 +345,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); } /** @@ -370,19 +386,20 @@ 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()); + QPair range(dataX.front(), dataX.back()); - plotMiniPlot(input, 0, "CalPlot", "CalCurve"); - setXAxisToCurve("CalPlot", "CalCurve"); + 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); - replot("CalPlot"); + m_uiForm.ppCalibration->replot(); //Also replot the energy calPlotEnergy(); @@ -437,16 +454,17 @@ 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); - plotMiniPlot(energyWs, 0, "ResPlot", "ResCurve"); - setXAxisToCurve("ResPlot", "ResCurve"); + m_uiForm.ppResolution->clear(); + m_uiForm.ppResolution->addSpectrum("Energy", energyWs, 0); + m_uiForm.ppResolution->resizeX(); calSetDefaultResolution(energyWs); - replot("ResPlot"); + m_uiForm.ppResolution->replot(); } /** @@ -455,7 +473,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"); @@ -474,13 +492,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 f28b6a39c66a..c773f40c4c8b 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectDiagnostics.cpp @@ -67,30 +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(); - - // 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 @@ -232,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())); } } @@ -275,15 +258,15 @@ 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()); - plotMiniPlot(input, 0, "SlicePlot"); - setXAxisToCurve("SlicePlot", "SlicePlot"); + 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); - replot("SlicePlot"); + m_uiForm.ppRawPlot->resizeX(); } else { @@ -425,11 +408,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("Slice", 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 a935563049b5..48f35777924b 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectMoments.cpp @@ -23,30 +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"]); - - // 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); @@ -132,10 +111,11 @@ namespace CustomInterfaces { disconnect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(updateProperties(QtProperty*, double))); - plotMiniPlot(filename, 0, "MomentsPlot", "MomentsPlotCurve"); - std::pair range = getCurveRange("MomentsPlotCurve"); - setMiniPlotGuides("MomentsRangeSelector", m_properties["EMin"], m_properties["EMax"], range); - setPlotRange("MomentsRangeSelector", m_properties["EMin"], m_properties["EMax"], range); + m_uiForm.ppRawPlot->clear(); + m_uiForm.ppRawPlot->addSpectrum("Raw", filename, 0); + 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))); @@ -248,16 +228,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("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(); } } // namespace CustomInterfaces diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/IndirectSymmetrise.cpp index 127f79f65539..177dd6e9e71f 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); } //---------------------------------------------------------------------------------------------- @@ -225,10 +204,8 @@ namespace CustomInterfaces updateMiniPlots(); // Set the preview range to the maximum absolute X value - auto axisRange = getCurveRange("SymmRawPlot"); + QPair axisRange = m_uiForm.ppRawPlot->getCurveRange("Raw"); 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); @@ -255,19 +232,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("Raw", 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("Raw"), QwtPlot::xBottom); + m_uiForm.ppPreviewPlot->replot(); } /** @@ -278,17 +250,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"]) { @@ -314,7 +275,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(); } @@ -445,7 +406,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("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/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 e0e414edb52c..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())); @@ -122,19 +115,12 @@ namespace CustomInterfaces if(resultWsNames.size() < 3) 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"); - - // 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_uiForm.ppPlot->clear(); + 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(); } void IndirectTransmission::instrumentSet() diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/JumpFit.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/JumpFit.cpp index c4e81ff4db66..5fa2ba6da67d 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 @@ -176,19 +169,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"); } /** @@ -233,18 +218,20 @@ 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]); + + 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 { @@ -328,7 +315,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 fc7b66de8a32..25b268e35b41 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))); @@ -143,13 +135,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->removeSpectrum("Fit"); + + // Plot the new fit + m_uiForm.ppPlot->addSpectrum("Fit", ws, 1, Qt::red); } } @@ -181,6 +175,8 @@ namespace IDA void MSDFit::plotInput() { + m_uiForm.ppPlot->clear(); + QString wsname = m_uiForm.dsSampleInput->getCurrentDataName(); if(!AnalysisDataService::Instance().doesExist(wsname.toStdString())) @@ -189,18 +185,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("Sample"); m_rangeSelectors["MSDRange"]->setRange(range.first, range.second); - - // Replot - replot("MSDPlot"); } catch(std::invalid_argument & exc) { @@ -208,10 +201,6 @@ namespace IDA } m_currentWsName = wsname; - - // Remove the old fit curve - removeCurve("MSDFitCurve"); - replot("MSDPlot"); } /** @@ -253,6 +242,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/CustomInterfaces/src/Indirect/Quasi.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Quasi.cpp index 8feaf67b9013..aab618bf18e3 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))); @@ -213,8 +206,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(); @@ -250,19 +245,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"); } /** @@ -276,12 +263,11 @@ 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"); - 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 110ad3c1de6a..354d1f50df9e 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(); @@ -109,10 +102,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); } /** @@ -135,9 +125,9 @@ 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); + 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); @@ -149,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); } /** @@ -207,15 +197,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 7ddd6e763ce2..98a8c958ed76 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/Stretch.cpp @@ -10,20 +10,14 @@ namespace MantidQt { namespace CustomInterfaces { - Stretch::Stretch(QWidget * parent) : + Stretch::Stretch(QWidget * parent) : IndirectBayesTab(parent) { 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))); @@ -35,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); @@ -69,7 +63,7 @@ namespace MantidQt /** * Validate the form to check the program can be run - * + * * @return :: Whether the form was valid */ bool Stretch::validate() @@ -92,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; @@ -101,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(); @@ -140,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) @@ -152,15 +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) { - plotMiniPlot(filename, 0, "StretchPlot", "RawPlotCurve"); - std::pair range = getCurveRange("RawPlotCurve"); - setMiniPlotGuides("StretchERange", m_properties["EMin"], m_properties["EMax"], range); - setPlotRange("StretchERange", m_properties["EMin"], m_properties["EMax"], range); + m_uiForm.ppPlot->addSpectrum("Sample", filename, 0); + 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); } /** @@ -180,7 +174,7 @@ namespace MantidQt */ void Stretch::maxValueChanged(double max) { - m_dblManager->setValue(m_properties["EMax"], max); + m_dblManager->setValue(m_properties["EMax"], max); } /** diff --git a/Code/Mantid/MantidQt/MantidWidgets/CMakeLists.txt b/Code/Mantid/MantidQt/MantidWidgets/CMakeLists.txt index 032cf36a0a2a..565630f797c6 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/CMakeLists.txt +++ b/Code/Mantid/MantidQt/MantidWidgets/CMakeLists.txt @@ -24,6 +24,7 @@ set ( SRC_FILES src/MuonFitPropertyBrowser.cpp src/MuonSequentialFitDialog.cpp src/PeakPicker.cpp + src/PreviewPlot.cpp src/ProcessingAlgoWidget.cpp src/PropertyHandler.cpp src/RangeSelector.cpp @@ -73,6 +74,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 @@ -120,6 +122,7 @@ set ( UI_FILES inc/MantidQtMantidWidgets/SlicingAlgorithmDialog.ui inc/MantidQtMantidWidgets/SlitCalculator.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 new file mode 100644 index 000000000000..13250323b045 --- /dev/null +++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/PreviewPlot.h @@ -0,0 +1,164 @@ +#ifndef MANTIDQTMANTIDWIDGETS_PREVIEWPLOT_H_ +#define MANTIDQTMANTIDWIDGETS_PREVIEWPLOT_H_ + +#include "ui_PreviewPlot.h" + +#include "WidgetDllOption.h" +#include "MantidQtAPI/MantidWidget.h" + +#include "MantidAPI/MatrixWorkspace.h" + +#include +#include +#include +#include + +#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 showLegend READ legendIsShown WRITE showLegend) + + public: + PreviewPlot(QWidget *parent = NULL, bool init = true); + virtual ~PreviewPlot(); + + QColor canvasColour(); + void setCanvasColour(const QColor & colour); + + bool legendIsShown(); + + void setAxisRange(QPair range, int axisID = QwtPlot::xBottom); + + QPair getCurveRange(const Mantid::API::MatrixWorkspace_sptr ws); + 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 & curveName); + + bool hasCurve(const QString & curveName); + + signals: + /// Signals that the plot should be refreshed + void needToReplot(); + void needToHardReplot(); + + public slots: + void showLegend(bool show); + void togglePanTool(bool enabled); + void toggleZoomTool(bool enabled); + void resetView(); + void resizeX(); + void clear(); + void replot(); + void hardReplot(); + + private: + /// Holds information about a plot curve + struct PlotCurveConfiguration + { + Mantid::API::MatrixWorkspace_sptr ws; + 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(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); + QStringList getCurvesForWorkspace(const Mantid::API::MatrixWorkspace_sptr ws); + + private slots: + void showContextMenu(QPoint position); + void handleViewToolSelect(); + void handleAxisTypeSelect(); + + private: + Ui::PreviewPlot m_uiForm; + + /// Poco Observers for ADS Notifications + Poco::NObserver m_removeObserver; + Poco::NObserver m_replaceObserver; + + /// If the widget was initialised + bool m_init; + + /// The plot its self + friend class RangeSelector; + + /// Map of curve key to plot info + QMap m_curves; + + /// Plot manipulation tools + QwtPlotMagnifier *m_magnifyTool; + QwtPlotPanner *m_panTool; + QwtPlotZoomer *m_zoomTool; + + /// Context menu items + QMenu *m_contextMenu; + QActionGroup *m_plotToolGroup; + QActionGroup *m_xAxisTypeGroup; + QActionGroup *m_yAxisTypeGroup; + + /// Menu action for showing/hiding plot legend + QAction *m_showLegendAction; + + }; + +} +} + +#endif //MANTIDQTMANTIDWIDGETS_PREVIEWPLOT_H_ 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/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/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp new file mode 100644 index 000000000000..376582042ef4 --- /dev/null +++ b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp @@ -0,0 +1,728 @@ +//------------------------------------------------------ +// Includes +//------------------------------------------------------ +#include "MantidQtMantidWidgets/PreviewPlot.h" + +#include "MantidAPI/AnalysisDataService.h" +#include "MantidAPI/AlgorithmManager.h" +#include "MantidQtAPI/QwtWorkspaceSpectrumData.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +#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), + m_removeObserver(*this, &PreviewPlot::handleRemoveEvent), + m_replaceObserver(*this, &PreviewPlot::handleReplaceEvent), + m_init(init), m_curves(), + m_magnifyTool(NULL), m_panTool(NULL), m_zoomTool(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); + } + + // Setup plot manipulation tools + m_zoomTool = new QwtPlotZoomer(QwtPlot::xBottom, QwtPlot::yLeft, + QwtPicker::DragSelection | QwtPicker::CornerToCorner, QwtPicker::AlwaysOff, m_uiForm.plot->canvas()); + m_zoomTool->setEnabled(false); + + m_panTool = new QwtPlotPanner(m_uiForm.plot->canvas()); + m_panTool->setEnabled(false); + + m_magnifyTool = new QwtPlotMagnifier(m_uiForm.plot->canvas()); + m_magnifyTool->setMouseButton(Qt::NoButton); + m_magnifyTool->setEnabled(false); + + // Handle showing the context menu + 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); + m_plotToolGroup->setExclusive(true); + + QStringList plotTools; + plotTools << "None" << "Pan" << "Zoom"; + 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 + 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); + + connect(this, SIGNAL(needToReplot()), this, SLOT(replot())); + connect(this, SIGNAL(needToHardReplot()), this, SLOT(hardReplot())); +} + + +/** + * Destructor + * + * Removes observers on the ADS. + */ +PreviewPlot::~PreviewPlot() +{ + if(m_init) + { + AnalysisDataService::Instance().notificationCenter.removeObserver(m_removeObserver); + AnalysisDataService::Instance().notificationCenter.removeObserver(m_replaceObserver); + } +} + + +/** + * Gets the background colour of the plot window. + * + * @return Plot canvas colour + */ +QColor PreviewPlot::canvasColour() +{ + return m_uiForm.plot->canvasBackground(); +} + + +/** + * Sets the background colour of the plot window. + * + * @param colour Plot canvas colour + */ +void PreviewPlot::setCanvasColour(const QColor & colour) +{ + m_uiForm.plot->setCanvasBackground(QBrush(colour)); +} + + +/** + * Checks to see if the plot legend is visible. + * + * @returns True if the legend is shown + */ +bool PreviewPlot::legendIsShown() +{ + return m_showLegendAction->isChecked(); +} + + +/** + * Sets the range of the given axis scale to a given range. + * + * @param range Pair of values for range + * @param axisID ID of axis + */ +void PreviewPlot::setAxisRange(QPair range, int axisID) +{ + if(range.first > range.second) + throw std::runtime_error("Supplied range is invalid."); + + m_uiForm.plot->setAxisScale(axisID, range.first, range.second); + emit needToReplot(); +} + + +/** + * 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_sptr ws) +{ + QStringList curveNames = getCurvesForWorkspace(ws); + + if(curveNames.size() == 0) + throw std::runtime_error("Curve for workspace not found."); + + return getCurveRange(curveNames[0]); +} + + +/** + * Gets the X range of a curve given its name. + * + * @param wsName Name of curve + */ +QPair PreviewPlot::getCurveRange(const QString & curveName) +{ + if(!m_curves.contains(curveName)) + throw std::runtime_error("Curve not on preview plot."); + + size_t numPoints = m_curves[curveName].curve->data().size(); + + if(numPoints < 2) + return qMakePair(0.0, 0.0); + + double low = m_curves[curveName].curve->data().x(0); + double high = m_curves[curveName].curve->data().x(numPoints - 1); + + return qMakePair(low, high); +} + + +/** + * 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 Spectrum index to plot + * @param curveColour Colour of curve to plot + */ +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); + + // Create the curve label + QLabel *label = new QLabel(curveName); + label->setVisible(false); + QPalette palette = label->palette(); + palette.setColor(label->foregroundRole(), curveColour); + label->setPalette(palette); + m_uiForm.loLegend->addWidget(label); + label->setVisible(legendIsShown()); + + 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(); +} + + +/** + * Adds a workspace to the preview plot given its name. + * + * @param curveName Name of curve + * @param wsName Name of workspace in ADS + * @param specIndex Spectrum index to plot + * @param curveColour Colour of curve to plot + */ +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(); + auto ws = AnalysisDataService::Instance().retrieveWS(wsName.toStdString()); + + if(!ws) + throw std::runtime_error(wsNameStr + " is not a MatrixWorkspace, not supported by PreviewPlot."); + + addSpectrum(curveName, ws, specIndex, curveColour); +} + + +/** + * 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) +{ + QStringList curveNames = getCurvesForWorkspace(ws); + + 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 curve + */ +void PreviewPlot::removeSpectrum(const QString & curveName) +{ + // Remove the curve object and legend label + if(m_curves.contains(curveName)) + { + 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); + + emit needToReplot(); +} + + +/** + * 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. + * + * @param show If the legend should be shown + */ +void PreviewPlot::showLegend(bool show) +{ + m_showLegendAction->setChecked(show); + + for(auto it = m_curves.begin(); it != m_curves.end(); ++it) + it.value().label->setVisible(show); +} + + +/** + * 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_uiForm.plot->setAxisAutoScale(QwtPlot::xBottom); + m_uiForm.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. + */ +void PreviewPlot::resizeX() +{ + double low = DBL_MAX; + double high = DBL_MIN; + + for(auto it = m_curves.begin(); it != m_curves.end(); ++it) + { + auto range = getCurveRange(it.key()); + + if(range.first < low) + low = range.first; + + if(range.second > high) + high = range.second; + } + + 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().curve); + m_uiForm.loLegend->removeWidget(it.value().label); + delete it.value().label; + } + + m_curves.clear(); + + emit needToReplot(); +} + + +/** + * Replots the curves shown on the plot. + */ +void PreviewPlot::replot() +{ + m_uiForm.plot->replot(); +} + + +/** + * Removes all curves and re-adds them. + */ +void PreviewPlot::hardReplot() +{ + QStringList keys = m_curves.keys(); + + for(auto it = keys.begin(); it != keys.end(); ++it) + { + removeCurve(m_curves[*it].curve); + m_curves[*it].curve = addCurve(m_curves[*it].ws, m_curves[*it].wsIndex, m_curves[*it].colour); + } + + emit needToReplot(); +} + + +/** + * Handle a workspace being deleted from ADS. + * + * Removes it from the plot (via removeSpectrum). + * + * @param pNF Poco notification + */ +void PreviewPlot::handleRemoveEvent(WorkspacePreDeleteNotification_ptr pNf) +{ + MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast(pNf->object()); + + // Ignore non matrix worksapces + if(!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) +{ + MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast(pNf->object()); + + // Ignore non matrix worksapces + if(!ws) + return; + + if(getCurvesForWorkspace(ws).size() > 0) + emit needToHardReplot(); +} + + +/** + * 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(MatrixWorkspace_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."); + + // 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); + curve->setPen(curveColour); + curve->attach(m_uiForm.plot); + + return curve; +} + + +/** + * 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; +} + + +/** + * 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, menu); + menuAction->setMenu(menu); + m_contextMenu->addAction(menuAction); + + return group->actions(); +} + + +/** + * 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; +} + + +/** + * 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. + * + * @param position Position at which to show menu + */ +void PreviewPlot::showContextMenu(QPoint position) +{ + // Show the context menu + m_contextMenu->popup(m_uiForm.plot->mapToGlobal(position)); +} + + +/** + * Handles the view tool being selected from the context menu. + */ +void PreviewPlot::handleViewToolSelect() +{ + 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); + } +} + + +/** + * Handles a change in the plot axis type. + */ +void PreviewPlot::handleAxisTypeSelect() +{ + // 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_uiForm.plot->setAxisScaleEngine(QwtPlot::xBottom, xEngine); + + if(yEngine) + m_uiForm.plot->setAxisScaleEngine(QwtPlot::yLeft, yEngine); + + // Update the plot + emit needToHardReplot(); +} diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/RangeSelector.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/RangeSelector.cpp index f4f6df930a45..30334d6da2cb 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_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() +{ + 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: 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 ----- 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 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. | +------------------+----------------------------------------------------------+